<?php
/**
 * check_cf_payment.php
 * ─────────────────────
 * AJAX polling endpoint — user presses "Check Payment Status" after STK push.
 * 1. First asks LipaLink transaction_status API directly (catches cancellations
 *    even if webhook hasn't fired yet).
 * 2. Falls back to DB if API call fails.
 */
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/lipalink.php';

if (session_status() === PHP_SESSION_NONE) session_start();

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'unauthenticated']); exit;
}

$userId     = intval($_SESSION['user_id']);
$pendingRef = $_SESSION['cf_pending_ref'] ?? null;
$conn       = getConnection();

if (!$pendingRef) {
    echo json_encode(['status' => 'no_pending']); exit;
}

// ── Ensure table exists ───────────────────────────────────────────
$chk = $conn->query("SHOW TABLES LIKE 'chat_foreigners_payments'");
if (!$chk || $chk->num_rows === 0) {
    echo json_encode(['status' => 'no_table']); exit;
}

// ── Load payment row ──────────────────────────────────────────────
$stmt = $conn->prepare("SELECT * FROM chat_foreigners_payments
    WHERE reference=? AND user_id=? LIMIT 1");
$stmt->bind_param("si", $pendingRef, $userId);
$stmt->execute();
$payment = $stmt->get_result()->fetch_assoc();

if (!$payment) {
    echo json_encode(['status' => 'not_found']); exit;
}

// Already resolved in DB — return immediately
if (in_array($payment['status'], ['completed', 'failed'])) {
    if ($payment['status'] === 'completed') {
        unset($_SESSION['cf_pending_ref']);
        echo json_encode(['status' => 'completed']); exit;
    } else {
        unset($_SESSION['cf_pending_ref']);
        echo json_encode(['status' => 'failed', 'message' => 'Payment failed. Please try again.']); exit;
    }
}

// ── Still pending — poll LipaLink directly ───────────────────────
$crid   = $payment['checkout_request_id'];
$apiKey = getSetting('chat_foreigners_api_key', '');

if (!empty($crid) && !empty($apiKey) && strpos($crid, 'PFX') === 0) {
    $d        = lipalink_check_status($crid, $apiKey);
    $pfStatus = strtolower($d['status'] ?? '');

    if (!empty($d['success'])) {
        if ($pfStatus === 'success') {
            $upd = $conn->prepare("UPDATE chat_foreigners_payments
                SET status='completed', completed_at=NOW() WHERE id=? AND status='pending'");
            $upd->bind_param("i", $payment['id']); $upd->execute();
            unset($_SESSION['cf_pending_ref']);
            // Return redirect URL if configured
            $redirectLink = getSetting('chat_foreigners_redirect_link', '');
            echo json_encode([
                'status'   => 'completed',
                'redirect' => !empty($redirectLink) ? $redirectLink : null,
            ]); exit;

        } elseif (in_array($pfStatus, ['failed','cancelled','canceled'])) {
            $upd = $conn->prepare("UPDATE chat_foreigners_payments
                SET status='failed' WHERE id=? AND status='pending'");
            $upd->bind_param("i", $payment['id']); $upd->execute();
            unset($_SESSION['cf_pending_ref']);
            echo json_encode(['status'=>'failed','message'=>'Payment '.$pfStatus.'. Please try again.']); exit;
        }
        // pending/processing — fall through
    }
}

echo json_encode(['status' => 'pending', 'message' => 'Waiting for M-PESA confirmation…']);