<?php
/**
 * Initier un paiement PayDunya Checkout
 */

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

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

$utilisateur = verifierToken();
$body = getBody();
validerChamps($body, ['rdv_id', 'operateur', 'telephone']);

$db = getDB();

/**
 * Récupération RDV + patient + paiement
 */
$stmt = $db->prepare("
    SELECT 
        r.id,
        r.statut,
        r.service_id,
        r.patient_nom,
        r.patient_prenom,
        s.nom AS service_nom,
        u.telephone AS patient_telephone,
        u.email AS patient_email,
        p.id AS paiement_id,
        p.montant
    FROM rendez_vous r
    JOIN services s ON s.id = r.service_id
    JOIN utilisateurs u ON u.id = r.patient_id
    LEFT JOIN paiements p ON p.rdv_id = r.id
    WHERE r.id = ? AND r.patient_id = ?
");
$stmt->execute([$body['rdv_id'], $utilisateur['utilisateur_id']]);
$rdv = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$rdv) {
    repondre(['erreur' => 'RDV introuvable'], 404);
}

if ($rdv['statut'] !== 'confirme') {
    repondre(['erreur' => 'RDV non confirmé. Statut actuel : ' . $rdv['statut']], 409);
}

// Créer un paiement s'il n'existe pas
if (!$rdv['paiement_id']) {
    $prixReservation = (float) getParametre('prix_reservation', 200);
    $expireAt = date('Y-m-d H:i:s', strtotime('+3 hours'));
    
    $stmtP = $db->prepare("
        INSERT INTO paiements (rdv_id, montant, operateur, telephone_paiement, expire_at, statut)
        VALUES (?, ?, ?, ?, ?, 'en_attente')
    ");
    $stmtP->execute([
        $rdv['id'],
        $prixReservation,
        $body['operateur'],
        $body['telephone'],
        $expireAt,
    ]);
    $rdv['paiement_id'] = $db->lastInsertId();
    $rdv['montant'] = $prixReservation;
}

$reference = 'SENRDV-' . $rdv['id'] . '-' . time();

/**
 * Création facture PayDunya Checkout
 */
$payload = [
    'invoice' => [
        'items' => [
            [
                'name' => 'Frais réservation - ' . $rdv['service_nom'],
                'quantity' => 1,
                'unit_price' => (float)$rdv['montant'],
                'total_price' => (float)$rdv['montant'],
                'description' => 'RDV médical - ' . $rdv['patient_prenom'] . ' ' . $rdv['patient_nom'],
            ]
        ],
        'total_amount' => (float)$rdv['montant'],
        'description' => 'Frais réservation RDV médical - ' . $rdv['service_nom'],
    ],
    'store' => [
        'name' => 'SEN RDV SANTE+',
        'website_url' => 'https://senrdvsanteplus.com',
    ],
    'actions' => [
        'return_url' => PAYDUNYA_RETURN_URL,
        'cancel_url' => PAYDUNYA_RETURN_URL,
    ],
    'custom_data' => [
        'rdv_id' => (int)$rdv['id'],
        'paiement_id' => (int)$rdv['paiement_id'],
        'reference' => $reference,
    ],
];

$ch = curl_init(PAYDUNYA_BASE_URL . '/checkout-invoice/create');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'PAYDUNYA-MASTER-KEY: ' . PAYDUNYA_MASTER_KEY,
        'PAYDUNYA-PUBLIC-KEY: ' . PAYDUNYA_PUBLIC_KEY,
        'PAYDUNYA-PRIVATE-KEY: ' . PAYDUNYA_PRIVATE_KEY,
        'PAYDUNYA-TOKEN: ' . PAYDUNYA_TOKEN,
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
]);

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

// Log pour déboguer
error_log("=== PayDunya Initier ===");
error_log("URL: " . PAYDUNYA_BASE_URL . '/checkout-invoice/create');
error_log("Payload: " . json_encode($payload));
error_log("HTTP Code: " . $httpCode);
error_log("Response: " . $response);
error_log("cURL Error: " . ($curlError ?: 'none'));
error_log("========================");

if ($curlError) {
    repondre(['erreur' => 'Erreur de connexion à PayDunya: ' . $curlError], 502);
}

if ($httpCode !== 200 && $httpCode !== 201) {
    repondre([
        'erreur' => 'Erreur PayDunya (HTTP ' . $httpCode . ')',
        'detail' => $response,
    ], 502);
}

$result = json_decode($response, true);

if (!$result) {
    repondre([
        'erreur' => 'Réponse PayDunya invalide',
        'detail' => $response,
    ], 502);
}

// PayDunya peut retourner "success" au lieu de "response_code"
$isSuccess = ($result['response_code'] ?? '') === '00' || ($result['success'] ?? false) === true;

if (!$isSuccess) {
    $message = $result['response_text'] ?? $result['message'] ?? 'Erreur PayDunya';
    repondre([
        'erreur' => $message,
        'detail' => $result,
    ], 502);
}

$token = $result['token'] ?? $result['invoice_token'] ?? null;
$paiementUrl = $result['response_text'] ?? $result['invoice_url'] ?? null;

if (!$paiementUrl) {
    repondre([
        'erreur' => 'URL de paiement manquante dans la réponse PayDunya',
        'detail' => $result,
    ], 500);
}

/**
 * Sauvegarde token PayDunya
 */
if ($token) {
    $db->prepare("
        UPDATE paiements
        SET paydunya_token = ?, operateur = ?, telephone_paiement = ?
        WHERE id = ?
    ")->execute([$token, $body['operateur'], $body['telephone'], $rdv['paiement_id']]);
}

repondre([
    'succes' => true,
    'paiement_url' => $paiementUrl,
]);