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

// ---------- Error Logging ----------
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php-error.log');

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

$allowedOrigins = [
    'https://admin.vistafxsolutions.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.*, 
               wr.payout_method,
               wr.wallet_address,
               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[] = [
            //     'id' => $row['id'],
            //     'trade_id' => $row['trade_id'],
            //     'email' => $row['email'],
            //     'amount' => $row['amount'],
            //     'type' => $row['type'],
            //     'withdrawal_method' => $row['withdrawal_method'],
            //     'payout_method' => $row['payout_method'],
            //     'wallet_address' => $row['wallet_address'],
            //     'bank_details' => $row['bank_details'],
            //     'comment' => $row['comment'],
            //     'status' => $row['status'],
            //     'created_at' => $row['created_at'],
            //     'account_name' => $row['account_name'],
            //     'account_type' => $row['account_type'],
            //     'first_name' => $row['first_name'],
            //     'last_name' => $row['last_name']
            // ];
            // Detect CENT account
$isCentAcc = stripos($row['account_type'], 'CENT') !== false;

$displayAmount = floatval($row['amount']); // already stored correctly


$withdrawals[] = [
    'id' => $row['id'],
    'trade_id' => $row['trade_id'],
    'email' => $row['email'],
    'amount' => number_format($displayAmount, 2, '.', ''), // send converted USD
    'type' => $row['type'],
    'withdrawal_method' => $row['withdrawal_method'],
    'payout_method' => $row['payout_method'],
    'wallet_address' => $row['wallet_address'],
    'bank_details' => $row['bank_details'],
    'comment' => $row['comment'],
    'status' => $row['status'],
    'created_at' => $row['created_at'],
    'account_name' => $row['account_name'],
    'account_type' => $row['account_type'],
    'first_name' => $row['first_name'],
    'last_name' => $row['last_name']
];

        }
        echo json_encode(["success" => true, "withdrawals" => $withdrawals]);
    } else {
        error_log("DB Error (fetch_pending_withdrawals): " . $conn->error);
        echo json_encode(["success" => false, "error" => "DB Error: " . $conn->error]);
    }
    exit;
}


// ✅ Handle approve/reject
if (isset($data['action']) && ($data['action'] === 'approve' || $data['action'] === 'reject')) {
    $action = $data['action'];
    $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) {
        error_log("Invalid withdrawal request id=$request_id");
        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'] ?? '';
    $account_type = strtoupper(trim($account['account_type'] ?? ''));

// More accurate detection of CENT accounts (because group contains "Cent\Wave7")
$isCent = (stripos($account_type, 'CENT') !== false);

// Convert USD to Cent amount (x100)
$mt5_withdraw_amount = $isCent ? $withdraw_amount * 100 : $withdraw_amount;



    $statusValue = ($action === 'approve') ? 1 : 2;
    $statusText = ($action === 'approve') ? 'approved' : 'rejected';
    $ticket = '';

    // ✅ If approved, deduct from MT5
    if ($action === 'approve') {
        try {
            $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,
                        -$mt5_withdraw_amount, // ✅ Deduct correct amount
                        "Withdrawal approved",
                        $ticket
                    );
                } else {
                    error_log("MT5 UserGet failed for trade_id=$trade_id");
                }
                $api->Disconnect();
            } else {
                error_log("MT5 Connect failed: ret=$ret");
            }
        } catch (Throwable $e) {
            error_log("MT5 Exception: " . $e->getMessage());
        }
    }

    // --- 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, // ✅ Store in dollars as usual
        $type,
        $statusValue,
        $admin_comment,
        $ticket
    );

    if (!$stmtInsert->execute()) {
        error_log("Failed to insert wallet_withdraw: " . $stmtInsert->error);
        echo json_encode(["success" => false, "error" => "DB insert 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);
    if (!$stmt->execute()) {
        error_log("Failed to update withdrawal_requests id=$request_id : " . $stmt->error);
    }

    // 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();

    // ✅ Email logic (unchanged)
    $emailSent = false;
    if (EMAIL_AUTOMATION_ENABLED) {
        try {
            $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') {
                    $expected_arrival = "24 hours";
                    $remaining_balance = 0.0;

                    try {
                        $mt5 = new MTWebAPI();
                        $ret = $mt5->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, 5, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);
                        if ($ret == MTRetCode::MT_RET_OK) {
                            $mt5User = new MTUser();
                            if ($mt5->UserGet(intval($trade_id), $mt5User) == MTRetCode::MT_RET_OK) {
                                $remaining_balance = $mt5User->Balance ?? 0.0;
                            }
                            $mt5->Disconnect();
                        }
                    } catch (Throwable $e) {
                        error_log("MT5 balance fetch failed: " . $e->getMessage());
                    }

                    $emailResult = $mailSystem->sendWithdrawalApproved(
                        $email,
                        $fullName,
                        $withdraw_amount,
                        'USD',
                        $ticket,
                        $expected_arrival,
                        $remaining_balance
                    );
                } else {
                    $emailResult = $mailSystem->sendWithdrawalRejected(
                        $email,
                        $fullName,
                        $withdraw_amount,
                        'USD',
                        $admin_comment,
                        'WD-' . $request_id
                    );
                }

                $emailSent = $emailResult['success'];

                if (!$emailResult['success']) {
                    error_log("Withdrawal {$action} email failed for $email: " . $emailResult['message']);
                }
            }
            $stmtUserDetails->close();
        } catch (Throwable $e) {
            error_log("Withdrawal email exception: " . $e->getMessage());
        }
    }

    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"]);
