<?php
header('Content-Type: application/json; charset=utf-8');

try {
    include '../config/bd.php';

    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $checkColumn = $pdo->query("SHOW COLUMNS FROM transactions LIKE 'security_code'");
    $hasSecurityCode = $checkColumn->rowCount() > 0;

    if ($hasSecurityCode) {
        $stmt = $pdo->query("SELECT id, transaction_name, package_name, amount, security_code, date_time 
                             FROM transactions 
                             ORDER BY id DESC 
                             LIMIT 1");
    } else {
        $stmt = $pdo->query("SELECT id, transaction_name, package_name, amount, date_time 
                             FROM transactions 
                             ORDER BY id DESC 
                             LIMIT 1");
    }
    
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        $response = [
            'success' => true,
            'id' => intval($row['id']),
            'transaction_name' => $row['transaction_name'] ?? '',
            'package_name' => $row['package_name'] ?? '',
            'amount' => floatval($row['amount'] ?? 0),
            'security_code' => $hasSecurityCode ? ($row['security_code'] ?? null) : null,
            'date_time' => $row['date_time'] ?? ''
        ];
    } else {
        $response = [
            'success' => true,
            'id' => 0,
            'transaction_name' => '',
            'package_name' => '',
            'amount' => 0.0,
            'security_code' => null,
            'date_time' => ''
        ];
    }

} catch (Exception $e) {
    $response = [
        'success' => false,
        'error' => 'Error',
        'id' => 0,
        'transaction_name' => '',
        'package_name' => '',
        'amount' => 0.0,
        'security_code' => null,
        'date_time' => ''
    ];
}

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