<?php
/**
 * Logique interne de confirmation PayDunya
 * Appelée depuis d'autres endpoints serveur
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/paydunya.php';
require_once __DIR__ . '/../config/push.php';

/**
 * Confirme les paiements PayDunya en attente
 */
function confirmerPaiementsPayDunya(PDO $db)
{
    $stmt = $db->prepare("
        SELECT p.id, p.rdv_id, p.paydunya_token, r.patient_id
        FROM paiements p
        JOIN rendez_vous r ON r.id = p.rdv_id
        WHERE p.statut = 'en_attente'
          AND p.paydunya_token IS NOT NULL
    ");
    $stmt->execute();
    $paiements = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($paiements as $p) {

        // Appel PayDunya confirm
        $ch = curl_init(
            PAYDUNYA_BASE_URL . '/checkout-invoice/confirm/' . $p['paydunya_token']
        );

        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'PAYDUNYA-MASTER-KEY: ' . PAYDUNYA_MASTER_KEY,
                'PAYDUNYA-PUBLIC-KEY: ' . PAYDUNYA_PUBLIC_KEY,
                'PAYDUNYA-PRIVATE-KEY: ' . PAYDUNYA_PRIVATE_KEY,
                'PAYDUNYA-TOKEN: ' . PAYDUNYA_TOKEN,
            ],
            CURLOPT_TIMEOUT => 20,
        ]);

        $response = curl_exec($ch);
        curl_close($ch);

        $result = json_decode($response, true);

        // ✅ Lecture robuste du statut PayDunya
        $status = null;
        if (isset($result['status'])) {
            $status = $result['status'];
        } elseif (isset($result['invoice']['status'])) {
            $status = $result['invoice']['status'];
        }

        if (
            isset($result['response_code']) &&
            $result['response_code'] === '00' &&
            $status !== null &&
            in_array(strtolower($status), ['completed', 'paid', 'success'])
        ) {
            // ✅ Paiement confirmé

            // 1️⃣ Marquer paiement validé
            $db->prepare("
                UPDATE paiements
                SET statut = 'valide', paye_at = NOW()
                WHERE id = ?
            ")->execute([$p['id']]);

            // 2️⃣ Mettre le RDV à payé
            $db->prepare("
                UPDATE rendez_vous
                SET statut = 'paye'
                WHERE id = ?
            ")->execute([$p['rdv_id']]);

            // ✅ FIX : création du ticket QR si absent
            $check = $db->prepare("SELECT id FROM tickets WHERE rdv_id = ?");
            $check->execute([$p['rdv_id']]);

            if ($check->rowCount() === 0) {

                // Génération du QR
                $codeQR = 'SENRDV-' . strtoupper(bin2hex(random_bytes(8)));

                // Récupérer l'heure du RDV
                $stmt2 = $db->prepare("SELECT heure_rdv FROM rendez_vous WHERE id = ?");
                $stmt2->execute([$p['rdv_id']]);
                $rdvData = $stmt2->fetch(PDO::FETCH_ASSOC);

                if (!empty($rdvData['heure_rdv'])) {
                    $heureDebut = $rdvData['heure_rdv'];
                    $heureFin   = date('H:i:s', strtotime($heureDebut) + 15 * 60);

                    $db->prepare("
                        INSERT INTO tickets
                          (rdv_id, code_qr, statut, prioritaire, heure_validite_debut, heure_validite_fin)
                        VALUES (?, ?, 'actif', 1, ?, ?)
                    ")->execute([
                        $p['rdv_id'],
                        $codeQR,
                        $heureDebut,
                        $heureFin
                    ]);
                }
            }

            // 3️⃣ Notification patient
            envoyerNotificationPush(
                $p['patient_id'],
                '✅ Paiement confirmé',
                'Votre rendez-vous est validé. Votre ticket est disponible.',
                ['rdv_id' => $p['rdv_id']]
            );
        }
    }
}