<?php
header('Content-Type: application/json');
$response = ['success' => false, 'status' => null, 'message' => 'Gagal memeriksa status deposit.'];

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/session.php';
require_once __DIR__ . '/../../lib/Auth.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!Auth::isLoggedIn()) {
    http_response_code(401);
    $response['message'] = 'Sesi berakhir.';
    echo json_encode($response);
    exit;
}

if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    $response['message'] = 'Koneksi database gagal.';
    echo json_encode($response);
    exit;
}

$uniqueCode = $_GET['unique_code'] ?? null;
$userId = $_SESSION['user_id'];

if (empty($uniqueCode)) {
    http_response_code(400);
    $response['message'] = 'ID unik deposit tidak diberikan.';
    echo json_encode($response);
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT status, expired_at FROM deposits WHERE paydisini_unique_code = :unique_code AND user_id = :user_id LIMIT 1");
    $stmt->bindParam(':unique_code', $uniqueCode);
    $stmt->bindParam(':user_id', $userId, PDO::PARAM_INT);
    $stmt->execute();
    $deposit = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($deposit) {
        $response['success'] = true;
        $response['status'] = $deposit['status'];
        $response['expired_at'] = $deposit['expired_at'];
        unset($response['message']);
    } else {
        http_response_code(404);
        $response['message'] = 'Deposit tidak ditemukan.';
    }
} catch (\PDOException $e) {
    error_log("AJAX Get Deposit Status DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database.";
    http_response_code(500);
}

echo json_encode($response);
exit;
?>
