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

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

include_once __DIR__ . '/connection.php';
include_once __DIR__ . "/config.php";

$input = file_get_contents("php://input");
$data = json_decode($input, true);

// --- Fetch user accounts for dropdown ---
if(isset($data['action']) && $data['action'] === 'fetch_accounts') {
    $accounts = [];
    $user_id = $data['user_id'] ?? 0;

    $stmt = $conn->prepare("SELECT trade_id, email, account_name, account_type FROM liveaccounts WHERE user_id=?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    while($row = $result->fetch_assoc()) {
        $accounts[] = $row;
    }

    echo json_encode(["success"=>true, "accounts"=>$accounts]);
    exit;
}

// --- Fetch recent deposits ---
if ((isset($_GET['action']) && $_GET['action']==='recent') || ($data['action'] ?? '')==='recent') {
    $deposits = [];
    $stmt = $conn->prepare("
        SELECT dr.*, l.email, l.account_name, l.account_type 
        FROM deposit_requests dr
        JOIN liveaccounts l ON l.trade_id = dr.trade_id
        ORDER BY dr.created_at DESC LIMIT 5
    ");
    $stmt->execute();
    $result = $stmt->get_result();
    while($row = $result->fetch_assoc()) {
        $deposits[] = [
            "email" => $row['email'],
            "amount" => $row['amount'],
            "type" => $row['type'],
            "account_name" => $row['account_name'],
            "account_type" => $row['account_type'],
            "status" => $row['status'],
            "created_at" => $row['created_at']
        ];
    }
    echo json_encode(["success"=>true,"deposits"=>$deposits]);
    exit;
}

// --- Submit deposit request ---
$trade_id = $data['trade_id'] ?? 0;
$amount = floatval($data['amount'] ?? 0);
$type = $data['type'] ?? 'balance';
$comment = $data['comment'] ?? 'Deposit via UI';

if(!$trade_id || $amount <=0 || !in_array($type,['balance','bonus'])) {
    echo json_encode(["success"=>false,"error"=>"Invalid parameters"]);
    exit;
}

// Get account info by trade_id
$stmt = $conn->prepare("SELECT id, user_id FROM liveaccounts WHERE trade_id=? LIMIT 1");
$stmt->bind_param("i", $trade_id);
$stmt->execute();
$userRow = $stmt->get_result()->fetch_assoc();

if(!$userRow){
    echo json_encode(["success"=>false,"error"=>"User not found"]);
    exit;
}

// --- Insert deposit request with pending status ---
$stmt = $conn->prepare("INSERT INTO deposit_requests (user_id, trade_id, amount, type, comment, status) VALUES (?, ?, ?, ?, ?, 'pending')");
$stmt->bind_param("isdss", $userRow['user_id'], $trade_id, $amount, $type, $comment);

if($stmt->execute()){
    $request_id = $conn->insert_id;
    echo json_encode([
        "success"=>true,
        "message"=>"Deposit request submitted successfully. Waiting for admin approval.",
        "ticket"=>$request_id
    ]);
} else {
    echo json_encode(["success"=>false,"error"=>"Failed to submit deposit request"]);
}
?>
