<?php
session_start();
header("Content-Type: application/json");
require 'require/conn.php';

$response = array();

// Ensure user is logged in
if (!isset($_SESSION['user_id'])) {
    $response['status'] = 'error';
    $response['message'] = 'User not logged in.';
    echo json_encode($response);
    exit();
}
$user_id = $_SESSION['user_id'];

// Validate CSRF token
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    $response['status'] = 'error';
    $response['message'] = 'Invalid CSRF token.';
    echo json_encode($response);
    exit();
}

// Validate required fields
if (
    empty($_POST['mobile_no']) ||
    empty($_POST['amount']) ||
    empty($_POST['network']) ||
    empty($_POST['airtime_type']) ||
    empty($_POST['transaction_pin'])
) {
    $response['status'] = 'error';
    $response['message'] = 'Missing required fields.';
    echo json_encode($response);
    exit();
}

// Sanitize input
$network_id   = intval($_POST['network']);
$amount       = floatval($_POST['amount']);
$phone        = htmlspecialchars(trim($_POST['mobile_no']));
$airtime_type = htmlspecialchars(trim($_POST['airtime_type']));
$transaction_pin = htmlspecialchars(trim($_POST['transaction_pin']));

// Check wallet balance
$userQuery = $conn->prepare("SELECT wallet FROM users WHERE id = ?");
$userQuery->bind_param("i", $user_id);
$userQuery->execute();
$userResult = $userQuery->get_result();

if ($userResult->num_rows === 0) {
    $response['status'] = 'error';
    $response['message'] = 'User not found.';
    echo json_encode($response);
    exit();
}

$userData = $userResult->fetch_assoc();
$walletBalance = $userData['wallet'];

if ($walletBalance < $amount) {
    $response['status'] = 'error';
    $response['message'] = 'Insufficient wallet balance.';
    echo json_encode($response);
    exit();
}

// Get API details
$apiQuery = $conn->query("SELECT vtu_key, vtu_url FROM api_settings WHERE id = 1");
if ($apiQuery->num_rows === 0) {
    $response['status'] = 'error';
    $response['message'] = 'API settings not found.';
    echo json_encode($response);
    exit();
}
$apiSettings = $apiQuery->fetch_assoc();
$vtu_api_key = $apiSettings['vtu_key'];
$vtu_url     = $apiSettings['vtu_url'];

// Make API request
$postData = json_encode([
    "network" => $network_id,
    "amount" => $amount,
    "mobile_number" => $phone,
    "airtime_type" => $airtime_type
]);

$ch = curl_init($vtu_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Token ' . $vtu_api_key
]);
$apiResponse = curl_exec($ch);
curl_close($ch);

$response['status'] = 'success';
$response['message'] = 'Airtime purchase successful.';
$response['wallet_balance'] = $walletBalance - $amount;

echo json_encode($response);
exit();
?>
