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

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

// Basic admin check (this is a simplified check, adjust based on your project's admin auth)
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$action = $_GET['action'] ?? '';
$user_id = $_POST['user_id'] ?? null;

if (!$user_id) {
    echo json_encode(['success' => false, 'error' => 'Missing User ID']);
    exit;
}

try {
    $db = db();
    
    // Find the latest pending/matching/account_sent recharge for this user
    $stmt = $db->prepare("SELECT id FROM finance_requests WHERE user_id = ? AND type = 'recharge' AND status IN ('0', '1', '2', 'pending', 'matched', 'account_sent') ORDER BY created_at DESC LIMIT 1");
    $stmt->execute([$user_id]);
    $order_id = $stmt->fetchColumn();

    if (!$order_id) {
        echo json_encode(['success' => false, 'error' => 'No pending recharge order found for this user']);
        exit;
    }

    if ($action === 'match_success') {
        $bank = $_POST['bank'] ?? '';
        $name = $_POST['name'] ?? '';
        $account = $_POST['account'] ?? '';
        $amount = isset($_POST['amount']) ? (float)$_POST['amount'] : null;
        
        if ($amount !== null) {
            $stmt = $db->prepare("UPDATE finance_requests SET status = '1', account_bank = ?, account_name = ?, account_number = ?, amount = ? WHERE id = ?");
            $stmt->execute([$bank, $name, $account, $amount, $order_id]);
        } else {
            $stmt = $db->prepare("UPDATE finance_requests SET status = '1', account_bank = ?, account_name = ?, account_number = ? WHERE id = ?");
            $stmt->execute([$bank, $name, $account, $order_id]);
        }
        echo json_encode(['success' => true]);
    } 
    elseif ($action === 'send_account') {
        $bank = $_POST['bank'] ?? '';
        $name = $_POST['name'] ?? '';
        $account = $_POST['account'] ?? '';
        $amount = isset($_POST['amount']) ? (float)$_POST['amount'] : null;

        if ($bank && $name && $account) {
            if ($amount !== null) {
                $stmt = $db->prepare("UPDATE finance_requests SET status = '2', account_bank = ?, account_name = ?, account_number = ?, amount = ? WHERE id = ?");
                $stmt->execute([$bank, $name, $account, $amount, $order_id]);
            } else {
                $stmt = $db->prepare("UPDATE finance_requests SET status = '2', account_bank = ?, account_name = ?, account_number = ? WHERE id = ?");
                $stmt->execute([$bank, $name, $account, $order_id]);
            }
        } else {
            $stmt = $db->prepare("UPDATE finance_requests SET status = '2' WHERE id = ?");
            $stmt->execute([$order_id]);
        }
        echo json_encode(['success' => true]);
    }
    else {
        echo json_encode(['success' => false, 'error' => 'Invalid action']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
