<?php
/**
 * ============================================================================
 * api/toggle-favorite.php - Toggle Product Favorite API
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

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

// Check if user is logged in
if (!isLoggedIn()) {
    jsonError('Unauthorized', 401);
}

// Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonError('Method not allowed', 405);
}

$userId = getUserId();
$data = json_decode(file_get_contents('php://input'), true);
$productId = $data['product_id'] ?? null;

if (!$productId) {
    jsonError('Product ID required');
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Check if already favorited
    $sql = "SELECT id FROM favorites WHERE user_id = ? AND product_id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$userId, $productId]);
    $existing = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($existing) {
        // Remove from favorites
        $sql = "DELETE FROM favorites WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$existing['id']]);
        
        logActivity($userId, 'remove_favorite', "Removed product {$productId} from favorites");
        jsonSuccess('Removed from favorites', ['is_favorite' => false]);
    } else {
        // Add to favorites
        $sql = "INSERT INTO favorites (user_id, product_id) VALUES (?, ?)";
        $stmt = $db->prepare($sql);
        $stmt->execute([$userId, $productId]);
        
        logActivity($userId, 'add_favorite', "Added product {$productId} to favorites");
        jsonSuccess('Added to favorites', ['is_favorite' => true]);
    }
    
} catch (Exception $e) {
    logError('Favorite toggle error: ' . $e->getMessage());
    jsonError('Operation failed', 500);
}
?>