<?php
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db/config.php';

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

if (!is_logged_in()) {
    echo json_encode(['success' => false, 'message' => 'User not logged in']);
    exit;
}

$user_id = $_SESSION['user_id'];
$drill_id = isset($_POST['drill_id']) ? (int)$_POST['drill_id'] : null;
$session_id = isset($_POST['session_id']) ? (int)$_POST['session_id'] : null;

if (!$drill_id && !$session_id) {
    echo json_encode(['success' => false, 'message' => 'Drill or session ID required']);
    exit;
}

$pdo = db();

// Check if it's already a favorite
if ($drill_id) {
    $stmt = $pdo->prepare('SELECT id FROM user_favorites WHERE user_id = ? AND drill_id = ?');
    $stmt->execute([$user_id, $drill_id]);
} else {
    $stmt = $pdo->prepare('SELECT id FROM user_favorites WHERE user_id = ? AND training_session_id = ?');
    $stmt->execute([$user_id, $session_id]);
}

$is_favorite = $stmt->fetch();

try {
    if ($is_favorite) {
        // Remove from favorites
        if ($drill_id) {
            $stmt = $pdo->prepare('DELETE FROM user_favorites WHERE user_id = ? AND drill_id = ?');
            $stmt->execute([$user_id, $drill_id]);
        } else {
            $stmt = $pdo->prepare('DELETE FROM user_favorites WHERE user_id = ? AND training_session_id = ?');
            $stmt->execute([$user_id, $session_id]);
        }
        echo json_encode(['success' => true, 'status' => 'removed']);
    } else {
        // Add to favorites
        if ($drill_id) {
            $stmt = $pdo->prepare('INSERT INTO user_favorites (user_id, drill_id) VALUES (?, ?)');
            $stmt->execute([$user_id, $drill_id]);
        } else {
            $stmt = $pdo->prepare('INSERT INTO user_favorites (user_id, training_session_id) VALUES (?, ?)');
            $stmt->execute([$user_id, $session_id]);
        }
        echo json_encode(['success' => true, 'status' => 'added']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
