<?php
/**
 * Wishlist API Endpoint
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/constants.php';
require_once __DIR__ . '/../includes/Database.php';
require_once __DIR__ . '/../includes/Auth.php';

header('Content-Type: application/json');

$auth = new Auth();
$db = Database::getInstance();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

$userId = $auth->getUserId();

if (!$userId) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Login required']);
    exit;
}

try {
    switch ($method) {
        case 'GET':
            // Get user wishlist
            $wishlist = $db->fetchAll(
                "SELECT w.*, p.name, p.slug, p.image, p.price, p.sale_price
                 FROM wishlist w
                 INNER JOIN products p ON w.product_id = p.id
                 WHERE w.user_id = ? AND p.is_active = 1
                 ORDER BY w.created_at DESC",
                [$userId]
            );
            
            echo json_encode(['success' => true, 'wishlist' => $wishlist]);
            break;

        case 'POST':
            $data = json_decode(file_get_contents('php://input'), true);
            
            if ($action === 'add') {
                $productId = $data['product_id'] ?? 0;
                
                // Check if already in wishlist
                $existing = $db->fetchOne(
                    "SELECT id FROM wishlist WHERE user_id = ? AND product_id = ?",
                    [$userId, $productId]
                );
                
                if ($existing) {
                    echo json_encode(['success' => false, 'message' => 'Product already in wishlist']);
                } else {
                    $db->execute(
                        "INSERT INTO wishlist (user_id, product_id) VALUES (?, ?)",
                        [$userId, $productId]
                    );
                    echo json_encode(['success' => true]);
                }
            } elseif ($action === 'remove') {
                $productId = $data['product_id'] ?? 0;
                $db->execute(
                    "DELETE FROM wishlist WHERE user_id = ? AND product_id = ?",
                    [$userId, $productId]
                );
                echo json_encode(['success' => true]);
            }
            break;

        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>

