<?php
header('Content-Type: application/json');
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/config/db.php';

$response = ['status' => 'error', 'message' => 'Invalid action request.'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && isset($_POST['product_id'])) {
    $action = $_POST['action'];
    $product_id = intval($_POST['product_id']);
    
    // Verify product exists
    $stmt_check = $pdo->prepare("SELECT name FROM products WHERE id = ?");
    $stmt_check->execute([$product_id]);
    $product = $stmt_check->fetch();
    
    if (!$product) {
        echo json_encode(['status' => 'error', 'message' => 'Product does not exist.']);
        exit;
    }
    
    $wishlist_count = 0;
    
    if ($action === 'add') {
        if (isset($_SESSION['customer_id'])) {
            // DB Save for logged in customer
            try {
                $stmt_insert = $pdo->prepare("INSERT IGNORE INTO wishlist (user_id, product_id) VALUES (?, ?)");
                $stmt_insert->execute([$_SESSION['customer_id'], $product_id]);
                
                // Get updated count
                $stmt_count = $pdo->prepare("SELECT COUNT(*) FROM wishlist WHERE user_id = ?");
                $stmt_count->execute([$_SESSION['customer_id']]);
                $wishlist_count = $stmt_count->fetchColumn();
                
                $response = [
                    'status' => 'success',
                    'message' => htmlspecialchars($product['name']) . ' added to your private wishlist!',
                    'wishlist_count' => $wishlist_count
                ];
            } catch (Exception $e) {
                $response = ['status' => 'error', 'message' => 'Could not save item to database.'];
            }
        } else {
            // Guest Session Save
            if (!isset($_SESSION['wishlist'])) {
                $_SESSION['wishlist'] = [];
            }
            if (!in_array($product_id, $_SESSION['wishlist'])) {
                $_SESSION['wishlist'][] = $product_id;
            }
            $wishlist_count = count($_SESSION['wishlist']);
            
            $response = [
                'status' => 'success',
                'message' => htmlspecialchars($product['name']) . ' added to your wishlist! Sign in to save permanently.',
                'wishlist_count' => $wishlist_count
            ];
        }
    } elseif ($action === 'remove') {
        if (isset($_SESSION['customer_id'])) {
            // DB Delete
            try {
                $stmt_delete = $pdo->prepare("DELETE FROM wishlist WHERE user_id = ? AND product_id = ?");
                $stmt_delete->execute([$_SESSION['customer_id'], $product_id]);
                
                $stmt_count = $pdo->prepare("SELECT COUNT(*) FROM wishlist WHERE user_id = ?");
                $stmt_count->execute([$_SESSION['customer_id']]);
                $wishlist_count = $stmt_count->fetchColumn();
                
                $response = [
                    'status' => 'success',
                    'message' => 'Removed from your private wishlist.',
                    'wishlist_count' => $wishlist_count
                ];
            } catch (Exception $e) {
                $response = ['status' => 'error', 'message' => 'Could not delete item.'];
            }
        } else {
            // Session Delete
            if (isset($_SESSION['wishlist']) && is_array($_SESSION['wishlist'])) {
                $key = array_search($product_id, $_SESSION['wishlist']);
                if ($key !== false) {
                    unset($_SESSION['wishlist'][$key]);
                    $_SESSION['wishlist'] = array_values($_SESSION['wishlist']); // Reset array keys
                }
            }
            $wishlist_count = isset($_SESSION['wishlist']) ? count($_SESSION['wishlist']) : 0;
            
            $response = [
                'status' => 'success',
                'message' => 'Removed from your wishlist.',
                'wishlist_count' => $wishlist_count
            ];
        }
    }
}

echo json_encode($response);
exit;
?>
