<?php
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

$allowedOrigins = [
    'https://admin.ecotradefx.com',
    'http://localhost:3000'
];

if (in_array($origin, $allowedOrigins)) {
    header("Access-Control-Allow-Origin: $origin");
    header("Access-Control-Allow-Credentials: true");
} else {
    header("Access-Control-Allow-Origin: *");
}

header('Content-Type: application/json');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header('Access-Control-Max-Age: 1728000');

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

include_once __DIR__ . '/unified_config.php';
include_once __DIR__ . '/connection.php';
include_once __DIR__ . "/mt5_api/mt5_api.php";

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

// Fetch pending deposits
if(isset($data['action']) && $data['action'] === 'fetch_pending_deposits') {
    $deposits = [];
    $query = "
        SELECT dr.*, 
               l.trade_id, l.account_name, l.account_type, 
               COALESCE(lu.first_name, 'Unknown') as first_name, 
               COALESCE(lu.last_name, 'User') as last_name,
               lu.email  
        FROM deposit_requests dr
        LEFT JOIN liveaccounts l ON l.trade_id = dr.trade_id
        LEFT JOIN loginusers lu ON lu.id = l.user_id
        ORDER BY dr.created_at DESC
    ";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $result = $stmt->get_result();
    while($row = $result->fetch_assoc()) {
        $deposits[] = $row;
    }
    echo json_encode(["success" => true, "deposits" => $deposits]);
    exit;
}

// Handle approve/reject deposit
if(isset($data['action']) && ($data['action'] === 'approve' || $data['action'] === 'reject')) {
    $request_id = $data['request_id'] ?? 0;
    $admin_comment = $data['admin_comment'] ?? '';

    // Get request details
    $stmt = $conn->prepare("SELECT * FROM deposit_requests WHERE id = ? AND status = 'pending'");
    $stmt->bind_param("i", $request_id);
    $stmt->execute();
    $request = $stmt->get_result()->fetch_assoc();

    if(!$request) {
        echo json_encode(["success"=>false, "error"=>"Invalid request"]);
        exit;
    }

    if($data['action'] === 'approve') {
        // Fetch user account from liveaccounts
        $stmt = $conn->prepare("SELECT * FROM liveaccounts WHERE trade_id = ? LIMIT 1");
        $stmt->bind_param("s", $request['trade_id']);
        $stmt->execute();
        $userRow = $stmt->get_result()->fetch_assoc();

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

        // Connect to MT5
        $api = new MTWebAPI("WebAPITesterLocal", "./logs", true);
        $ret = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, 5, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);
        if($ret != MTRetCode::MT_RET_OK){
            echo json_encode(["success"=>false,"error"=>"MT5 connection failed"]);
            exit;
        }

        // Fetch MT5 user
        $userMT5 = new MTUser();
        $ret = $api->UserGet(intval($userRow['trade_id']), $userMT5);
        if($ret != MTRetCode::MT_RET_OK){
            $api->Disconnect();
            echo json_encode(["success"=>false,"error"=>"User not found in MT5"]);
            exit;
        }

        // Deposit into MT5
        $ticket = 0;
        $dealType = ($request['type']==='bonus') ? MTEnDealAction::DEAL_BONUS : MTEnDealAction::DEAL_BALANCE;
        $ret = $api->TradeBalance($userMT5->Login, $dealType, floatval($request['amount']), "Deposit approved", $ticket);

        if($ret == MTRetCode::MT_RET_OK){
            // ✅ Insert into wallet_deposit with correct Status and bind_param types
            $status = 1; // approved = 1

            $stmtInsert = $conn->prepare("
                INSERT INTO wallet_deposit 
                (email, trade_id, deposit_amount, deposit_type, company_bank, client_bank, account_number, deposed_date, Status, image, AdminRemark, Js_Admin_Remark_Date, btc_amount, utr_number, ifsc)
                VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), ?, 'default_image.jpg', ?, NOW(), ?, ?, ?)
            ");

            $email = $userRow['email'] ?? '';
            $deposit_amount = floatval($request['amount']);
            $deposit_type = $request['type'];
            $company_bank = '';
            $client_bank = '';
            $account_number = 0;
            $btc_amount = '';
            $utr_number = '';
            $ifsc = '';
            $admin_remark = $admin_comment;

            $stmtInsert->bind_param(
                "ssdsssisssss",  // 12 types for 12 values
                $email,
                $request['trade_id'],
                $deposit_amount,
                $deposit_type,
                $company_bank,
                $client_bank,
                $account_number,
                $status,
                $admin_remark,
                $btc_amount,
                $utr_number,
                $ifsc
            );

            if(!$stmtInsert->execute()) {
                $api->Disconnect();
                echo json_encode(["success"=>false, "error"=>"Failed to insert into wallet_deposit: ".$stmtInsert->error]);
                exit;
            }
        } else {
            $api->Disconnect();
            echo json_encode(["success"=>false,"error"=>"MT5 deposit failed: $ret"]);
            exit;
        }

        $api->Disconnect();
    }

    // Update request status
    $status = $data['action'] === 'approve' ? 'approved' : 'rejected';
    $stmt = $conn->prepare("UPDATE deposit_requests SET status = ?, admin_comment = ? WHERE id = ?");
    $stmt->bind_param("ssi", $status, $admin_comment, $request_id);
    $stmt->execute();

    // ------------------
    // Send deposit approval/rejection email
    // ------------------
    $emailSent = false;
    if (EMAIL_AUTOMATION_ENABLED) {
        // Get user details for email
        $stmtUserDetails = $conn->prepare("
            SELECT lu.email, lu.first_name, lu.last_name, lu.balance 
            FROM liveaccounts l 
            JOIN loginusers lu ON lu.id = l.user_id 
            WHERE l.trade_id = ?
        ");
        $stmtUserDetails->bind_param("s", $request['trade_id']);
        $stmtUserDetails->execute();
        $userResult = $stmtUserDetails->get_result();
        
        if ($userDetails = $userResult->fetch_assoc()) {
            $mailSystem = getMailSystem();
            $fullName = trim($userDetails['first_name'] . ' ' . $userDetails['last_name']);
            
            if ($data['action'] === 'approve') {
                $emailResult = $mailSystem->sendDepositApproved(
                    $userDetails['email'], 
                    $fullName, 
                    $request['amount'], 
                    'USD',
                    $userDetails['balance'], // Current balance after deposit
                    'DEP-' . $request_id
                );
            } else {
                $emailResult = $mailSystem->sendDepositFailed(
                    $userDetails['email'], 
                    $fullName, 
                    $request['amount'], 
                    'USD',
                    $admin_comment
                );
            }
            
            $emailSent = $emailResult['success'];
            
            // Log email result
            if (!$emailResult['success']) {
                error_log("Failed to send deposit {$status} email to " . $userDetails['email'] . ": " . $emailResult['message']);
            }
        }
        $stmtUserDetails->close();
    }

    echo json_encode([
        "success" => true, 
        "message" => "Deposit request {$status} successfully",
        "email_sent" => $emailSent
    ]);
    exit;
}

echo json_encode(["success"=>false, "error"=>"Invalid action"]);
?>
