<?php
// Don't include header.php as it outputs HTML
require_once 'includes/config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';

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

// Enable CORS for AJAX requests
header('Access-Control-Allow-Origin: ' . SITE_URL);
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); // Method Not Allowed
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

// Start session to check if user is logged in
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401); // Unauthorized
    echo json_encode(['success' => false, 'message' => 'You must be logged in to favorite products']);
    exit();
}

// Get POST data
$product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;

// Validate product ID
if ($product_id <= 0) {
    http_response_code(400); // Bad Request
    echo json_encode(['success' => false, 'message' => 'Invalid product ID']);
    exit();
}

try {
    // Check if product exists
    $product = getProductById($pdo, $product_id);
    if (!$product) {
        http_response_code(404); // Not Found
        echo json_encode(['success' => false, 'message' => 'Product not found']);
        exit();
    }
    
    // Check if already favorited
    $is_favorited = isProductFavorited($pdo, $_SESSION['user_id'], $product_id);
    
    if ($is_favorited) {
        // Remove from favorites
        if (removeFavorite($pdo, $_SESSION['user_id'], $product_id)) {
            $action = 'removed';
        } else {
            throw new Exception('Failed to remove product from favorites');
        }
    } else {
        // Add to favorites
        if (addFavorite($pdo, $_SESSION['user_id'], $product_id)) {
            $action = 'added';
        } else {
            throw new Exception('Failed to add product to favorites');
        }
    }
    
    // Get updated favorite count
    $favorite_count = getFavoriteCount($pdo, $product_id);
    
    // Return success response
    echo json_encode([
        'success' => true, 
        'action' => $action,
        'favorite_count' => $favorite_count,
        'message' => $action === 'added' ? 'Product added to favorites' : 'Product removed from favorites'
    ]);
    
} catch (Exception $e) {
    http_response_code(500); // Internal Server Error
    echo json_encode(['success' => false, 'message' => 'Error processing request: ' . $e->getMessage()]);
}
?>