<?php
require_once '../config/cors.php';
require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

$method = $_SERVER['REQUEST_METHOD'];

if ($method !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

$data = json_decode(file_get_contents("php://input"));

if (!isset($data->userId) || !isset($data->productId)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'User ID and Product ID are required']);
    exit();
}

$userId = $data->userId;
$productId = $data->productId;

try {
    // Check if product exists
    $checkProduct = "SELECT id FROM products WHERE id = ?";
    $stmt = $db->prepare($checkProduct);
    $stmt->bindParam(1, $productId);
    $stmt->execute();

    if ($stmt->rowCount() === 0) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Product not found']);
        exit();
    }
    
    // Ensure user has a wishlist
    $checkWishlist = "SELECT id FROM wishlists WHERE user_id = ?";
    $stmt = $db->prepare($checkWishlist);
    $stmt->bindParam(1, $userId);
    $stmt->execute();

    if ($stmt->rowCount() === 0) {
        $createWishlist = "INSERT INTO wishlists (user_id) VALUES (?)";
        $stmt = $db->prepare($createWishlist);
        $stmt->bindParam(1, $userId);
        $stmt->execute();
        $wishlistId = $db->lastInsertId();
    } else {
        $wishlist = $stmt->fetch(PDO::FETCH_ASSOC);
        $wishlistId = $wishlist['id'];
    }

    // Check if item is already in wishlist
    $checkExisting = "SELECT id FROM wishlist_items WHERE wishlist_id = ? AND product_id = ?";
    $stmt = $db->prepare($checkExisting);
    $stmt->bindParam(1, $wishlistId);
    $stmt->bindParam(2, $productId);
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
        http_response_code(409);
        echo json_encode(['success' => false, 'message' => 'Product already in wishlist']);
        exit();
    }

    // Add to wishlist
    $variantId = isset($data->variantId) ? $data->variantId : null;
    $query = "INSERT INTO wishlist_items (wishlist_id, product_id, variant_id, created_at) VALUES (?, ?, ?, NOW())";
    
    $stmt = $db->prepare($query);
    $stmt->bindParam(1, $wishlistId);
    $stmt->bindParam(2, $productId);
    $stmt->bindParam(3, $variantId);

    if ($stmt->execute()) {
        $newItemId = $db->lastInsertId();
        http_response_code(201);
        echo json_encode([
            'success' => true, 
            'message' => 'Product added to wishlist',
            'id' => $newItemId,
            'wishlist_id' => $newItemId
        ]);
    } else {
        throw new Exception('Failed to add to wishlist');
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal server error: ' . $e->getMessage()]);
}