<?php
// ================================
// PESAPAL CALLBACK HANDLER (API 3.0)
// ================================

require_once '../config.php';
require_once '../includes/db.php';

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

// Logging
$logDir = '../logs';
if (!is_dir($logDir)) {
    mkdir($logDir, 0755, true);
}
$logFile = $logDir . '/pesapal_callback_' . date('Y-m-d') . '.log';

function writeLog($message) {
    global $logFile;
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

$method = $_SERVER['REQUEST_METHOD'];
writeLog("Callback received: $method");

if ($method === 'GET') {
    // Handle IPN notification with OrderTrackingId
    $order_tracking_id = $_GET['OrderTrackingId'] ?? '';

    if (!$order_tracking_id) {
        writeLog("ERROR: Missing OrderTrackingId");
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Missing OrderTrackingId']);
        exit;
    }

    writeLog("Processing OrderTrackingId: $order_tracking_id");

    // Get PesaPal credentials
    $consumer_key = getSetting('pesapal_consumer_key');
    $consumer_secret = getSetting('pesapal_consumer_secret');
    $mode = getSetting('pesapal_mode', 'sandbox');

    // ================================
    // STEP 1: GET AUTH TOKEN
    // ================================
    $auth_token = getPesapalAuthToken($consumer_key, $consumer_secret, $mode);
    if (!$auth_token) {
        writeLog("ERROR: Failed to get auth token");
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Authentication failed']);
        exit;
    }

    // ================================
    // STEP 2: CHECK TRANSACTION STATUS
    // ================================
    $status_response = getPesapalTransactionStatus($auth_token, $order_tracking_id, $mode);

    if (!$status_response) {
        writeLog("ERROR: Failed to get transaction status");
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Status check failed']);
        exit;
    }

    writeLog("Status response: " . json_encode($status_response));

    // ================================
    // STEP 3: UPDATE DATABASE
    // ================================
    $payment_status = 'pending';
    $receipt = '';

    if (isset($status_response->payment_status_description)) {
        $status_desc = strtolower($status_response->payment_status_description);

        if ($status_desc === 'completed') {
            $payment_status = 'success';
            $receipt = $order_tracking_id;
        } elseif (in_array($status_desc, ['failed', 'cancelled', 'reversed'])) {
            $payment_status = 'failed';
        }
        // 'pending' remains as 'pending'
    }

    // Update transaction in database
    $stmt = $pdo->prepare("
        UPDATE transactions
        SET status = ?, receipt = ?, updated_at = NOW()
        WHERE order_tracking_id = ?
    ");
    $stmt->execute([$payment_status, $receipt, $order_tracking_id]);

    $affected_rows = $stmt->rowCount();
    writeLog("Database update: status=$payment_status, receipt=$receipt, affected_rows=$affected_rows");

    echo json_encode([
        'success' => true,
        'status' => $payment_status,
        'order_tracking_id' => $order_tracking_id
    ]);

} elseif ($method === 'POST') {
    // Handle POST callback if needed
    $input = json_decode(file_get_contents('php://input'), true);
    writeLog("POST callback: " . json_encode($input));

    http_response_code(200);
    echo json_encode(['success' => true]);
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}

// ================================
// PESAPAL API FUNCTIONS
// ================================

function getPesapalAuthToken($consumer_key, $consumer_secret, $mode) {
    $url = $mode === 'production'
        ? 'https://pay.pesapal.com/v3/api/Auth/RequestToken'
        : 'https://cybqa.pesapal.com/pesapalv3/api/Auth/RequestToken';

    $data = [
        'consumer_key' => $consumer_key,
        'consumer_secret' => $consumer_secret
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Accept: application/json'],
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15
    ]);

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

    if ($http_code === 200) {
        $result = json_decode($response);
        return $result->token ?? null;
    }

    return null;
}

function getPesapalTransactionStatus($token, $order_tracking_id, $mode) {
    $url = $mode === 'production'
        ? 'https://pay.pesapal.com/v3/api/Transactions/GetTransactionStatus'
        : 'https://cybqa.pesapal.com/pesapalv3/api/Transactions/GetTransactionStatus';

    $url .= '?orderTrackingId=' . urlencode($order_tracking_id);

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer $token",
            'Content-Type: application/json'
        ],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15
    ]);

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

    if ($http_code === 200) {
        return json_decode($response);
    }

    return null;
}
?>