<?php
// api/paiements/initier_paxity.php
require_once '../config/helpers.php';
require_once '../config/database.php';

header('Content-Type: application/json');

// Vérifier le token
$token = verifierToken();
if (!$token || $token['role'] !== 'patient') {
    http_response_code(401);
    echo json_encode(['succes' => false, 'erreur' => 'Accès non autorisé']);
    exit;
}

// Récupérer les données POST
$input = json_decode(file_get_contents('php://input'), true);
$rdv_id = $input['rdv_id'] ?? null;
$montant = $input['montant'] ?? 200;

if (!$rdv_id) {
    http_response_code(400);
    echo json_encode(['succes' => false, 'erreur' => 'ID du RDV requis']);
    exit;
}

try {
    $pdo = getDB();
    
    // Vérifier le RDV
    $stmt = $pdo->prepare("
        SELECT r.*, u.telephone, u.nom, u.prenom, u.email,
               s.nom as service_nom, h.nom as hopital_nom
        FROM rendez_vous r
        JOIN utilisateurs u ON r.patient_id = u.id
        JOIN services s ON r.service_id = s.id
        JOIN hopitaux h ON s.hopital_id = h.id
        WHERE r.id = ? AND r.patient_id = ?
    ");
    $stmt->execute([$rdv_id, $token['id']]);
    $rdv = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$rdv) {
        http_response_code(404);
        echo json_encode(['succes' => false, 'erreur' => 'RDV non trouvé']);
        exit;
    }
    
    // Vérifier si le RDV est déjà payé
    if ($rdv['statut'] === 'paye' || $rdv['statut'] === 'consomme') {
        echo json_encode([
            'succes' => false, 
            'erreur' => 'Ce RDV a déjà été payé',
            'deja_paye' => true
        ]);
        exit;
    }
    
    
    // Créer une référence unique
    $reference = 'SENRDV_' . time() . '_' . $rdv_id . '_' . rand(1000, 9999);
    
    // Configurations Paxity - À remplacer par vos vraies clés
    $api_key = 'private_OHr2BWHPs1Sij9RvVFd0OdvkUPrStmGb';
    $secret_key = 'Uf0bJMQOr4um3kEqUlDd8AOgI8C4ecVi';
    $base_url = 'https://api.paxity.io/v1';
    
    // Préparer les données pour Paxity
    $payment_data = [
        'amount' => $montant,
        'currency' => 'XOF',
        'reference' => $reference,
        'description' => "Paiement RDV SEN RDV SANTÉ+ - " . $rdv['service_nom'],
        'customer' => [
            'name' => $rdv['prenom'] . ' ' . $rdv['nom'],
            'email' => $rdv['email'] ?? 'client@senrdv.sn',
            'phone' => $rdv['telephone']
        ],
        'callback_url' => 'https://senrdv.sendigital.org/api/paiements/callback_paxity.php',
        'cancel_url' => 'https://senrdv.sendigital.org/web/paiement-annule.html',
        'return_url' => 'https://senrdv.sendigital.org/web/paiement-retour.php?rdv_id=' . $rdv_id
    ];
    
    // Appel API Paxity
    $ch = curl_init($base_url . '/payments');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $api_key,
        'X-Secret: ' . $secret_key,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payment_data));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($http_code === 200 || $http_code === 201) {
        $paxity_response = json_decode($response, true);
        
        // Enregistrer le paiement en base
        $stmt = $pdo->prepare("
            INSERT INTO paiements (rdv_id, montant, reference_transaction, paydunya_token, statut, created_at)
            VALUES (?, ?, ?, ?, 'en_attente', NOW())
        ");
        $stmt->execute([
            $rdv_id, 
            $montant, 
            $reference,
            $paxity_response['transaction_id'] ?? $reference
        ]);
        
        echo json_encode([
            'succes' => true,
            'reference' => $reference,
            'payment_url' => $paxity_response['payment_url'] ?? $paxity_response['url'] ?? '',
            'transaction_id' => $paxity_response['transaction_id'] ?? ''
        ]);
    } else {
        echo json_encode([
            'succes' => false,
            'erreur' => 'Erreur Paxity: ' . $response,
            'http_code' => $http_code
        ]);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'succes' => false,
        'erreur' => 'Erreur serveur: ' . $e->getMessage()
    ]);
}