<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

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

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

// ✅ Vérifier POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['error' => 'Méthode non autorisée']);
    exit;
}

$db = getDB();
$data = json_decode(file_get_contents('php://input'), true);

// ✅ Champs obligatoires
if (
    empty($data['rdv_id']) ||
    empty($data['montant']) ||
    empty($data['telephone'])
) {
    echo json_encode(['error' => 'Données manquantes']);
    exit;
}

$rdvId     = (int)$data['rdv_id'];
$montant   = (float)$data['montant'];
$telephone = preg_replace('/\s+/', '', $data['telephone']); // clean

// ✅ Extraire numéro et prefixe (Sénégal)
$prefixPhone = substr($telephone, 0, 3) === "221" ? "221" : "221";
$phoneNumber = substr($telephone, -9);

// ✅ Référence unique
$reference = 'RDV_' . $rdvId . '_' . time();

// ✅ Sauvegarder paiement
$db->prepare("
    INSERT INTO paiements (rdv_id, montant, statut, reference)
    VALUES (?, ?, 'en_attente', ?)
")->execute([$rdvId, $montant, $reference]);

// ✅ CONFIG PAXITY
$apiKey   = 'private_OHr2BWHPs1Sij9RvVFd0OdvkUPrStmGb';
$apiToken = 'Uf0bJMQOr4um3kEqUlDd8AOgI8C4ecVi';
$url      = "https://api.paxity.com/v1/payments/payin/";

// ✅ PAYLOAD EXACT DOC PAXITY
$payload = [
    "amount" => $montant,
    "currency" => "XOF",
    "phoneNumber" => $phoneNumber,
    "prefixPhone" => $prefixPhone,
    "paymentMethod" => "OMSN", // Orange Money SN
    "description" => "Paiement RDV SEN SANTE",
    "reference" => $reference,
    "ipn" => "https://senrdv.sendigital.org/api/paiements/paxity_callback.php"
];

// ✅ CURL
$ch = curl_init($url);

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        "x-api-key: $apiKey",
        "x-api-token: $apiToken",
        "Content-Type: application/json"
    ],
    CURLOPT_POSTFIELDS => json_encode($payload)
]);

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

// ✅ erreur CURL
if ($error) {
    echo json_encode(['error' => $error]);
    exit;
}

// ✅ log
file_put_contents(
    __DIR__ . "/paxity_log.txt",
    date('Y-m-d H:i:s') . " => " . $response . PHP_EOL,
    FILE_APPEND
);

// ✅ réponse Paxity
$result = json_decode($response, true);

// ✅ renvoyer réponse brute (important pour debug)
echo json_encode([
    "success" => true,
    "reference" => $reference,
    "paxity_response" => $result
]);