<?php
// /web/confirmation.php
// Affichage du ticket SEN RDV apres paiement Paxity

require_once __DIR__ . '/../api/config/helpers.php';
require_once __DIR__ . '/../api/config/database.php';

// helpers.php impose application/json pour les endpoints API.
// Cette page est une page HTML, on remplace donc ce header.
header_remove('Content-Type');
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

$rdvId = isset($_GET['rdv_id']) ? (int) $_GET['rdv_id'] : 0;
$rdv = null;
$erreur = null;
$estPaye = false;

if ($rdvId <= 0) {
    $erreur = 'Rendez-vous introuvable.';
} else {
    try {
        $db = getDB();

        $stmt = $db->prepare("\n            SELECT\n                r.id,\n                r.patient_nom,\n                r.patient_prenom,\n                r.date_rdv,\n                r.heure_rdv,\n                r.numero_file,\n                r.statut AS rdv_statut,\n                s.nom AS service_nom,\n                h.nom AS hopital_nom,\n                t.id AS ticket_id,\n                t.code_qr,\n                t.statut AS ticket_statut,\n                t.prioritaire,\n                t.heure_validite_debut,\n                t.heure_validite_fin,\n                p.montant,\n                p.statut AS paiement_statut,\n                p.paye_at,\n                p.paydunya_token AS reference_paxity\n            FROM rendez_vous r\n            JOIN services s ON s.id = r.service_id\n            JOIN hopitaux h ON h.id = s.hopital_id\n            LEFT JOIN tickets t ON t.rdv_id = r.id\n            LEFT JOIN paiements p ON p.id = (\n                SELECT p2.id\n                FROM paiements p2\n                WHERE p2.rdv_id = r.id\n                ORDER BY (p2.statut = 'valide') DESC, p2.id DESC\n                LIMIT 1\n            )\n            WHERE r.id = ?\n            LIMIT 1\n        ");

        $stmt->execute([$rdvId]);
        $rdv = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$rdv) {
            $erreur = 'Rendez-vous introuvable.';
        } else {
            $estPaye = ($rdv['paiement_statut'] === 'valide' && $rdv['rdv_statut'] === 'paye');
        }
    } catch (Throwable $e) {
        error_log('confirmation.php RDV #' . $rdvId . ' : ' . $e->getMessage());
        $erreur = 'Impossible de charger la confirmation pour le moment.';
    }
}

function e($valeur) {
    return htmlspecialchars((string) $valeur, ENT_QUOTES, 'UTF-8');
}

function dateFr($date) {
    if (!$date) return '-';
    $ts = strtotime($date);
    return $ts ? date('d/m/Y', $ts) : $date;
}

