<?php
// Start session untuk menyimpan data QRIS
session_start();

// Error handling
error_reporting(E_ALL);
ini_set('display_errors', 0); // Jangan tampilkan error HTML

// Function untuk response JSON
function jsonResponse($success, $message, $data = null, $code = 200) {
    http_response_code($code);
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data,
        'timestamp' => date('Y-m-d H:i:s')
    ], JSON_PRETTY_PRINT);
    exit;
}

// Log untuk debugging
error_log('=== DEPOSIT QRIS REQUEST ===');
error_log('Method: ' . $_SERVER['REQUEST_METHOD']);
error_log('POST Data: ' . print_r($_POST, true));

// Check method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Method not allowed. Use POST method.', null, 405);
}

try {
    // Ambil dan validasi input
    $username = trim($_POST['username'] ?? '');
    $amount = intval($_POST['amount'] ?? 0);
    
    error_log("Parsed - Username: $username, Amount: $amount");
    
    // Validasi username
    if (empty($username)) {
        jsonResponse(false, 'Username tidak boleh kosong', null, 400);
    }
    
    // Validasi amount
    if ($amount < 1000) {
        jsonResponse(false, 'Minimum deposit adalah Rp 30.000', [
            'min' => 1000, 
            'provided' => $amount
        ], 400);
    }
    
    if ($amount > 10000000) {
        jsonResponse(false, 'Maximum deposit adalah Rp 10.000.000', [
            'max' => 10000000, 
            'provided' => $amount
        ], 400);
    }
    
    // Load class PGA
    $classPath = __DIR__ . '/../classes/class.pga.php';
    error_log("Looking for class at: $classPath");
    
    if (!file_exists($classPath)) {
        jsonResponse(false, 'File class.pga.php tidak ditemukan', [
            'path' => $classPath
        ], 500);
    }
    
    require_once($classPath);
    
    if (!class_exists('pga')) {
        jsonResponse(false, 'Class PGA tidak ditemukan setelah require', null, 500);
    }
    
    // Generate QRIS
    error_log('Initializing PGA class...');
    $qris = new pga();
    
    error_log('Calling generateQris...');
    $result = $qris->generateQris($username, $amount);
    
    // Log response dari API
    error_log('PGA API Response: ' . print_r($result, true));
    
    // Validasi response
    if (!is_array($result)) {
        jsonResponse(false, 'Response dari API tidak valid (bukan array)', [
            'type' => gettype($result),
            'response' => $result
        ], 500);
    }
    
    if (!isset($result['success'])) {
        jsonResponse(false, 'Response tidak memiliki key "success"', [
            'response' => $result
        ], 500);
    }
    
    if (!$result['success']) {
        $errorMsg = $result['message'] ?? 'Gagal generate QRIS tanpa pesan error';
        jsonResponse(false, $errorMsg, $result, 500);
    }
    
    if (!isset($result['data']) || empty($result['data'])) {
        jsonResponse(false, 'Response tidak memiliki data QRIS', [
            'response' => $result
        ], 500);
    }
    
    // Validasi struktur data QRIS
    if (!isset($result['data']['data']) || empty($result['data']['data'])) {
        jsonResponse(false, 'QR String tidak ditemukan dalam response', [
            'response_data' => $result['data']
        ], 500);
    }
    
    if (!isset($result['data']['trx_id']) || empty($result['data']['trx_id'])) {
        jsonResponse(false, 'Transaction ID tidak ditemukan dalam response', [
            'response_data' => $result['data']
        ], 500);
    }
    
    // ✅ SIMPAN KE SESSION - INI YANG PENTING!
    $_SESSION['qris_data'] = [
        'username' => $username,
        'amount' => $amount,
        'qris_response' => $result,
        'session_ready' => true,
        'created_at' => time()
    ];
    
    error_log('QRIS data saved to session successfully');
    error_log('Session ID: ' . session_id());
    error_log('Session Data: ' . print_r($_SESSION['qris_data'], true));
    
    // ✅ REDIRECT KE PAYMENT.PHP (bukan return JSON)
    header('Location: ../payment.php');
    exit;
    
} catch (Exception $e) {
    error_log('Exception in deposit_qris: ' . $e->getMessage());
    error_log('Stack trace: ' . $e->getTraceAsString());
    
    jsonResponse(false, 'Error: ' . $e->getMessage(), [
        'exception' => get_class($e),
        'file' => $e->getFile(),
        'line' => $e->getLine(),
        'trace' => $e->getTraceAsString()
    ], 500);
    
} catch (Error $e) {
    error_log('Fatal Error in deposit_qris: ' . $e->getMessage());
    error_log('Stack trace: ' . $e->getTraceAsString());
    
    jsonResponse(false, 'Fatal Error: ' . $e->getMessage(), [
        'error' => get_class($e),
        'file' => $e->getFile(),
        'line' => $e->getLine(),
        'trace' => $e->getTraceAsString()
    ], 500);
}
?>