<?php
// /api/public/prise_rdv.php
// Création de RDV avec paiement Paxity

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    repondre(['erreur' => 'Méthode non autorisée'], 405);
}

$body = getBody();
validerChamps($body, ['nom', 'prenom', 'telephone', 'hopital_id', 'service_id', 'creneau_id', 'date_rdv']);

$db = getDB();

// --- RÉCUPÉRER LE MONTANT DEPUIS LA BASE ---
$montant = (int) getParametre('prix_reservation', 200);

try {
    // Vérifier la disponibilité du créneau
    $stmt = $db->prepare("
        SELECT po.id, po.quota, po.mode_rdv,
               (SELECT COUNT(*) FROM rendez_vous rv 
                WHERE rv.service_id = po.service_id 
                AND rv.date_rdv = po.date_plage
                AND rv.statut NOT IN ('annule', 'expire')) as nb_pris
        FROM plages_ouvertes po
        WHERE po.id = ? AND po.actif = 1
    ");
    $stmt->execute([$body['creneau_id']]);
    $plage = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$plage) {
        repondre(['erreur' => 'Créneau non disponible'], 400);
    }

    if ($plage['mode_rdv'] === 'quota' && $plage['nb_pris'] >= $plage['quota']) {
        repondre(['erreur' => 'Quota atteint pour cette date'], 400);
    }

    // Patient technique "Sur place" (ID 51)
    $patient_id = PATIENT_SUR_PLACE_ID;

    // Créer le RDV
    $stmt = $db->prepare("
        INSERT INTO rendez_vous (
            patient_id, service_id, creneau_id,
            patient_nom, patient_prenom, motif,
            date_rdv, heure_rdv, statut, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'en_attente', NOW())
    ");

    $stmt->execute([
        $patient_id,
        $body['service_id'],
        $body['creneau_id'],
        $body['nom'],
        $body['prenom'],
        $body['motif'] ?? 'Visite',
        $body['date_rdv'],
        $body['heure_rdv'] ?? '00:00:00'
    ]);

    $rdv_id = $db->lastInsertId();

    // Calculer le numéro de file
    $stmt = $db->prepare("
        SELECT COUNT(*) FROM rendez_vous 
        WHERE service_id = ? AND date_rdv = ? AND statut NOT IN ('annule', 'expire')
    ");
    $stmt->execute([$body['service_id'], $body['date_rdv']]);
    $numero_file = $stmt->fetchColumn();

    $stmt = $db->prepare("UPDATE rendez_vous SET numero_file = ? WHERE id = ?");
    $stmt->execute([$numero_file, $rdv_id]);

    // --- INITIATION DU PAIEMENT PAXITY ---
    $reference = 'SENRDV_' . time() . '_' . $rdv_id;

    // Nettoyer le téléphone
    $telephone_paiement = preg_replace('/[^0-9]/', '', $body['telephone']);
    if (strlen($telephone_paiement) > 9 && substr($telephone_paiement, 0, 1) === '0') {
        $telephone_paiement = substr($telephone_paiement, 1);
    }
    if (strpos($telephone_paiement, '221') === 0) {
        $telephone_paiement = substr($telephone_paiement, 3);
    }

    // CRÉER LE PAIEMENT
    $stmt = $db->prepare("
        INSERT INTO paiements (
            rdv_id, 
            montant, 
            operateur, 
            telephone_paiement, 
            reference_transaction, 
            statut, 
            expire_at, 
            created_at
        ) VALUES (?, ?, ?, ?, ?, 'en_attente', DATE_ADD(NOW(), INTERVAL 24 HOUR), NOW())
    ");
    $stmt->execute([
        $rdv_id,
        $montant,
        'wave',
        $telephone_paiement,
        $reference
    ]);
    $paiement_id = $db->lastInsertId();

    // --- APPEL API PAXITY ---
    $phone = preg_replace('/[^0-9]/', '', $body['telephone']);
    if (strlen($phone) > 9 && substr($phone, 0, 1) === '0') {
        $phone = substr($phone, 1);
    }
    if (strpos($phone, '221') === 0) {
        $phone = substr($phone, 3);
    }

    $payment_method = 'WAVESN';

    $payment_data = [
        'amount' => $montant,
        'country' => 'SN',
        'currency' => 'XOF',
        'phoneNumber' => $phone,
        'prefixPhone' => 221,
        'paymentMethod' => $payment_method,
        'codeOtp' => '',
        'description' => "RDV SEN RDV SANTÉ+ - " . ($body['motif'] ?? 'Visite'),
        'idClient' => 'SENRDV_' . $rdv_id,
        'ipn' => 'https://senrdv.sendigital.org/api/public/callback_paxity.php',
        'redirectUrl' => 'https://senrdv.sendigital.org/web/confirmation.php?rdv_id=' . $rdv_id
    ];

    // Journaliser
    file_put_contents(__DIR__ . '/paxity_log.txt', 
        date('Y-m-d H:i:s') . " - RDV #$rdv_id - Montant: $montant FCFA\n" . 
        "Requête: " . json_encode($payment_data, JSON_PRETTY_PRINT) . "\n---\n", 
        FILE_APPEND
    );

    $ch = curl_init(PAXITY_BASE_URL . PAXITY_PAYMENT_ENDPOINT);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Accept: application/json',
        'Content-Type: application/json',
        'X-API-KEY: ' . PAXITY_API_KEY,
        'X-API-TOKEN: ' . PAXITY_API_TOKEN
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payment_data));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);

    file_put_contents(__DIR__ . '/paxity_log.txt', 
        date('Y-m-d H:i:s') . " - HTTP $http_code\nResponse: $response\n========================\n", 
        FILE_APPEND
    );

    if ($http_code === 200 || $http_code === 201) {
        $paxity_response = json_decode($response, true);
        
        if ($paxity_response) {
            $data = $paxity_response['data'] ?? $paxity_response;
            
            // 🔴 LE LIEN DE PAIEMENT PAXITY
            $payment_link = $data['link'] ?? null;
            $transaction_id = $data['transactionId'] ?? $data['id'] ?? null;
            $qr_code = $data['qrCode'] ?? null;
            $status = $data['status'] ?? 'PENDING';
            
            // Mettre à jour le paiement
            if ($transaction_id) {
                $stmt = $db->prepare("
                    UPDATE paiements 
                    SET paydunya_token = ?, statut = 'en_attente'
                    WHERE id = ?
                ");
                $stmt->execute([$transaction_id, $paiement_id]);
            }

            // 🔴 SI LE LIEN EXISTE, ON REDIRIGE L'UTILISATEUR VERS PAXITY
            if ($payment_link) {
                repondre([
                    'succes' => true,
                    'rdv_id' => $rdv_id,
                    'numero_file' => $numero_file,
                    'montant' => $montant,
                    'reference' => $reference,
                    'transaction_id' => $transaction_id,
                    'payment_url' => $payment_link,  // ← Lien Paxity
                    'qr_code' => $qr_code,
                    'status' => $status,
                    'paiement_id' => $paiement_id
                ], 201);
            } else {
                // Si pas de link, erreur
                repondre([
                    'succes' => false,
                    'erreur' => 'Aucun lien de paiement retourné par Paxity',
                    'rdv_id' => $rdv_id,
                    'response' => $paxity_response
                ], 400);
            }
        } else {
            repondre([
                'succes' => false,
                'erreur' => 'Erreur Paxity: ' . $response,
                'rdv_id' => $rdv_id
            ], 400);
        }
    } else {
        repondre([
            'succes' => false,
            'erreur' => 'Erreur paiement: ' . ($curl_error ?: 'Service indisponible'),
            'rdv_id' => $rdv_id,
            'paiement_id' => $paiement_id
        ], 400);
    }

} catch (PDOException $e) {
    file_put_contents(__DIR__ . '/db_error.txt', 
        date('Y-m-d H:i:s') . " - " . $e->getMessage() . "\n", 
        FILE_APPEND
    );
    repondre(['erreur' => 'Erreur base de données: ' . $e->getMessage()], 500);
} catch (Exception $e) {
    repondre(['erreur' => 'Erreur: ' . $e->getMessage()], 500);
}