<?php
header('Content-Type: application/json');

$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("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(0);
}

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 all withdrawals
if(isset($data['action']) && $data['action'] === 'fetch_pending_withdrawals') {
    $withdrawals = [];

    $query = "
        SELECT wr.*, 
               COALESCE(l.email, lu.email, 'N/A') as email,
               COALESCE(l.account_name, '') as account_name, 
               COALESCE(l.account_type, '') as account_type, 
               COALESCE(lu.first_name, '') as first_name, 
               COALESCE(lu.last_name, '') as last_name
        FROM withdrawal_requests wr
        LEFT JOIN liveaccounts l ON l.trade_id = wr.trade_id
        LEFT JOIN loginusers lu ON lu.id = l.user_id
        ORDER BY wr.created_at DESC
    ";

    $result = $conn->query($query);
    if($result) {
        while($row = $result->fetch_assoc()) {
            $withdrawals[] = $row;
        }
        echo json_encode(["success" => true, "withdrawals" => $withdrawals]);
    } else {
        echo json_encode(["success" => false, "error" => $conn->error]);
    }
    exit;
}

// ✅ Handle approve/reject
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 withdrawal_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 or already processed request"]);
        exit;
    }

    $trade_id = $request['trade_id'];
    $withdraw_amount = floatval($request['amount']);
    $type = $request['type'];

    // --- Fetch user account ---
    $stmt = $conn->prepare("SELECT * FROM liveaccounts WHERE trade_id = ? LIMIT 1");
    $stmt->bind_param("s", $trade_id);
    $stmt->execute();
    $account = $stmt->get_result()->fetch_assoc();

    $email = $account['email'] ?? '';

    // ✅ Set dynamic status
    $statusValue = ($data['action'] === 'approve') ? 1 : 2; // 1 = approved, 2 = rejected
    $statusText = ($data['action'] === 'approve') ? 'approved' : 'rejected';

    $ticket = ''; // MT5 transaction ID (if approved)

    // ✅ If approved, deduct from MT5
    if ($data['action'] === 'approve') {
        $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) {
            $user = new MTUser();
            if ($api->UserGet(intval($trade_id), $user) == MTRetCode::MT_RET_OK) {
                $api->TradeBalance(
                    $user->Login,
                    MTEnDealAction::DEAL_BALANCE,
                    -$withdraw_amount,
                    "Withdrawal approved",
                    $ticket
                );
            }
            $api->Disconnect();
        }
    }

    // --- Insert into wallet_withdraw ---
    $stmtInsert = $conn->prepare("
        INSERT INTO wallet_withdraw 
        (email, trade_id, withdraw_amount, withdraw_type, company_bank, client_bank, account_holder_name, withdraw_date, Status, AdminRemark, Js_Admin_Remark_Date, transaction_id, account_number)
        VALUES (?, ?, ?, ?, '', '', '', NOW(), ?, ?, NOW(), ?, '')
    ");

    $stmtInsert->bind_param("ssdsiss", 
        $email, 
        $trade_id, 
        $withdraw_amount, 
        $type, 
        $statusValue,
        $admin_comment,
        $ticket
    );

    if(!$stmtInsert->execute()){
        echo json_encode(["success"=>false, "error"=>"Failed to insert into wallet_withdraw: ".$stmtInsert->error]);
        exit;
    }

    // --- Update withdrawal request status ---
    $stmt = $conn->prepare("UPDATE withdrawal_requests SET status = ?, admin_comment = ? WHERE id = ?");
    $stmt->bind_param("ssi", $statusText, $admin_comment, $request_id);
    $stmt->execute();

    // Return updated request
    $stmt = $conn->prepare("
        SELECT wr.*, COALESCE(l.email, lu.email, 'N/A') as email
        FROM withdrawal_requests wr
        LEFT JOIN liveaccounts l ON l.trade_id = wr.trade_id
        LEFT JOIN loginusers lu ON lu.id = l.user_id
        WHERE wr.id = ?
    ");
    $stmt->bind_param("i", $request_id);
    $stmt->execute();
    $updatedRequest = $stmt->get_result()->fetch_assoc();

    // ------------------
    // Send withdrawal approval/rejection email
    // ------------------
    $emailSent = false;
    if (EMAIL_AUTOMATION_ENABLED) {
        // Get user details for email
        $stmtUserDetails = $conn->prepare("
            SELECT lu.first_name, lu.last_name 
            FROM liveaccounts l 
            JOIN loginusers lu ON lu.id = l.user_id 
            WHERE l.trade_id = ?
        ");
        $stmtUserDetails->bind_param("s", $trade_id);
        $stmtUserDetails->execute();
        $userResult = $stmtUserDetails->get_result();
        
        if ($userDetails = $userResult->fetch_assoc()) {
            $mailSystem = getMailSystem();
            $fullName = trim($userDetails['first_name'] . ' ' . $userDetails['last_name']);
            
            if ($action === 'approve') {
                $emailResult = $mailSystem->sendWithdrawalApproved(
                    $email, 
                    $fullName, 
                    $withdraw_amount, 
                    $type,
                    $ticket
                );
            } else {
                $emailResult = $mailSystem->sendWithdrawalRejected(
                    $email, 
                    $fullName, 
                    $withdraw_amount, 
                    $admin_comment
                );
            }
            
            $emailSent = $emailResult['success'];
            
            // Log email result
            if (!$emailResult['success']) {
                error_log("Failed to send withdrawal {$action} email to $email: " . $emailResult['message']);
            }
        }
        $stmtUserDetails->close();
    }

    echo json_encode([
        "success" => true,
        "message" => "Withdrawal request {$statusText} successfully",
        "withdrawal" => $updatedRequest,
        "mt5_ticket" => $ticket,
        "email_sent" => $emailSent
    ]);
    exit;
}

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