<?php
session_start();

// Include database connection
require 'require/conn.php';

// Ensure database connection is established
if (!$conn) {
    die(json_encode(['status' => 'error', 'message' => 'Database connection failed: ' . mysqli_connect_error()]));
}

// Validate CSRF token
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    die(json_encode(['status' => 'error', 'message' => 'CSRF token validation failed.']));
}

// Validate inputs
$mobile_no = trim($_POST['mobile_no']);
$transaction_pin = trim($_POST['transaction_pin']);
$amount = trim($_POST['amount']);

if (!preg_match('/^\d{10,15}$/', $mobile_no)) {
    die(json_encode(['status' => 'error', 'message' => 'Invalid mobile number.']));
}

// Fetch API settings from the database
$settings_query = $conn->query("SELECT api_key, vtu_url FROM api_settings WHERE id = 1");
if (!$settings_query || $settings_query->num_rows == 0) {
    die(json_encode(['status' => 'error', 'message' => 'API settings not found.']));
}
$settings = $settings_query->fetch_assoc();
$api_key = trim($settings['api_key']);
$vtu_url = trim($settings['vtu_url']);
 
// Validate transaction pin
$user_id = $_SESSION['user_id'];
$pin_query = $conn->prepare("SELECT transaction_pin, wallet_balance FROM jamaa WHERE id = ?");
if (!$pin_query) {
    die(json_encode(['status' => 'error', 'message' => 'Database query failed: ' . $conn->error]));
}
$pin_query->bind_param("i", $user_id);
if (!$pin_query->execute()) {
    die(json_encode(['status' => 'error', 'message' => 'Failed to execute query: ' . $pin_query->error]));
}
$pin_result = $pin_query->get_result();

if ($pin_result->num_rows > 0) {
    $user = $pin_result->fetch_assoc();
    if (!password_verify($transaction_pin, $user['transaction_pin'])) {
        die(json_encode(['status' => 'error', 'message' => 'Invalid transaction pin.']));
    }
    $wallet_balance = $user['wallet_balance'];
} else {
    die(json_encode(['status' => 'error', 'message' => 'User not found.']));
}

// Fetch airtime_name and price
$airtime_query = $conn->prepare("SELECT airtime_name, user_price, api_price FROM airtime_plans WHERE amount = ?");
if (!$airtime_query) {
    die(json_encode(['status' => 'error', 'message' => 'Database query failed: ' . $conn->error]));
}
$airtime_query->bind_param("s", $amount);
if (!$airtime_query->execute()) {
    die(json_encode(['status' => 'error', 'message' => 'Failed to execute query: ' . $airtime_query->error]));
}
$airtime_result = $airtime_query->get_result();

if ($airtime_result->num_rows == 0) {
    die(json_encode(['status' => 'error', 'message' => 'Data plan not found.']));
}

$airtime = $airtime_result->fetch_assoc();
$airtime_name = $airtime['airtime_name'];
$price = ($_SESSION['user_type'] === 'api') ? $airtime['api_price'] : $airtime['user_price'];

// Check if wallet balance is sufficient
if ($wallet_balance < $price) {
    die(json_encode(['status' => 'error', 'message' => 'Insufficient wallet balance.']));
}

// Generate unique reference
$reference = 'REF-' . uniqid();

// Insert purchase record with "pending" status and no deduction
$insert_query = $conn->prepare("INSERT INTO airtime_purchases (user_id, airtime_name, price, mobile_no, reference, status, old_balance, new_balance, deducted) VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, FALSE)");
if (!$insert_query) {
    die(json_encode(['status' => 'error', 'message' => 'Database query failed: ' . $conn->error]));
}
$insert_query->bind_param("issssdd", $user_id, $airtime_name, $price, $mobile_no, $reference, $wallet_balance, $wallet_balance);
if (!$insert_query->execute()) {
    die(json_encode(['status' => 'error', 'message' => 'Failed to record purchase: ' . $insert_query->error]));
}

// Prepare payload for API call
$payload = [
    'plan_id' => $amount,
    'mobile_no' => $mobile_no,
    'reference' => $reference,
    'api_key' => $api_key, // Include API key if required
    'amount' => $price     // Include amount if required
];
error_log("Payload Sent: " . json_encode($payload)); // Log request payload

// Initialize cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $vtu_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Set headers
$headers = [
    'Authorization: Basic ' . $api_key,
    'Content-Type: application/json'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Execute cURL request
$request = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

error_log("API Response: " . $request); // Log API response
error_log("HTTP Code: " . $http_code); // Log HTTP status code

// Decode API response
$response = json_decode($request, true);

if ($http_code !== 200 || !isset($response['status']) || $response['status'] !== 'success') {
    $error_message = $response['message'] ?? 'Unknown error';
    
    // Update record as failed
    $update_query = $conn->prepare("UPDATE airtime_purchases SET status = 'failed', error_message = ? WHERE reference = ?");
    if (!$update_query) {
        die(json_encode(['status' => 'error', 'message' => 'Database query failed: ' . $conn->error]));
    }
    $update_query->bind_param("ss", $error_message, $reference);
    if (!$update_query->execute()) {
        die(json_encode(['status' => 'error', 'message' => 'Failed to update purchase record: ' . $update_query->error]));
    }

    die(json_encode(['status' => 'error', 'message' => 'Data purchase failed: ' . $error_message]));
}

// Deduct funds from wallet after successful API response
$new_balance = $wallet_balance - $price;
$update_wallet_query = $conn->prepare("UPDATE jamaa SET wallet_balance = ? WHERE id = ?");
if (!$update_wallet_query) {
    die(json_encode(['status' => 'error', 'message' => 'Database query failed: ' . $conn->error]));
}
$update_wallet_query->bind_param("di", $new_balance, $user_id);
if (!$update_wallet_query->execute()) {
    die(json_encode(['status' => 'error', 'message' => 'Failed to update wallet balance: ' . $update_wallet_query->error]));
}

// Update purchase record as successful and mark as deducted
$update_query = $conn->prepare("UPDATE airtime_purchases SET status = 'success', deducted = TRUE, new_balance = ? WHERE reference = ?");
if (!$update_query) {
    die(json_encode(['status' => 'error', 'message' => 'airtimebase query failed: ' . $conn->error]));
}
$update_query->bind_param("ds", $new_balance, $reference);
if (!$update_query->execute()) {
    die(json_encode(['status' => 'error', 'message' => 'Failed to update purchase record: ' . $update_query->error]));
}

echo json_encode(['status' => 'success', 'message' => 'airtime purchase successful.']);
?>