<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';
startSecureSession();

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

if (!isCustomerLoggedIn()) {
  echo json_encode(['success' => false, 'error' => 'Not logged in', 'redirect' => '/customer/login.php']);
  exit;
}

$customer = getCurrentCustomer();
$custId = (int)$customer['id'];
$productId = (int)($_POST['product_id'] ?? $_GET['product_id'] ?? 0);

if (!$productId) {
  echo json_encode(['success' => false, 'error' => 'Invalid product']);
  exit;
}

$existing = Database::fetchOne("SELECT id FROM wishlist WHERE customer_id=? AND product_id=?", [$custId, $productId]);

if ($existing) {
  Database::execute("DELETE FROM wishlist WHERE customer_id=? AND product_id=?", [$custId, $productId]);
  echo json_encode(['success' => true, 'action' => 'removed', 'message' => 'Removed from wishlist']);
} else {
  Database::execute("INSERT INTO wishlist (customer_id, product_id, created_at) VALUES (?,?,NOW()) ON DUPLICATE KEY UPDATE created_at=NOW()", [$custId, $productId]);
  echo json_encode(['success' => true, 'action' => 'added', 'message' => 'Saved to wishlist']);
}
