<?php
$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('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');

// ✅ Debug-safe error logging
ini_set('display_errors', '0'); // Hide raw errors from users
ini_set('log_errors', '1');
if (!ini_get('error_log')) {
    ini_set('error_log', __DIR__ . '/php-error.log');
}

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

// Generate per-request trace id
$TRACE_ID = bin2hex(random_bytes(6));
function jerror($msg, $code = 500, $extra = []) {
    http_response_code($code);
    echo json_encode(array_merge(["success" => false, "error" => $msg], $extra));
    exit;
}

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

    if (!is_array($data)) {
        jerror("Invalid JSON", 400, ["trace_id" => $TRACE_ID]);
    }

    // -------------------- 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);
        if (!$stmt) {
            error_log("[TRACE:$TRACE_ID] fetch_pending_deposits prepare failed: ".$conn->error);
            jerror("DB prepare failed", 500, ["trace_id" => $TRACE_ID, "details" => $conn->error]);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $deposits[] = $row;
        }
        $stmt->close();

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

    // -------------------- APPROVE or REJECT --------------------
    if (isset($data['action']) && ($data['action'] === 'approve' || $data['action'] === 'reject')) {
        $action        = $data['action'];
        $request_id    = (int)($data['request_id'] ?? 0);
        $admin_comment = trim($data['admin_comment'] ?? '');

        if ($request_id <= 0) {
            jerror("Missing or invalid request_id", 400, ["trace_id" => $TRACE_ID]);
        }

        // Load request (must be pending)
        $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();
        $stmt->close();

        if (!$request) {
            jerror("Invalid request", 400, ["trace_id" => $TRACE_ID]);
        }

        $trade_id     = $request['trade_id'];
        $deposit_amt  = (float)$request['amount'];
        $deposit_type = $request['type']; // 'bonus' or 'balance'

        // Fetch user account from liveaccounts (we need email and maybe current balance)
        $stmt = $conn->prepare("SELECT * FROM liveaccounts WHERE trade_id = ? LIMIT 1");
        if (!$stmt) {
            error_log("[TRACE:$TRACE_ID] liveaccounts prepare failed: ".$conn->error);
            jerror("DB prepare failed", 500, ["trace_id" => $TRACE_ID, "details" => $conn->error]);
        }
        $stmt->bind_param("s", $trade_id);
        $stmt->execute();
        $userRow = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (!$userRow) {
            jerror("User not found in liveaccounts", 404, ["trace_id" => $TRACE_ID]);
        }

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

        $ticket = 0; // MT5 ticket / transaction id
        $emailSent = false;
        $emailError = null;

        if ($action === 'approve') {
            // --------- APPROVE: perform MT5 deposit, insert wallet_deposit, update status, send email ----------
            try {
                // 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) {
                    error_log("[TRACE:$TRACE_ID] MT5 connection failed: ret=$ret");
                    jerror("MT5 connection failed", 502, ["trace_id" => $TRACE_ID, "mt5_code" => $ret]);
                }

                // Fetch MT5 user
                $userMT5 = new MTUser();
                $retUG = $api->UserGet((int)$trade_id, $userMT5);
                if ($retUG != MTRetCode::MT_RET_OK) {
                    $api->Disconnect();
                    error_log("[TRACE:$TRACE_ID] MT5 UserGet failed: ret=$retUG for trade_id=$trade_id");
                    jerror("User not found in MT5", 404, ["trace_id" => $TRACE_ID, "mt5_code" => $retUG]);
                }

                // Choose action (balance or bonus)
                $dealType = ($deposit_type === 'bonus') ? MTEnDealAction::DEAL_BONUS : MTEnDealAction::DEAL_BALANCE;

                // --------- ✅ CENT account adjustment ----------
               $accountTypeName = $userRow['account_type'] ?? '';
                $centMultiplier = ($accountTypeName === 'Cent') ? 0.01 : 1.0;

                // Convert deposit amount for MT5 if CENT
                $mt5DepositAmount = $deposit_amt;
                if ($centMultiplier !== 1.0) {
                    $mt5DepositAmount = $deposit_amt / $centMultiplier; // 1 USD = 100 units
                }

                // Do the deposit
                $retTB = $api->TradeBalance($userMT5->Login, $dealType, $mt5DepositAmount, "Deposit approved", $ticket);
                if ($retTB != MTRetCode::MT_RET_OK) {
                    $api->Disconnect();
                    error_log("[TRACE:$TRACE_ID] MT5 TradeBalance failed: ret=$retTB, login={$userMT5->Login}, amount=$mt5DepositAmount, dealType=$dealType");
                    jerror("MT5 deposit failed", 502, ["trace_id" => $TRACE_ID, "mt5_code" => $retTB]);
                }

                // Optionally refresh MT5 user to get current balance after deposit
                $current_balance = null;
                $userMT5After = new MTUser();
                if ($api->UserGet((int)$trade_id, $userMT5After) == MTRetCode::MT_RET_OK) {
                    $current_balance = isset($userMT5After->Balance) ? (float)$userMT5After->Balance : null;
                }

                $api->Disconnect();

                // Insert into wallet_deposit
                $status = 1; // approved
                $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 (?, ?, ?, ?, '', '', 0, NOW(), ?, 'default_image.jpg', ?, NOW(), '', '', '')
                ");
                if (!$stmtInsert) {
                    error_log("[TRACE:$TRACE_ID] wallet_deposit prepare failed: ".$conn->error);
                    jerror("Failed to record deposit", 500, ["trace_id" => $TRACE_ID, "details" => $conn->error]);
                }
                $stmtInsert->bind_param(
                    "ssdiss",
                    $email,
                    $trade_id,
                    $deposit_amt,
                    $deposit_type,
                    $status,
                    $admin_comment
                );
                if (!$stmtInsert->execute()) {
                    $stmtInsert->close();
                    error_log("[TRACE:$TRACE_ID] wallet_deposit execute failed: ".$stmtInsert->error);
                    jerror("Failed to save wallet_deposit", 500, ["trace_id" => $TRACE_ID, "details" => $stmtInsert->error]);
                }
                $stmtInsert->close();

                // Update deposit_requests status=approved
                $statusText = 'approved';
                $stmtUp = $conn->prepare("UPDATE deposit_requests SET status = ?, admin_comment = ? WHERE id = ?");
                $stmtUp->bind_param("ssi", $statusText, $admin_comment, $request_id);
                if (!$stmtUp->execute()) {
                    error_log("[TRACE:$TRACE_ID] deposit_requests update failed id=$request_id : ".$stmtUp->error);
                }
                $stmtUp->close();

                // Fetch user details for email
                $stmtUserDetails = $conn->prepare("
                    SELECT lu.email, lu.first_name, lu.last_name, l.Balance
                    FROM liveaccounts l 
                    JOIN loginusers lu ON lu.id = l.user_id 
                    WHERE l.trade_id = ?
                ");
                $stmtUserDetails->bind_param("s", $trade_id);
                $stmtUserDetails->execute();
                $userRes = $stmtUserDetails->get_result();
                $userDetails = $userRes->fetch_assoc();
                $stmtUserDetails->close();

                if ($userDetails && EMAIL_AUTOMATION_ENABLED) {
                    $mailSystem = getMailSystem();
                    $fullName = trim(($userDetails['first_name'] ?? '') . ' ' . ($userDetails['last_name'] ?? ''));
                    $balanceToSend = is_null($current_balance) ? (float)($userDetails['Balance'] ?? 0) : $current_balance;

                    try {
                        $emailResult = $mailSystem->sendDepositApproved(
                            $userDetails['email'],
                            $fullName,
                            $deposit_amt,
                            'USD',
                            $balanceToSend,
                            'DEP-' . $request_id
                        );
                        $emailSent = is_array($emailResult) ? (bool)($emailResult['success'] ?? false) : (bool)$emailResult;
                        if (!$emailSent) {
                            $emailError = is_array($emailResult) ? ($emailResult['message'] ?? 'unknown') : 'unknown';
                            error_log("[TRACE:$TRACE_ID] Deposit approve email failed for {$userDetails['email']}: ".$emailError);
                        }
                    } catch (Throwable $exMail) {
                        $emailError = $exMail->getMessage();
                        error_log("[TRACE:$TRACE_ID] Deposit approve email exception: ".$emailError);
                    }
                }

                echo json_encode([
                    "success"      => true,
                    "message"      => "Deposit request approved successfully",
                    "trace_id"     => $TRACE_ID,
                    "mt5_ticket"   => $ticket,
                    "email_sent"   => $emailSent,
                    "email_error"  => $emailError
                ]);
                exit;

            } catch (Throwable $ex) {
                error_log("[TRACE:$TRACE_ID] APPROVE exception: ".$ex->getMessage());
                jerror("Internal error during approval", 500, ["trace_id" => $TRACE_ID, "details" => $ex->getMessage()]);
            }
        } else {
            // --------- REJECT ----------
            $statusText = 'rejected';
            $stmt = $conn->prepare("UPDATE deposit_requests SET status = ?, admin_comment = ? WHERE id = ?");
            $stmt->bind_param("ssi", $statusText, $admin_comment, $request_id);
            $stmt->execute();
            $stmt->close();

            // Send "Deposit Failed" email
            $emailSent = false;
            $emailError = null;

            if (EMAIL_AUTOMATION_ENABLED) {
                $stmtUserDetails = $conn->prepare("
                    SELECT lu.email, 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'] ?? ''));

                    try {
                        $emailResult = $mailSystem->sendDepositFailed(
                            $userDetails['email'],
                            $fullName,
                            $deposit_amt,
                            'USD',
                            $admin_comment,
                            'DEP-' . $request_id
                        );
                        $emailSent = is_array($emailResult) ? (bool)($emailResult['success'] ?? false) : (bool)$emailResult;
                        if (!$emailSent) {
                            $emailError = is_array($emailResult) ? ($emailResult['message'] ?? 'unknown') : 'unknown';
                            error_log("[TRACE:$TRACE_ID] Deposit reject email failed for {$userDetails['email']}: ".$emailError);
                        }
                    } catch (Throwable $exMail) {
                        $emailError = $exMail->getMessage();
                        error_log("[TRACE:$TRACE_ID] Deposit reject email exception: ".$emailError);
                    }
                }
                $stmtUserDetails->close();
            }

            echo json_encode([
                "success"     => true,
                "message"     => "Deposit request rejected successfully",
                "trace_id"    => $TRACE_ID,
                "email_sent"  => $emailSent,
                "email_error" => $emailError
            ]);
            exit;
        }
    }

    echo json_encode(["success" => false, "error" => "Invalid action", "trace_id" => $TRACE_ID]);
    exit;

} catch (Throwable $e) {
    error_log("[TRACE:$TRACE_ID] Deposit API FATAL: " . $e->getMessage());
    echo json_encode([
        "success" => false,
        "error"   => "Internal server error",
        "trace_id"=> $TRACE_ID,
        "details" => $e->getMessage()
    ]);
    exit;
}
