<?php
header('Content-Type: application/json');
require_once '../includes/config.php';

$action = $_POST['action'] ?? $_GET['action'] ?? '';

// Add to Favorites
if ($action === 'add' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? '';
    $type = $_POST['type'] ?? 'movie';
    $title = $_POST['title'] ?? '';
    $posterPath = $_POST['poster_path'] ?? '';
    $rating = $_POST['rating'] ?? 0;
    
    if (empty($id)) {
        echo json_encode(['success' => false, 'message' => 'ID is required']);
        exit;
    }
    
    $_SESSION['favorites'][$id] = [
        'id' => $id,
        'type' => $type,
        'title' => $title,
        'poster_path' => $posterPath,
        'rating' => $rating,
        'added_at' => time()
    ];
    
    echo json_encode([
        'success' => true,
        'message' => 'Added to favorites',
        'count' => count($_SESSION['favorites'])
    ]);
    exit;
}

// Remove from Favorites
if ($action === 'remove' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? '';
    
    if (empty($id)) {
        echo json_encode(['success' => false, 'message' => 'ID is required']);
        exit;
    }
    
    if (isset($_SESSION['favorites'][$id])) {
        unset($_SESSION['favorites'][$id]);
        echo json_encode([
            'success' => true,
            'message' => 'Removed from favorites',
            'count' => count($_SESSION['favorites'])
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Item not found in favorites'
        ]);
    }
    exit;
}

// Check if item is in favorites
if ($action === 'check') {
    $id = $_GET['id'] ?? '';
    
    if (empty($id)) {
        echo json_encode(['success' => false, 'message' => 'ID is required']);
        exit;
    }
    
    $isFavorite = isset($_SESSION['favorites'][$id]);
    echo json_encode([
        'success' => true,
        'isFavorite' => $isFavorite
    ]);
    exit;
}

// Get favorites count
if ($action === 'count') {
    echo json_encode([
        'success' => true,
        'count' => count($_SESSION['favorites'] ?? [])
    ]);
    exit;
}

// Get all favorites
if ($action === 'list') {
    echo json_encode([
        'success' => true,
        'favorites' => array_values($_SESSION['favorites'] ?? [])
    ]);
    exit;
}

echo json_encode(['success' => false, 'message' => 'Invalid action']);
