<?php
session_start();
require_once "../config.php"; // make sure $pdo is defined here

header('Content-Type: text/html; charset=utf-8'); // ensure HTML output

if (!isset($_SESSION['SESS_USERID'])) {
    echo "<script>alert('Error: User not logged in!'); window.location.href='dashboard.php';</script>";
    exit();
}

$userId = $_SESSION['SESS_USERID'];

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    try {
        $stmt = $pdo->prepare("SELECT username, balance, iprofit, cur_symbol, `switch` FROM logins WHERE id = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            echo "<script>alert('Error: User not found.'); window.location.href='dashboard.php';</script>";
            exit();
        }

        $username = htmlspecialchars($user['username']);
        $balance  = floatval($user['balance']);
        $iprofit  = floatval($user['iprofit']);
        $currency = $user['cur_symbol'];
        $locked   = intval($user['switch']); // 1 = blocked, 0 = allowed

        // Load SweetAlert2 first
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';

        // Case: blocked by system
        if ($locked === 1) {
            echo "<script>
                Swal.fire({
                    icon: 'error',
                    title: 'Transfer Blocked',
                    text: 'Hello {$username}, your profit transfer is blocked by the system. Please contact support.',
                    confirmButtonText: 'OK'
                }).then(() => { window.location.href='dashboard.php'; });
            </script>";
            exit();
        }

        // Case: allowed, confirm transfer
        if ($locked === 0) {
            if ($iprofit <= 0) {
                echo "<script>
                    Swal.fire({
                        icon: 'info',
                        title: 'No Profit',
                        text: 'Hello {$username}, you have no locked profits to transfer.',
                        confirmButtonText: 'OK'
                    }).then(() => { window.location.href='dashboard.php'; });
                </script>";
                exit();
            }

            // Confirmation popup
            echo "<script>
                Swal.fire({
                    title: 'Transfer Confirmation',
                    text: 'Hello {$username}, do you want to transfer your locked profits ({$currency}" . number_format($iprofit,2) . ") to your account balance?',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Transfer',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Execute the transfer immediately
                        fetch('execute_transfer.php', {
                            method: 'POST',
                            credentials: 'same-origin'
                        }).then(() => { window.location.href='dashboard.php'; });
                    } else {
                        window.location.href='dashboard.php';
                    }
                });
            </script>";
            exit();
        }

    } catch (Exception $e) {
        error_log('Transfer Error: ' . $e->getMessage());
        echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'An unexpected error occurred. Please try again.',
                confirmButtonText: 'OK'
            }).then(() => { window.location.href='dashboard.php'; });
        </script>";
        exit();
    }
}
?>
