<?php
/**
 * API - Check Deposit Status
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit(0); }

if (session_status() === PHP_SESSION_NONE) { session_start(); }

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/Auth.php';
require_once '../../includes/ApiAuth.php';

$user = ApiAuth::authenticate();
$userId = $user['id'];

$paymentRef = $_GET['payment_ref'] ?? $_POST['payment_ref'] ?? '';
$depositId = $_GET['deposit_id'] ?? $_POST['deposit_id'] ?? '';

if (empty($paymentRef) && empty($depositId)) {
    jsonError('Payment reference or deposit ID is required');
}

$result = null;

if (!empty($paymentRef)) {
    $result = dbFetch(
        "SELECT p.*, d.deposit_id, d.bonus_applied, d.status as deposit_status 
         FROM upi_payments p 
         LEFT JOIN deposits d ON d.user_id = p.user_id AND d.utr_number = p.utr_number AND d.utr_number IS NOT NULL
         WHERE p.payment_ref = :ref AND p.user_id = :uid",
        ['ref' => $paymentRef, 'uid' => $userId]
    );
}

if (!$result && !empty($depositId)) {
    $result = dbFetch(
        "SELECT d.*, p.payment_ref, p.auto_verified 
         FROM deposits d 
         LEFT JOIN upi_payments p ON p.user_id = d.user_id AND p.utr_number = d.utr_number
         WHERE d.deposit_id = :did AND d.user_id = :uid",
        ['did' => $depositId, 'uid' => $userId]
    );
}

if (!$result) {
    jsonError('Deposit not found');
}

// Get current balance
$wallet = dbFetch("SELECT balance, bonus_balance FROM user_wallets WHERE user_id = :uid", ['uid' => $userId]);

jsonSuccess('Deposit status retrieved', [
    'payment_ref' => $result['payment_ref'] ?? null,
    'deposit_id' => $result['deposit_id'] ?? null,
    'amount' => (float)($result['amount'] ?? 0),
    'status' => $result['status'] ?? $result['deposit_status'] ?? 'unknown',
    'utr_number' => $result['utr_number'] ?? null,
    'auto_verified' => (bool)($result['auto_verified'] ?? false),
    'bonus_applied' => (float)($result['bonus_applied'] ?? 0),
    'rejection_reason' => $result['rejection_reason'] ?? null,
    'created_at' => $result['created_at'] ?? null,
    'completed_at' => $result['completed_at'] ?? null,
    'current_balance' => (float)($wallet['balance'] ?? 0) + (float)($wallet['bonus_balance'] ?? 0)
]);
