<?php
//learn.inc.php
//liste des formations
require_once 'config.inc.php';

if (!isset($_SESSION['user'])) {
    header('Location: login.php');
    exit;
}

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

$stmt = $dbh->prepare("
    SELECT f.*, p.progress
    FROM mondialisa_formations f
    INNER JOIN mondialisa_formation_user_progress p 
        ON f.ref = p.formation_ref
    WHERE p.user_ref = ?
");
$stmt->execute([$user_ref]);
$formations = $stmt->fetchAll(PDO::FETCH_ASSOC);

$certStmt = $dbh->prepare("
    SELECT * FROM mondialisa_formation_certificate
    WHERE user_ref = ?
    ORDER BY issued_at DESC
");
$certStmt->execute([$user_ref]);
$allCerts = $certStmt->fetchAll(PDO::FETCH_ASSOC);

// Map certificates by formation_ref
$certMap = [];
foreach ($allCerts as $c) {
    if (!isset($certMap[$c['formation_ref']])) {
        $certMap[$c['formation_ref']] = $c;
    }
}


?>

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

<div class="container my-5">
<h2>📚 My Trainings</h2>
<?php foreach ($formations as $f): ?>
<?php
$done = $f['progress'] ?? 0;
$cert = $certMap[$f['ref']] ?? null;

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

<div class="card mb-3">
  <div class="card-body">
    <h3 class="card-title"><?= htmlspecialchars($f['title']) ?></h3>
    <p class="card-text"><?= htmlspecialchars($f['description']) ?></p>
    <a href="index.php?p=learn_formation&ref=<?= htmlspecialchars($f['ref']) ?>" class="btn btn-primary">
        <?= $caption ?>
    </a>
    <div class="mt-2"><?= $getCertified ?></div>
    <div class="progress mt-2">
        <div class="progress-bar" role="progressbar" style="width: <?= $done ?>%;" 
             aria-valuenow="<?= $done ?>" aria-valuemin="0" aria-valuemax="100">
             <?= $done ?>%
        </div>
    </div>
  </div>
</div>

<?php endforeach; ?>


</div>
