<?php
// ================================
// SHINDA USSD HANDLER (FIXED)
// ================================

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

header('Content-Type: text/plain');

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

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

// ================================
// ACCEPT BOTH POST & GET
// ================================
$phone     = $_POST['phone'] ?? $_GET['phone'] ?? '';
$text      = $_POST['text'] ?? $_GET['text'] ?? '';
$sessionId = $_POST['sessionId'] ?? $_GET['sessionId'] ?? '';

// Log raw request
logUSSD("RAW INPUT → Phone: $phone | Text: '$text' | SessionID: $sessionId");

// ================================
// NORMALIZE INPUT
// ================================
$text = trim($text);

// Convert to steps
$parts = ($text === "") ? [] : explode('*', $text);

logUSSD("Parsed parts: " . json_encode($parts));

// ================================
// LEVEL 1 → FIRST REQUEST
// ================================
if ($text == "") {

    logUSSD("LEVEL 1 - Show Menu");

    $stmt = $pdo->query("SELECT id, name, amount FROM services WHERE active = 1 ORDER BY id");
    $services = $stmt->fetchAll();

    if (!$services) {
        echo "END No services available";
        exit;
    }

    $response = "CON Welcome to Shinda\n";
    foreach ($services as $s) {
        $response .= $s['id'] . ". {$s['name']} (Ksh {$s['amount']})\n";
    }
    $response .= "0. Exit";

    echo $response;
    exit;
}

// ================================
// LEVEL 2 → USER SELECTS BOX
// ================================
if (count($parts) == 1) {

    $choice = $parts[0];

    logUSSD("LEVEL 2 - Choice: $choice");

    if ($choice == "0") {
        echo "END Thank you for using Shinda";
        exit;
    }

    // Validate selection
    $stmt = $pdo->prepare("SELECT * FROM services WHERE id = ? AND active = 1");
    $stmt->execute([$choice]);
    $box = $stmt->fetch();

    if (!$box) {
        echo "END Invalid selection";
        exit;
    }

    // Save session (optional)
    $stmt = $pdo->prepare("INSERT INTO sessions (phone, selected_box) VALUES (?, ?)");
    $stmt->execute([$phone, $box['box_number']]);

    // ================================
    // TRIGGER PAYMENT
    // ================================
    logUSSD("Triggering payment for Box {$box['box_number']}");

    $paymentResponse = triggerPesapalPayment($phone, $box['box_number']);

    if (!$paymentResponse || empty($paymentResponse['success'])) {
        $msg = $paymentResponse['message'] ?? 'Payment failed';
        logUSSD("Payment error: $msg");
        echo "END ❌ $msg";
        exit;
    }

    $order_tracking_id = $paymentResponse['order_tracking_id'] ?? '';

    // ================================
    // CHECK TRANSACTION STATUS
    // ================================
    sleep(2);

    $stmt = $pdo->prepare("SELECT status, receipt FROM transactions WHERE order_tracking_id = ?");
    $stmt->execute([$order_tracking_id]);
    $transaction = $stmt->fetch();

    if ($transaction && $transaction['status'] === 'success') {
        echo "END ✅ Payment Successful\nReceipt: {$transaction['receipt']}";
    } elseif ($transaction && $transaction['status'] === 'failed') {
        echo "END ❌ Payment Failed";
    } else {
        echo "END ⏳ Processing payment\nPlease complete payment on your phone";
    }

    exit;
}

// ================================
// FALLBACK (INVALID INPUT)
// ================================
logUSSD("INVALID INPUT → " . $text);
echo "END Invalid input. Please try again.";
exit;


// =======================================
// PESAPAL PAYMENT FUNCTION
// =======================================
function triggerPesapalPayment($phone, $boxNumber)
{
    global $pdo;

    // Confirm box exists
    $stmt = $pdo->prepare("SELECT amount FROM services WHERE box_number = ?");
    $stmt->execute([$boxNumber]);
    $box = $stmt->fetch();

    if (!$box) {
        return ['success' => false, 'message' => 'Box not found'];
    }

    $url = "https://shinda.co.ke/api/pesapal_payment.php";

    $payload = json_encode([
        'phone' => $phone,
        'box_number' => $boxNumber
    ]);

    $ch = curl_init($url);

    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => false
    ]);

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        return ['success' => false, 'message' => curl_error($ch)];
    }

    curl_close($ch);

    $result = json_decode($response, true);

    return $result ?: ['success' => false, 'message' => 'Invalid payment response'];
}
?>