<?php
// ─── API DAILY ────────────────────────────────────────────────────────────────
// Routes :
//   POST /api/daily.php?action=answer          → enregistre réponse du jour
//   GET  /api/daily.php?action=status&day=N    → statut question du jour

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

require 'db.php';
require 'jwt_helper.php';

$action = $_GET['action'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];
$body   = json_decode(file_get_contents('php://input'), true) ?? [];

// ─── POST answer ──────────────────────────────────────────────────────────────
if ($action === 'answer' && $method === 'POST') {
    $userId  = requireAuth();
    $day     = (int)($body['day']     ?? 0);
    $correct = (bool)($body['correct'] ?? false);

    if (!$day) {
        http_response_code(400);
        echo json_encode(['message' => 'day requis']);
        exit;
    }

    $pdo->prepare("
        INSERT INTO daily_history (user_id, day, correct)
        VALUES (?, ?, ?)
        ON DUPLICATE KEY UPDATE correct = VALUES(correct)
    ")->execute([$userId, $day, $correct ? 1 : 0]);

    echo json_encode(['message' => 'Réponse enregistrée', 'day' => $day, 'correct' => $correct]);
    exit;
}

// ─── GET status ───────────────────────────────────────────────────────────────
if ($action === 'status' && $method === 'GET') {
    $userId = requireAuth();
    $day    = (int)($_GET['day'] ?? 0);

    if (!$day) {
        http_response_code(400);
        echo json_encode(['message' => 'day requis']);
        exit;
    }

    $stmt = $pdo->prepare("SELECT correct FROM daily_history WHERE user_id = ? AND day = ?");
    $stmt->execute([$userId, $day]);
    $row = $stmt->fetch();

    echo json_encode([
        'day'      => $day,
        'answered' => (bool)$row,
        'correct'  => $row ? (bool)$row['correct'] : null
    ]);
    exit;
}

http_response_code(404);
echo json_encode(['message' => 'Action inconnue']);
