<?php
/**
 * Confirmation serveur PayDunya Checkout
 */
 error_log('CONFIRMATION PAYDUNYA — SCRIPT DÉMARRÉ');
 
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

$db = getDB();

/**
 * Paiements encore en attente
 */
$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) {

    $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,
        ],
    ]);

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

    $result = json_decode($response, true);

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

        $db->prepare("
            UPDATE paiements
            SET statut = 'valide', paye_at = NOW()
            WHERE id = ?
        ")->execute([$p['id']]);

        $db->prepare("
            UPDATE rendez_vous
            SET statut = 'paye'
            WHERE id = ?
        ")->execute([$p['rdv_id']]);

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

repondre([
    'succes' => true,
    'message' => 'Confirmation exécutée'
]);