<?php


$appName = 'mondialisa';
session_name($appName);
session_start();

require_once 'config.inc.php';



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

if (!isset($_SESSION['user']['ref'])) {
    echo json_encode(['success' => false, 'error' => 'unauthorized']);
    exit;
}

$user_ref = $_SESSION['user']['ref'];
$fullname = $_SESSION['user']['firstname'].' '.$_SESSION['user']['lastname'] ?? 'Apprenant';

/* ---------- Lire JSON ---------- */
$input = json_decode(file_get_contents('php://input'), true);

if (
    !$input ||
    empty($input['formation_ref']) ||
    empty($input['answers'])
) {
    echo json_encode(['success' => false, 'error' => 'invalid_payload']);
    exit;
}

$formation_ref = $input['formation_ref'];
$answers       = $input['answers']; // [question_id => optionX]

/* ---------- Charger bonnes réponses ---------- */
$ids = array_keys($answers);
$placeholders = implode(',', array_fill(0, count($ids), '?'));

$sql = "
    SELECT id, correct_option
    FROM mondialisa_formation_exam
    WHERE formation_ref = ?
    AND id IN ($placeholders)
";

$stmt = $dbh->prepare($sql);
$stmt->execute(array_merge([$formation_ref], $ids));
$questions = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$total = count($questions);

if ($total === 0) {
    echo json_encode(['success' => false, 'error' => 'no_questions']);
    exit;
}

/* ---------- Calcul score ---------- */
$correct = 0;

foreach ($questions as $qid => $correct_option) {
    if (
        isset($answers[$qid]) &&
        $answers[$qid] === $correct_option
    ) {
        $correct++;
    }
}

$score  = round(($correct / $total) * 100);
$passed = $score >= 70;

/* ---------- Enregistrer résultat ---------- */
$stmt = $dbh->prepare("
    INSERT INTO mondialisa_formation_exam_result
    (user_ref, formation_ref, score, passed, date_passed)
    VALUES (?, ?, ?, ?, NOW())
");
$stmt->execute([
    $user_ref,
    $formation_ref,
    $score,
    $passed ? 1 : 0
]);

/* ---------- Certificat ---------- */
$certificate_ref = null;

if ($passed) {

    // récupérer le titre formation
    $stmt = $dbh->prepare("
        SELECT title
        FROM mondialisa_formations
        WHERE ref = ?
        LIMIT 1
    ");
    $stmt->execute([$formation_ref]);
    $formation = $stmt->fetch(PDO::FETCH_ASSOC);

    $certificate_ref = strtoupper(uniqid('CERT-'));

    $stmt = $dbh->prepare("
        INSERT INTO mondialisa_formation_certificate
        (ref, user_ref, fullname, formation_ref, title, issued_at)
        VALUES (?, ?, ?, ?, ?, NOW())
    ");
    $stmt->execute([
        $certificate_ref,
        $user_ref,
        $fullname,
        $formation_ref,
        $formation['title'] ?? 'Formation'
    ]);
}

/* ---------- Réponse ---------- */
echo json_encode([
    'success'         => true,
    'score'           => $score,
    'passed'          => $passed,
    'certificate_ref' => $certificate_ref
]);
