<?php
require_once __DIR__ . '/../includes/config.php';
requireLogin();

$action = $_GET['action'] ?? '';
$user   = currentUser();

// ── GET actions (no CSRF needed for reads) ─────────────
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    switch ($action) {
        case 'get_deck':
            $deckId = (int)($_GET['deck_id'] ?? 0);
            if (!$deckId) jsonResponse(['success' => false, 'message' => 'Invalid deck_id'], 422);

            $ds = db()->prepare('SELECT id, title, difficulty, card_count FROM flashcard_decks WHERE id=? AND user_id=?');
            $ds->execute([$deckId, $user['id']]);
            $deck = $ds->fetch();
            if (!$deck) jsonResponse(['success' => false, 'message' => 'Deck not found'], 404);

            $cs = db()->prepare('SELECT id, question, answer, `order` FROM flashcards WHERE deck_id=? AND user_id=? ORDER BY `order`');
            $cs->execute([$deckId, $user['id']]);
            $cards = $cs->fetchAll();

            jsonResponse(['success' => true, 'title' => $deck['title'], 'difficulty' => $deck['difficulty'], 'cards' => $cards]);

        case 'list_decks':
            $ds = db()->prepare('SELECT id, title, difficulty, card_count, created_at FROM flashcard_decks WHERE user_id = ? ORDER BY created_at DESC');
            $ds->execute([$user['id']]);
            $decks = $ds->fetchAll();
            jsonResponse(['success' => true, 'decks' => $decks]);

        default:
            jsonResponse(['success' => false, 'message' => 'Unknown GET action'], 400);
    }
}

// ── POST actions ──────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['success' => false, 'message' => 'Method not allowed'], 405);
}

$body = json_decode(file_get_contents('php://input'), true) ?? [];

if (!verifyCsrf($body['csrf_token'] ?? '')) {
    jsonResponse(['success' => false, 'message' => 'Invalid CSRF token'], 403);
}

switch ($action) {
    case 'seen':
        $cardId = (int)($body['card_id'] ?? 0);
        if (!$cardId) jsonResponse(['success' => false, 'message' => 'Invalid card'], 422);
        db()->prepare('UPDATE flashcards SET times_seen = times_seen + 1, last_seen = NOW() WHERE id=? AND user_id=?')
            ->execute([$cardId, $user['id']]);
        jsonResponse(['success' => true]);

    case 'result':
        $cardId  = (int)($body['card_id'] ?? 0);
        $correct = (int)($body['correct'] ?? 0);
        if (!$cardId) jsonResponse(['success' => false, 'message' => 'Invalid card'], 422);
        if ($correct) {
            db()->prepare('UPDATE flashcards SET times_correct = times_correct + 1 WHERE id=? AND user_id=?')
                ->execute([$cardId, $user['id']]);
        }
        jsonResponse(['success' => true]);

    case 'delete_deck':
        $deckId = (int)($body['deck_id'] ?? 0);
        if (!$deckId) jsonResponse(['success' => false, 'message' => 'Invalid deck'], 422);
        $chk = db()->prepare('SELECT id FROM flashcard_decks WHERE id=? AND user_id=?');
        $chk->execute([$deckId, $user['id']]);
        if (!$chk->fetch()) jsonResponse(['success' => false, 'message' => 'Not found'], 404);
        db()->prepare('DELETE FROM flashcards WHERE deck_id=?')->execute([$deckId]);
        db()->prepare('DELETE FROM flashcard_decks WHERE id=?')->execute([$deckId]);
        jsonResponse(['success' => true]);

    default:
        jsonResponse(['success' => false, 'message' => 'Unknown action'], 400);
}