function heureFr($heure) {
    if (!$heure) return '-';
    return substr($heure, 0, 5);
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Confirmation - SEN RDV SANTE+</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
</head>
<body class="min-h-screen bg-slate-100 text-slate-800 font-sans">

<header class="bg-gradient-to-r from-[#003F8A] to-[#0066CC] text-white py-6 shadow-md">
    <div class="max-w-xl mx-auto px-4 text-center">
        <h1 class="text-3xl font-black tracking-widest">SEN RDV SANTE+</h1>
        <p class="text-white/80 text-sm mt-1">Confirmation de rendez-vous</p>
    </div>
</header>

<main class="max-w-xl mx-auto px-4 py-8">

<?php if ($erreur): ?>
    <div class="bg-white rounded-3xl p-7 shadow-xl border border-red-100 text-center">
        <div class="mx-auto w-16 h-16 rounded-full bg-red-100 text-red-600 flex items-center justify-center text-3xl font-black">!</div>
        <h2 class="mt-5 text-xl font-black text-slate-900">Une erreur est survenue</h2>
        <p class="mt-2 text-slate-600"><?= e($erreur) ?></p>
        <a href="/web/rdv.php" class="mt-6 inline-block w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3.5 rounded-xl transition">Nouveau rendez-vous</a>
    </div>

<?php elseif (!$estPaye || empty($rdv['code_qr'])): ?>
    <div class="bg-white rounded-3xl p-7 shadow-xl border border-amber-100 text-center">
        <div class="mx-auto w-16 h-16 rounded-full bg-amber-100 text-amber-700 flex items-center justify-center text-2xl font-black">...</div>
        <h2 class="mt-5 text-xl font-black text-slate-900">Paiement en cours de verification</h2>
        <p class="mt-2 text-slate-600">Nous attendons la confirmation du paiement par Paxity.</p>
        <p class="mt-3 text-sm text-slate-500">Cette page va verifier automatiquement votre paiement.</p>
        <button onclick="location.reload()" class="mt-6 w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3.5 rounded-xl transition">Verifier maintenant</button>
    </div>

    <script>
        setTimeout(function () {
            location.reload();
        }, 4000);
    </script>

<?php else: ?>
    <div class="bg-white rounded-3xl overflow-hidden shadow-xl border border-slate-200/70">
        <div class="bg-emerald-50 border-b border-emerald-100 px-6 py-6 text-center">
            <div class="mx-auto w-16 h-16 rounded-full bg-emerald-600 text-white flex items-center justify-center text-3xl font-black">✓</div>
            <h2 class="mt-4 text-2xl font-black text-slate-900">Paiement confirme</h2>
            <p class="text-emerald-700 font-semibold mt-1">Votre ticket SEN RDV est pret.</p>
        </div>

        <div class="p-6 sm:p-8">
            <div class="text-center">
                <p class="text-xs font-black uppercase tracking-widest text-slate-400">Votre QR Code</p>
                <div class="mt-4 inline-block bg-white border-2 border-slate-200 rounded-2xl p-4 shadow-sm">
                    <div id="qrcode"></div>
                </div>
                <p class="mt-3 font-mono text-sm font-bold text-slate-700 break-all"><?= e($rdv['code_qr']) ?></p>
                <p class="mt-1 text-xs text-slate-500">Presentez ce QR Code a l'accueil de l'etablissement.</p>
            </div>

            <div class="mt-7 grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
                <div class="bg-slate-50 rounded-xl p-4">
                    <div class="text-xs uppercase font-bold text-slate-400">Etablissement</div>
                    <div class="font-bold text-slate-900 mt-1"><?= e($rdv['hopital_nom']) ?></div>
                </div>
                <div class="bg-slate-50 rounded-xl p-4">
                    <div class="text-xs uppercase font-bold text-slate-400">Service</div>
                    <div class="font-bold text-slate-900 mt-1"><?= e($rdv['service_nom']) ?></div>
                </div>
                <div class="bg-slate-50 rounded-xl p-4">
                    <div class="text-xs uppercase font-bold text-slate-400">Patient</div>
                    <div class="font-bold text-slate-900 mt-1"><?= e($rdv['patient_prenom'] . ' ' . $rdv['patient_nom']) ?></div>
                </div>
                <div class="bg-slate-50 rounded-xl p-4">
                    <div class="text-xs uppercase font-bold text-slate-400">Numero de file</div>
                    <div class="font-black text-blue-700 text-xl mt-1">N° <?= e($rdv['numero_file']) ?></div>
                </div>
                <div class="bg-slate-50 rounded-xl p-4">
                    <div class="text-xs uppercase font-bold text-slate-400">Date</div>
                    <div class="font-bold text-slate-900 mt-1"><?= e(dateFr($rdv['date_rdv'])) ?></div>
                </div>
                <div class="bg-slate-50 rounded-xl p-4">
                    <div class="text-xs uppercase font-bold text-slate-400">Heure</div>
                    <div class="font-bold text-slate-900 mt-1"><?= e(heureFr($rdv['heure_rdv'])) ?></div>
                </div>
                <div class="bg-slate-50 rounded-xl p-4">
                    <div class="text-xs uppercase font-bold text-slate-400">Montant paye</div>
                    <div class="font-bold text-slate-900 mt-1"><?= e(number_format((float)$rdv['montant'], 0, ',', ' ')) ?> FCFA</div>
                </div>
                <div class="bg-slate-50 rounded-xl p-4">
                    <div class="text-xs uppercase font-bold text-slate-400">Reference</div>
                    <div class="font-mono text-xs font-bold text-slate-700 mt-1 break-all"><?= e($rdv['reference_paxity'] ?: '-') ?></div>
                </div>
            </div>

            <?php if (!empty($rdv['heure_validite_debut']) && !empty($rdv['heure_validite_fin'])): ?>
                <div class="mt-5 rounded-xl bg-blue-50 border border-blue-100 p-4 text-sm text-blue-900">
                    Validite prioritaire : <?= e(heureFr($rdv['heure_validite_debut'])) ?> a <?= e(heureFr($rdv['heure_validite_fin'])) ?>.
                </div>
            <?php endif; ?>

            <a href="/web/rdv.php" class="mt-7 block text-center w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-4 rounded-xl transition">Prendre un autre rendez-vous</a>
        </div>
    </div>

    <script>
        new QRCode(document.getElementById('qrcode'), {
            text: <?= json_encode((string)$rdv['code_qr'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
            width: 220,
            height: 220,
            colorDark: '#0f172a',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H
        });
    </script>
<?php endif; ?>

</main>

<footer class="text-center py-5 text-xs text-slate-400">SEN RDV SANTE+ - Plateforme de gestion des visites</footer>

</body>
</html>
