<?php
require_once '../config/conn.php';
header('Content-Type: application/json');

// Authenticate request
session_start();
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$input = json_decode(file_get_contents('php://input'), true);

if ($input['action'] === 'initiate_payment') {
    try {
        // In a real implementation, you would call SmartPay's API here
        // This is a mock implementation
        
        // Save the transaction details temporarily
        $stmt = $conn->prepare("INSERT INTO pending_transactions 
            (student_id, reference, amount, gateway, status, created_at) 
            VALUES (?, ?, ?, 'smartpay', 'pending', NOW())");
        $stmt->bind_param("isd", $input['student_id'], $input['reference'], $input['amount']);
        $stmt->execute();
        
        // Mock payment URL - in reality this would come from SmartPay API
        $paymentUrl = "https://smartpay.example.com/pay?ref=" . $input['reference'];
        
        echo json_encode([
            'success' => true,
            'payment_url' => $paymentUrl,
            'reference' => $input['reference']
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}
?>