<?php
require_once("../php/db_connect.php");

$callbackToken = $_SERVER['
l1SNHuWjN6VLohGcULInuUXs4Ibx06xW7FyZuzIzLYfIGZqH'] ?? '';
$expectedToken = '
l1SNHuWjN6VLohGcULInuUXs4Ibx06xW7FyZuzIzLYfIGZqH';

if ($callbackToken !== $expectedToken) {
    http_response_code(403);
    exit('Invalid callback token');
}

$payload = file_get_contents("php://input");
$data = json_decode($payload, true);

file_put_contents("../logs/xendit_callback_log.txt", $payload . PHP_EOL, FILE_APPEND);

$event = $data['event'] ?? '';
$paymentData = $data['data'] ?? [];
$referenceId = $paymentData['reference_id'] ?? '';
$status = $paymentData['status'] ?? '';

if ($referenceId && preg_match('/^ORDER-(\d+)$/', $referenceId, $m)) {
    $orderId = (int)$m[1];

    if ($status === 'SUCCEEDED') {
        $stmt = $conn->prepare("UPDATE orders SET payment_status='paid' WHERE id=?");
        $stmt->bind_param("i", $orderId);
        $stmt->execute();
    } elseif ($status === 'FAILED') {
        $stmt = $conn->prepare("UPDATE orders SET payment_status='failed' WHERE id=?");
        $stmt->bind_param("i", $orderId);
        $stmt->execute();
    }
}

http_response_code(200);
echo "OK";