<?php
// learn_formation.inc.php
?>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<div class="container my-5">

<h2><?= htmlspecialchars($formation['title']) ?></h2>
<p class="text-muted"><?= htmlspecialchars($formation['description']) ?></p>

<?php

$user = $_SESSION['user'];
$user_ref = $user['ref'];

// Progression de l'utilisateur
$st = $dbh->prepare("
    SELECT progress FROM mondialisa_formation_user_progress
    WHERE user_ref=? AND formation_ref=? 
");
$st->execute([$user_ref, $formation['ref']]);
$done = $st->fetchColumn() ?? 0;

// Vérifier certificat
$certStmt = $dbh->prepare("
    SELECT * FROM mondialisa_formation_certificate
    WHERE user_ref=? AND formation_ref=?
    ORDER BY issued_at DESC LIMIT 1
");
$certStmt->execute([$user_ref, $formation['ref']]);
$cert = $certStmt->fetch(PDO::FETCH_ASSOC);

// Définir bouton/caption
if ($cert) {
    $captionf = "✅ Certified on " . date('d/m/Y', strtotime($cert['issued_at']));
    $getCertified = 'ID: <a href="certificate.php?ref='.htmlspecialchars($cert['ref']).'" target="_blank">'.htmlspecialchars($cert['ref']).'</a>';
} elseif ($done == 100) {
    $captionf = "Completed";
    $getCertified = '<a class="btn btn-sm btn-success" href="index.php?p=learn_get_certified&ref='.htmlspecialchars($formation['ref']).'">Get Certified</a>';
} else {
    $captionf = $done > 0 ? "▶ Continue (".$done."%)" : "🚀 Start";
    $getCertified = "Complete to get Certified";
}
?>

<div style="border:1px solid #ddd;padding:15px;margin-bottom:10px">
    <h3><?= htmlspecialchars($f['title']) ?></h3>
    <p><?= htmlspecialchars($f['description']) ?></p>

    <a href=""
       class="btn btn-primary">
       <?= $captionf ?>
    </a>
    <?= $getCertified ?>
</div>

<h3 class="mt-4">📚 Modules</h3>

<?php foreach ($modules as $m): 
    $progress = $moduleProgress[$m['ref']] ?? 0;

    if ($progress >= 100) {
        $caption = "✅ Completed";
        $btnClass = "btn-success";
    } elseif ($progress > 0) {
        $caption = "▶ Continue ({$progress}%)";
        $btnClass = "btn-warning";
    } else {
        $caption = "🚀 Start";
        $btnClass = "btn-primary";
    }
?>

<div class="border rounded p-3 mb-3">
    <h4>📦 <?= htmlspecialchars($m['title']) ?></h4>
    <p><?= htmlspecialchars($m['description']) ?></p>

    <a href="index.php?p=learn_formation_module&ref=<?= $m['ref'] ?>"
       class="btn <?= $btnClass ?>">
       <?= $caption ?>
    </a>
</div>

<?php endforeach; ?>




 <div class="mt-5">
        <a href="index.php?p=learn" class="btn btn-secondary">
            🔙 Back 
        </a>
    </div>
</div>
