<?php
/**
 * ============================================================
 * AJAX: Toggle Wishlist
 * ============================================================
 * Add or remove product from wishlist
 */

// Initialize
define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
require_once BASE_PATH . '/app/config/config.php';

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME);
    session_start();
}

// Must be AJAX POST
if (!isAjax() || !isPost()) {
    Response::error('Invalid request', [], 400);
}

// Validate CSRF
if (!csrf_validate()) {
    Response::csrfError();
}

// Must be logged in
if (!isLoggedIn()) {
    Response::unauthorized('উইশলিস্ট ব্যবহার করতে লগইন করুন');
}

$userId = getUserId();
$productId = (int)post('product_id');

if ($productId < 1) {
    Response::error('অবৈধ পণ্য');
}

// Check if product exists
$product = Database::fetchColumn("SELECT id FROM products WHERE id = ?", [$productId]);
if (!$product) {
    Response::error('পণ্য পাওয়া যায়নি');
}

// Check if already in wishlist
$exists = Database::fetchColumn(
    "SELECT id FROM wishlists WHERE user_id = ? AND product_id = ?",
    [$userId, $productId]
);

if ($exists) {
    // Remove from wishlist
    Database::execute(
        "DELETE FROM wishlists WHERE user_id = ? AND product_id = ?",
        [$userId, $productId]
    );
    
    Response::success('উইশলিস্ট থেকে সরানো হয়েছে', [
        'in_wishlist' => false
    ]);
} else {
    // Add to wishlist
    Database::insert(
        "INSERT INTO wishlists (user_id, product_id) VALUES (?, ?)",
        [$userId, $productId]
    );
    
    Response::success('উইশলিস্টে যোগ করা হয়েছে', [
        'in_wishlist' => true
    ]);
}
