<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit; 
}

require_once "include/db.php";
mysqli_set_charset($conn, "utf8mb4");

$userId = intval($_SESSION['user_id']);

// Fetch User Data
$sql = "SELECT * FROM users WHERE id = $userId LIMIT 1";
$result = mysqli_query($conn, $sql);
$currentUser = ($result && mysqli_num_rows($result) > 0) ? mysqli_fetch_assoc($result) : null;

if (!$currentUser) {
    header("Location: ../login.php");
    exit;
}

$dbTheme = $_SESSION['theme'] ?? ($currentUser['theme'] ?? '#0ea5e9');
$userName = $currentUser['username'] ?? 'Trader';
$userBalance = floatval($currentUser['balance'] ?? 0);
$storedPassword = $currentUser['password'] ?? '';

$success = '';
$error = '';

// Handle AJAX User Lookup
if (isset($_GET['action']) && $_GET['action'] === 'lookup_user' && isset($_GET['email'])) {
    header('Content-Type: application/json');
    $email = mysqli_real_escape_string($conn, trim($_GET['email']));
    
    if (empty($email)) {
        echo json_encode(['found' => false, 'message' => 'Empty email']);
        exit;
    }
    
    $lookupSql = "SELECT id, username, full_name, email FROM users WHERE email = '$email' AND id != $userId LIMIT 1";
    $lookupResult = mysqli_query($conn, $lookupSql);
    
    if ($lookupResult && mysqli_num_rows($lookupResult) > 0) {
        $user = mysqli_fetch_assoc($lookupResult);
        echo json_encode([
            'found' => true,
            'name' => !empty($user['full_name']) ? $user['full_name'] : $user['username'],
            'username' => $user['username'],
            'email' => $user['email'],
            'id' => $user['id']
        ]);
    } else {
        echo json_encode(['found' => false, 'message' => 'User not found']);
    }
    exit;
}

// Handle AJAX Password Verification
if (isset($_GET['action']) && $_GET['action'] === 'verify_password' && isset($_GET['password'])) {
    header('Content-Type: application/json');
    $inputPassword = trim($_GET['password']);
    
    // Check password - your DB stores as INT, so we check both string and int match
    $isValid = false;
    
    // Try integer comparison (for numeric passwords stored as INT)
    if (is_numeric($storedPassword) && is_numeric($inputPassword)) {
        $isValid = (int)$storedPassword === (int)$inputPassword;
    }
    // Try string comparison
    if (!$isValid) {
        $isValid = (string)$storedPassword === (string)$inputPassword;
    }
    // Try exact match
    if (!$isValid) {
        $isValid = $storedPassword == $inputPassword;
    }
    
    echo json_encode(['valid' => $isValid]);
    exit;
}

// Handle Transfer
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'transfer') {
    $recipientEmail = mysqli_real_escape_string($conn, trim($_POST['recipient_email'] ?? ''));
    $amount = floatval($_POST['amount'] ?? 0);
    $note = mysqli_real_escape_string($conn, trim($_POST['note'] ?? ''));
    $inputPassword = trim($_POST['transfer_password'] ?? '');
    
    // Verify password first
    $passwordValid = false;
    if (is_numeric($storedPassword) && is_numeric($inputPassword)) {
        $passwordValid = (int)$storedPassword === (int)$inputPassword;
    }
    if (!$passwordValid) {
        $passwordValid = (string)$storedPassword === (string)$inputPassword;
    }
    if (!$passwordValid) {
        $passwordValid = $storedPassword == $inputPassword;
    }
    
    if (!$passwordValid) {
        $error = 'Incorrect password. Please enter your account password to authorize this transfer.';
    } elseif (empty($recipientEmail)) {
        $error = 'Please enter recipient email address.';
    } elseif ($amount <= 0) {
        $error = 'Please enter a valid amount.';
    } elseif ($amount > $userBalance) {
        $error = 'Insufficient balance. Your current balance is $' . number_format($userBalance, 2);
    } elseif ($amount < 10) {
        $error = 'Minimum transfer amount is $10.';
    } else {
        $recipientSql = "SELECT id, username, full_name, email, balance FROM users WHERE email = '$recipientEmail' AND id != $userId LIMIT 1";
        $recipientResult = mysqli_query($conn, $recipientSql);
        
        if (!$recipientResult || mysqli_num_rows($recipientResult) === 0) {
            $error = 'Recipient not found. Please check the email address.';
        } else {
            $recipient = mysqli_fetch_assoc($recipientResult);
            $recipientId = intval($recipient['id']);
            $recipientName = !empty($recipient['full_name']) ? $recipient['full_name'] : $recipient['username'];
            $recipientBalance = floatval($recipient['balance'] ?? 0);
            
            if ($recipientId === $userId) {
                $error = 'You cannot transfer funds to yourself.';
            } else {
                mysqli_begin_transaction($conn);
                
                try {
                    $newSenderBalance = $userBalance - $amount;
                    $deductSql = "UPDATE users SET balance = $newSenderBalance WHERE id = $userId";
                    if (!mysqli_query($conn, $deductSql)) {
                        throw new Exception('Failed to deduct from sender: ' . mysqli_error($conn));
                    }
                    
                    $newRecipientBalance = $recipientBalance + $amount;
                    $addSql = "UPDATE users SET balance = $newRecipientBalance WHERE id = $recipientId";
                    if (!mysqli_query($conn, $addSql)) {
                        throw new Exception('Failed to add to recipient: ' . mysqli_error($conn));
                    }
                    
                    $transferSql = "INSERT INTO internal_transfers 
                        (sender_id, recipient_id, amount, note, status, created_at) 
                        VALUES ($userId, $recipientId, $amount, '$note', 'completed', NOW())";
                    
                    if (!mysqli_query($conn, $transferSql)) {
                        $createTableSql = "CREATE TABLE IF NOT EXISTS `internal_transfers` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `sender_id` int(11) NOT NULL,
                            `recipient_id` int(11) NOT NULL,
                            `amount` decimal(15,2) NOT NULL,
                            `note` text DEFAULT NULL,
                            `status` enum('pending','completed','failed') DEFAULT 'pending',
                            `created_at` timestamp DEFAULT current_timestamp(),
                            PRIMARY KEY (`id`),
                            KEY `idx_sender` (`sender_id`),
                            KEY `idx_recipient` (`recipient_id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
                        mysqli_query($conn, $createTableSql);
                        
                        if (!mysqli_query($conn, $transferSql)) {
                            throw new Exception('Failed to record transfer: ' . mysqli_error($conn));
                        }
                    }
                    
                    mysqli_commit($conn);
                    
                    $userBalance = $newSenderBalance;
                    $currentUser['balance'] = $newSenderBalance;
                    
                    $success = 'Successfully transferred $' . number_format($amount, 2) . ' to ' . htmlspecialchars($recipientName);
                    
                } catch (Exception $e) {
                    mysqli_rollback($conn);
                    $error = 'Transfer failed: ' . $e->getMessage();
                }
            }
        }
    }
}

// Fetch Transfer History
$transfers = [];
$historySql = "SELECT t.*, 
    u1.username as sender_name, u1.full_name as sender_full_name,
    u2.username as recipient_name, u2.full_name as recipient_full_name
    FROM internal_transfers t
    LEFT JOIN users u1 ON t.sender_id = u1.id
    LEFT JOIN users u2 ON t.recipient_id = u2.id
    WHERE t.sender_id = $userId OR t.recipient_id = $userId
    ORDER BY t.created_at DESC LIMIT 20";
$historyResult = mysqli_query($conn, $historySql);
if ($historyResult) {
    while ($row = mysqli_fetch_assoc($historyResult)) {
        $transfers[] = $row;
    }
}

// Get initials for avatar
$initials = strtoupper(substr($currentUser['full_name'] ?? $currentUser['username'] ?? 'U', 0, 1));
if (!empty($currentUser['full_name'])) {
    $nameParts = explode(' ', $currentUser['full_name']);
    $initials = strtoupper(substr($nameParts[0], 0, 1) . (isset($nameParts[1]) ? substr($nameParts[1], 0, 1) : ''));
}
?>

<?php include "include/header.php"?>

<!-- SweetAlert2 CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

<style>
    :root {
        --primary-theme: <?php echo htmlspecialchars($dbTheme, ENT_QUOTES, 'UTF-8'); ?>;
        --primary-rgb: <?php 
            $hex = ltrim($dbTheme, '#');
            $r = hexdec(substr($hex, 0, 2));
            $g = hexdec(substr($hex, 2, 2));
            $b = hexdec(substr($hex, 4, 2));
            echo "$r, $g, $b";
        ?>;
    }
    
    .text-theme { color: var(--primary-theme) !important; }
    .bg-theme { background-color: var(--primary-theme) !important; }
    .border-theme { border-color: var(--primary-theme) !important; }
    .bg-theme-gradient { 
        background: linear-gradient(135deg, var(--primary-theme) 0%, #1e1b4b 100%) !important; 
    }
    .shadow-theme {
        box-shadow: 0 4px 20px -2px rgba(var(--primary-rgb), 0.25),
                    0 2px 8px -2px rgba(var(--primary-rgb), 0.15);
    }
    .shadow-theme-lg {
        box-shadow: 0 10px 40px -10px rgba(var(--primary-rgb), 0.3);
    }
    
    .glass-card {
        background: rgba(30, 41, 59, 0.6);
        backdrop-filter: blur(12px);
        -webkit-backdrop-filter: blur(12px);
        border: 1px solid rgba(255, 255, 255, 0.08);
    }
    .glass-card-light {
        background: rgba(255, 255, 255, 0.8);
        backdrop-filter: blur(12px);
        -webkit-backdrop-filter: blur(12px);
        border: 1px solid rgba(0, 0, 0, 0.06);
    }
    
    .gradient-border {
        position: relative;
        background: linear-gradient(135deg, rgba(var(--primary-rgb), 0.1), rgba(30, 27, 75, 0.2));
        border-radius: 1rem;
    }
    .gradient-border::before {
        content: '';
        position: absolute;
        inset: 0;
        border-radius: 1rem;
        padding: 1.5px;
        background: linear-gradient(135deg, var(--primary-theme), rgba(var(--primary-rgb), 0.3), transparent);
        -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
        mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
        -webkit-mask-composite: xor;
        mask-composite: exclude;
        pointer-events: none;
    }
    
    .mesh-bg {
        background: 
            radial-gradient(at 40% 20%, rgba(var(--primary-rgb), 0.15) 0px, transparent 50%),
            radial-gradient(at 80% 0%, rgba(139, 92, 246, 0.1) 0px, transparent 50%),
            radial-gradient(at 0% 50%, rgba(236, 72, 153, 0.08) 0px, transparent 50%);
    }
    
    ::-webkit-scrollbar { width: 6px; height: 6px; }
    ::-webkit-scrollbar-track { background: transparent; }
    ::-webkit-scrollbar-thumb { background: rgba(var(--primary-rgb), 0.3); border-radius: 99px; }
    ::-webkit-scrollbar-thumb:hover { background: rgba(var(--primary-rgb), 0.5); }
    
    .neon-accent {
        box-shadow: 0 0 15px rgba(var(--primary-rgb), 0.2),
                    inset 0 1px 0 rgba(255,255,255,0.1);
    }
    
    .input-field {
        transition: all 0.2s ease;
    }
    .input-field:focus {
        border-color: var(--primary-theme);
        box-shadow: 0 0 0 4px rgba(var(--primary-rgb), 0.08);
    }
    
    .btn-primary {
        background: var(--primary-theme);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        position: relative;
        overflow: hidden;
    }
    .btn-primary:hover {
        filter: brightness(1.15);
        transform: translateY(-2px);
        box-shadow: 0 10px 30px -10px rgba(var(--primary-rgb), 0.4);
    }
    .btn-primary:active {
        transform: translateY(0);
    }
    
    .recipient-card {
        transition: all 0.3s ease;
        animation: slideIn 0.4s ease-out;
    }
    @keyframes slideIn {
        from { opacity: 0; transform: translateY(-10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .amount-btn {
        transition: all 0.2s ease;
    }
    .amount-btn:hover, .amount-btn.active {
        background: var(--primary-theme) !important;
        color: white !important;
        border-color: var(--primary-theme) !important;
        transform: translateY(-2px);
    }
    
    .transfer-row {
        transition: all 0.3s ease;
    }
    .transfer-row:hover {
        background: rgba(var(--primary-rgb), 0.03);
    }
    
    .loading-spinner {
        animation: spin 1s linear infinite;
    }
    @keyframes spin {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }
    
    .not-found-shake {
        animation: shake 0.5s ease-in-out;
        border-color: #f43f5e !important;
    }
    @keyframes shake {
        0%, 100% { transform: translateX(0); }
        25% { transform: translateX(-5px); }
        75% { transform: translateX(5px); }
    }
    
    /* Password input styling for SweetAlert */
    .swal2-input.password-input {
        border-radius: 1rem !important;
        padding: 0.75rem 1rem !important;
        font-size: 1rem !important;
    }
</style>

<!-- NAVBAR -->
<?php include "include/nav.php"?>

<div class="flex min-h-screen bg-slate-50 dark:bg-[#0b111a] transition-colors duration-300">
  
  <!-- SIDEBAR -->
  <?php include "include/sidebar.php"?>
  
  <!-- MAIN CONTENT -->
  <main class="flex-1 min-w-0 md:ml-72 pb-24 md:pb-8">
    <div class="max-w-screen-2xl mx-auto px-4 sm:px-6 py-6">

      <!-- Hero Section -->
      <div class="relative rounded-3xl overflow-hidden mb-8 mesh-bg bg-theme-gradient">
        <div class="absolute inset-0 bg-[url('data:image/svg+xml,%3Csvg width=\'100\' height=\'100\' viewBox=\'0 0 100 100\' xmlns=\'http://www.w3.org/2000/svg\'%3E%3Cpath d=\'M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zM32 63c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm57-13c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-9-21c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM60 91c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM35 41c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM12 60c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2z\' fill=\'%23ffffff\' fill-opacity=\'0.03\'/%3E%3C/svg%3E')] opacity-30"></div>
        
        <div class="relative z-10 p-8 md:p-12">
          <div class="flex flex-col md:flex-row md:items-center justify-between gap-6">
            <div class="max-w-xl">
              <div class="inline-flex items-center gap-2 px-3 py-1.5 bg-white/10 backdrop-blur-md rounded-full border border-white/20 mb-4">
                <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-white/90"><path d="M17 1l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 23l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
                <span class="text-xs font-semibold text-white/90">Secure Transfers</span>
              </div>
              <h1 class="text-3xl md:text-4xl font-bold text-white tracking-tight mb-3">
                Internal <span class="text-white/80">Transfer</span>
              </h1>
              <p class="text-white/60 text-sm md:text-base leading-relaxed max-w-md">
                Send funds instantly to other users. Password verification required for security.
              </p>
            </div>
            
            <!-- Balance Card -->
            <div class="bg-white/10 backdrop-blur-md rounded-2xl p-5 border border-white/20 min-w-[300px]">
              <div class="text-xs text-white/60 uppercase tracking-wider mb-1">Available Balance</div>
              <div class="text-3x font-bold text-white" id="display-balance" style="font-size:22px !important;">$<?= number_format($userBalance, 2) ?></div>
              <div class="flex items-center gap-2 mt-2">
                <span class="w-2 h-2 rounded-full bg-emerald-400 animate-pulse"></span>
                <span class="text-xs text-white/70">Ready to transfer</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Main Grid -->
      <div class="grid grid-cols-1 xl:grid-cols-5 gap-6">
        
        <!-- LEFT: Transfer Form (3 cols) -->
        <div class="xl:col-span-3 space-y-6">
          
          <!-- Transfer Form -->
          <div class="glass-card-light dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700/50 overflow-hidden transition-colors shadow-lg">
            <div class="p-5 border-b border-slate-200 dark:border-slate-700/50 flex justify-between items-center bg-slate-50/50 dark:bg-slate-800/30">
              <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-theme/10 flex items-center justify-center neon-accent">
                  <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-theme"><path d="M17 1l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 23l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
                </div>
                <div>
                  <h3 class="font-bold text-slate-900 dark:text-white text-base">Send Funds</h3>
                  <p class="text-xs text-slate-500 dark:text-slate-400">Transfer to another user</p>
                </div>
              </div>
              <div class="flex items-center gap-1.5 px-3 py-1.5 bg-amber-500/10 rounded-lg border border-amber-500/20">
                <svg width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-amber-500"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
                <span class="text-[10px] font-bold text-amber-500">Password Required</span>
              </div>
            </div>
            
            <form id="transfer-form" method="POST" action="" class="p-6 space-y-5">
              <input type="hidden" name="action" value="transfer">
              <input type="hidden" name="transfer_password" id="transfer_password" value="">
              
              <!-- Recipient Email -->
              <div>
                <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Recipient Email <span class="text-rose-500">*</span></label>
                <div class="relative">
                  <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">
                    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
                  </span>
                  <input type="email" id="recipient_email" name="recipient_email" required 
                         placeholder="Enter recipient's email address"
                         class="input-field w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white text-sm rounded-xl pl-11 pr-12 py-3 outline-none"
                         oninput="handleEmailInput(this)" autocomplete="off">
                  <div id="email-loading" class="absolute right-4 top-1/2 -translate-y-1/2 hidden">
                    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-theme loading-spinner"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
                  </div>
                  <div id="email-check" class="absolute right-4 top-1/2 -translate-y-1/2 hidden">
                    <svg width="18" height="18" fill="none" stroke="#10b981" stroke-width="3" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></svg>
                  </div>
                  <div id="email-error" class="absolute right-4 top-1/2 -translate-y-1/2 hidden">
                    <svg width="18" height="18" fill="none" stroke="#f43f5e" stroke-width="2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M15 9l-6 6M9 9l6 6"/></svg>
                  </div>
                </div>
                <p class="text-[10px] text-slate-400 mt-1" id="email-hint">Enter a registered user's email address</p>
              </div>
              
              <!-- Recipient Info Card -->
              <div id="recipient-info" class="hidden recipient-card bg-slate-50 dark:bg-slate-800/50 rounded-xl p-4 border border-slate-200 dark:border-slate-700">
                <div class="flex items-center gap-3">
                  <div class="w-12 h-12 rounded-full bg-theme/10 flex items-center justify-center text-theme font-bold text-lg shrink-0" id="recipient-avatar">
                    ?
                  </div>
                  <div class="min-w-0 flex-1">
                    <div class="text-sm font-bold text-slate-900 dark:text-white truncate" id="recipient-name">--</div>
                    <div class="text-xs text-slate-500" id="recipient-username">--</div>
                    <div class="text-[10px] text-theme font-mono mt-0.5" id="recipient-email-display">--</div>
                  </div>
                  <div class="shrink-0">
                    <span class="px-2 py-1 bg-emerald-500/10 text-emerald-500 text-[10px] font-bold rounded-full border border-emerald-500/20">Verified</span>
                  </div>
                </div>
              </div>
              
              <!-- Amount -->
              <div>
                <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Amount (USD) <span class="text-rose-500">*</span></label>
                <div class="relative">
                  <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 font-bold text-sm">$</span>
                  <input type="number" id="amount" name="amount" required min="10" step="0.01" 
                         placeholder="0.00" max="<?= $userBalance ?>"
                         class="input-field w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white text-sm rounded-xl pl-8 pr-4 py-3 outline-none font-mono text-lg"
                         oninput="updateTransferSummary()">
                </div>
                <div class="flex gap-2 mt-2">
                  <button type="button" onclick="setAmount(50, this)" class="amount-btn flex-1 py-2 text-[11px] font-bold text-slate-600 dark:text-slate-400 bg-slate-100 dark:bg-slate-800 rounded-lg border border-slate-200 dark:border-slate-700">$50</button>
                  <button type="button" onclick="setAmount(100, this)" class="amount-btn flex-1 py-2 text-[11px] font-bold text-slate-600 dark:text-slate-400 bg-slate-100 dark:bg-slate-800 rounded-lg border border-slate-200 dark:border-slate-700">$100</button>
                  <button type="button" onclick="setAmount(500, this)" class="amount-btn flex-1 py-2 text-[11px] font-bold text-slate-600 dark:text-slate-400 bg-slate-100 dark:bg-slate-800 rounded-lg border border-slate-200 dark:border-slate-700">$500</button>
                  <button type="button" onclick="setAmount(1000, this)" class="amount-btn flex-1 py-2 text-[11px] font-bold text-slate-600 dark:text-slate-400 bg-slate-100 dark:bg-slate-800 rounded-lg border border-slate-200 dark:border-slate-700">$1K</button>
                  <button type="button" onclick="setAmount(<?= floor($userBalance) ?>, this)" class="amount-btn flex-1 py-2 text-[11px] font-bold text-slate-600 dark:text-slate-400 bg-slate-100 dark:bg-slate-800 rounded-lg border border-slate-200 dark:border-slate-700">Max</button>
                </div>
                <p class="text-[10px] text-slate-400 mt-1">Min: $10 | Max: $<?= number_format($userBalance, 2) ?></p>
              </div>
              
              <!-- Note -->
              <div>
                <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase mb-2 tracking-wider">Note (Optional)</label>
                <textarea name="note" rows="2" placeholder="Add a message for the recipient..."
                          class="input-field w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white text-sm rounded-xl px-4 py-3 outline-none resize-none"></textarea>
              </div>
              
              <!-- Transfer Summary -->
              <div class="bg-slate-50 dark:bg-slate-800/50 rounded-xl p-4 space-y-3 border border-slate-200 dark:border-slate-700">
                <div class="flex justify-between text-sm">
                  <span class="text-slate-500">Transfer Amount</span>
                  <span class="font-bold text-slate-900 dark:text-white" id="summary-amount">$0.00</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-slate-500">Transfer Fee</span>
                  <span class="font-bold text-emerald-500">FREE</span>
                </div>
                <div class="border-t border-slate-200 dark:border-slate-700 pt-2 flex justify-between text-sm">
                  <span class="text-slate-500">Total Deduction</span>
                  <span class="font-bold text-rose-500" id="summary-total">$0.00</span>
                </div>
                <div class="border-t border-slate-200 dark:border-slate-700 pt-2 flex justify-between text-sm">
                  <span class="text-slate-500">Remaining Balance</span>
                  <span class="font-bold text-slate-900 dark:text-white" id="summary-remaining">$<?= number_format($userBalance, 2) ?></span>
                </div>
              </div>
              
              <!-- Security Notice -->
              <div class="bg-amber-500/5 border border-amber-500/20 rounded-xl p-4 flex items-start gap-3">
                <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-amber-500 shrink-0 mt-0.5"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
                <div>
                  <p class="text-xs font-semibold text-amber-700 dark:text-amber-400">Security Verification Required</p>
                  <p class="text-[11px] text-amber-600 dark:text-amber-500 mt-0.5">You will be asked to enter your account password to authorize this transfer.</p>
                </div>
              </div>
              
              <button type="button" onclick="confirmTransfer()" id="transfer-btn" disabled
                      class="w-full py-4 bg-slate-300 dark:bg-slate-700 text-white text-sm font-bold rounded-xl transition-all flex items-center justify-center gap-2 cursor-not-allowed">
                <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg>
                Send Funds
              </button>
            </form>
          </div>

        </div>

        <!-- RIGHT: History & Info (2 cols) -->
        <div class="xl:col-span-2 space-y-6">
          
          <!-- Transfer History -->
          <div class="glass-card-light dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700/50 overflow-hidden transition-colors shadow-lg">
            <div class="p-5 border-b border-slate-200 dark:border-slate-700/50 flex justify-between items-center bg-slate-50/50 dark:bg-slate-800/30">
              <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-theme/10 flex items-center justify-center neon-accent">
                  <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-theme"><path d="M12 8v4l3 3m6-3a9 9 0 1 1-18 0 9 9 0 0 1 18 0z"/></svg>
                </div>
                <div>
                  <h3 class="font-bold text-slate-900 dark:text-white text-base">Recent Transfers</h3>
                  <p class="text-xs text-slate-500 dark:text-slate-400">Your transfer history</p>
                </div>
              </div>
            </div>
            
            <div class="overflow-x-auto max-h-[500px] overflow-y-auto">
              <?php if (empty($transfers)): ?>
              <div class="p-12 text-center">
                <div class="flex flex-col items-center gap-3">
                  <div class="w-16 h-16 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center mb-2">
                    <svg width="28" height="28" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-slate-400"><path d="M17 1l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 23l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
                  </div>
                  <p class="text-sm font-semibold text-slate-900 dark:text-white">No transfers yet</p>
                  <p class="text-xs text-slate-400">Your transfer history will appear here</p>
                </div>
              </div>
              <?php else: ?>
              <div class="divide-y divide-slate-200 dark:divide-slate-700/50">
                <?php foreach ($transfers as $transfer): 
                  $isSender = intval($transfer['sender_id']) === $userId;
                  $otherName = $isSender ? (!empty($transfer['recipient_full_name']) ? $transfer['recipient_full_name'] : $transfer['recipient_name']) : (!empty($transfer['sender_full_name']) ? $transfer['sender_full_name'] : $transfer['sender_name']);
                ?>
                <div class="transfer-row p-4">
                  <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-full <?= $isSender ? 'bg-rose-500/10' : 'bg-emerald-500/10' ?> flex items-center justify-center text-xs font-bold <?= $isSender ? 'text-rose-500' : 'text-emerald-500' ?> shrink-0">
                      <?= $isSender ? '<svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M12 19V5M5 12l7-7 7 7"/></svg>' : '<svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M12 5v14M19 12l-7 7-7-7"/></svg>' ?>
                    </div>
                    <div class="flex-1 min-w-0">
                      <div class="flex items-center justify-between">
                        <span class="text-sm font-bold text-slate-900 dark:text-white truncate"><?= htmlspecialchars($otherName) ?></span>
                        <span class="text-sm font-mono font-bold <?= $isSender ? 'text-rose-500' : 'text-emerald-500' ?> shrink-0 ml-2">
                          <?= $isSender ? '-' : '+' ?>$<?= number_format($transfer['amount'], 2) ?>
                        </span>
                      </div>
                      <div class="flex items-center justify-between mt-0.5">
                        <span class="text-[10px] text-slate-400"><?= date('M d, Y H:i', strtotime($transfer['created_at'])) ?></span>
                        <span class="px-2 py-0.5 text-[9px] font-bold rounded-full <?= $transfer['status'] === 'completed' ? 'bg-emerald-500/10 text-emerald-500' : 'bg-amber-500/10 text-amber-500' ?> border border-current/20">
                          <?= ucfirst($transfer['status']) ?>
                        </span>
                      </div>
                      <?php if (!empty($transfer['note'])): ?>
                      <p class="text-[10px] text-slate-500 mt-1 italic">"<?= htmlspecialchars($transfer['note']) ?>"</p>
                      <?php endif; ?>
                    </div>
                  </div>
                </div>
                <?php endforeach; ?>
              </div>
              <?php endif; ?>
            </div>
          </div>

          <!-- Transfer Info -->
          <div class="gradient-border p-6">
            <div class="relative z-10">
              <h4 class="font-bold text-slate-900 dark:text-white mb-4 flex items-center gap-2">
                <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-theme"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>
                Transfer Guidelines
              </h4>
              <div class="space-y-3">
                <div class="flex items-start gap-3">
                  <div class="w-6 h-6 rounded-full bg-emerald-500/10 flex items-center justify-center shrink-0 mt-0.5">
                    <svg width="12" height="12" fill="none" stroke="currentColor" stroke-width="3" viewBox="0 0 24 24" class="text-emerald-500"><path d="M20 6L9 17l-5-5"/></svg>
                  </div>
                  <p class="text-xs text-slate-500 dark:text-slate-400">Minimum transfer amount is <strong class="text-slate-700 dark:text-slate-300">$10</strong></p>
                </div>
                <div class="flex items-start gap-3">
                  <div class="w-6 h-6 rounded-full bg-emerald-500/10 flex items-center justify-center shrink-0 mt-0.5">
                    <svg width="12" height="12" fill="none" stroke="currentColor" stroke-width="3" viewBox="0 0 24 24" class="text-emerald-500"><path d="M20 6L9 17l-5-5"/></svg>
                  </div>
                  <p class="text-xs text-slate-500 dark:text-slate-400">All transfers are <strong class="text-slate-700 dark:text-slate-300">instant and free</strong></p>
                </div>
                <div class="flex items-start gap-3">
                  <div class="w-6 h-6 rounded-full bg-emerald-500/10 flex items-center justify-center shrink-0 mt-0.5">
                    <svg width="12" height="12" fill="none" stroke="currentColor" stroke-width="3" viewBox="0 0 24 24" class="text-emerald-500"><path d="M20 6L9 17l-5-5"/></svg>
                  </div>
                  <p class="text-xs text-slate-500 dark:text-slate-400">Password required for <strong class="text-slate-700 dark:text-slate-300">security</strong></p>
                </div>
                <div class="flex items-start gap-3">
                  <div class="w-6 h-6 rounded-full bg-amber-500/10 flex items-center justify-center shrink-0 mt-0.5">
                    <svg width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-amber-500"><path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
                  </div>
                  <p class="text-xs text-slate-500 dark:text-slate-400">Transfers are <strong class="text-slate-700 dark:text-slate-300">irreversible</strong>. Please verify recipient details.</p>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>

    </div>
  </main>
</div>

<!-- FOOTER -->
<?php include "include/footer.php"?>
<?php include "include/buttom-nav.php"?>

<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
let recipientFound = false;
let currentBalance = <?= $userBalance ?>;
let lookupTimeout = null;
let recipientData = null;

function handleEmailInput(input) {
    clearTimeout(lookupTimeout);
    const email = input.value.trim();
    
    document.getElementById('email-loading').classList.add('hidden');
    document.getElementById('email-check').classList.add('hidden');
    document.getElementById('email-error').classList.add('hidden');
    document.getElementById('recipient-info').classList.add('hidden');
    document.getElementById('email-hint').textContent = 'Enter a registered user\'s email address';
    document.getElementById('email-hint').className = 'text-[10px] text-slate-400 mt-1';
    recipientFound = false;
    recipientData = null;
    updateTransferButton();
    
    if (!email || email.length < 5 || !email.includes('@')) {
        return;
    }
    
    lookupTimeout = setTimeout(() => {
        lookupUser(email);
    }, 500);
}

function lookupUser(email) {
    const loading = document.getElementById('email-loading');
    const check = document.getElementById('email-check');
    const error = document.getElementById('email-error');
    const infoCard = document.getElementById('recipient-info');
    const hint = document.getElementById('email-hint');
    const emailInput = document.getElementById('recipient_email');
    
    loading.classList.remove('hidden');
    check.classList.add('hidden');
    error.classList.add('hidden');
    infoCard.classList.add('hidden');
    
    const url = window.location.pathname.split('/').pop() + '?action=lookup_user&email=' + encodeURIComponent(email);
    
    fetch(url)
        .then(r => {
            if (!r.ok) throw new Error('Network error');
            return r.json();
        })
        .then(data => {
            loading.classList.add('hidden');
            
            if (data.found) {
                recipientFound = true;
                recipientData = data;
                
                check.classList.remove('hidden');
                hint.textContent = 'User found: ' + data.name;
                hint.className = 'text-[10px] text-emerald-500 mt-1 font-medium';
                
                document.getElementById('recipient-name').textContent = data.name;
                document.getElementById('recipient-username').textContent = '@' + data.username;
                document.getElementById('recipient-email-display').textContent = data.email;
                
                const parts = data.name.split(' ');
                const initials = parts[0].charAt(0).toUpperCase() + (parts[1] ? parts[1].charAt(0).toUpperCase() : '');
                document.getElementById('recipient-avatar').textContent = initials;
                
                infoCard.classList.remove('hidden');
                emailInput.classList.remove('not-found-shake');
                
            } else {
                error.classList.remove('hidden');
                hint.textContent = 'No user found with this email';
                hint.className = 'text-[10px] text-rose-500 mt-1 font-medium';
                
                emailInput.classList.add('not-found-shake');
                setTimeout(() => emailInput.classList.remove('not-found-shake'), 500);
            }
            updateTransferButton();
        })
        .catch(err => {
            loading.classList.add('hidden');
            console.error('Lookup error:', err);
            hint.textContent = 'Error looking up user. Please try again.';
            hint.className = 'text-[10px] text-rose-500 mt-1';
        });
}

function setAmount(amt, btn) {
    document.getElementById('amount').value = amt;
    updateTransferSummary();
    
    document.querySelectorAll('.amount-btn').forEach(b => b.classList.remove('active'));
    if (btn) btn.classList.add('active');
}

function updateTransferSummary() {
    const amount = parseFloat(document.getElementById('amount').value) || 0;
    document.getElementById('summary-amount').textContent = '$' + amount.toFixed(2);
    document.getElementById('summary-total').textContent = '-$' + amount.toFixed(2);
    document.getElementById('summary-remaining').textContent = '$' + Math.max(0, currentBalance - amount).toFixed(2);
    updateTransferButton();
}

function updateTransferButton() {
    const btn = document.getElementById('transfer-btn');
    const amount = parseFloat(document.getElementById('amount').value) || 0;
    
    if (recipientFound && amount >= 10 && amount <= currentBalance) {
        btn.disabled = false;
        btn.classList.remove('bg-slate-300', 'dark:bg-slate-700', 'cursor-not-allowed');
        btn.classList.add('btn-primary', 'bg-theme', 'shadow-theme-lg');
    } else {
        btn.disabled = true;
        btn.classList.add('bg-slate-300', 'dark:bg-slate-700', 'cursor-not-allowed');
        btn.classList.remove('btn-primary', 'bg-theme', 'shadow-theme-lg');
    }
}

function confirmTransfer() {
    const email = document.getElementById('recipient_email').value;
    const amount = parseFloat(document.getElementById('amount').value);
    const name = recipientData ? recipientData.name : 'Unknown';
    
    if (!recipientFound || !recipientData) {
        Swal.fire({
            icon: 'warning',
            title: 'Invalid Recipient',
            text: 'Please enter a valid recipient email address.',
            confirmButtonColor: 'var(--primary-theme)',
            customClass: { popup: 'rounded-2xl' }
        });
        return;
    }
    
    if (amount < 10 || amount > currentBalance) {
        Swal.fire({
            icon: 'warning',
            title: 'Invalid Amount',
            text: amount < 10 ? 'Minimum transfer amount is $10.' : 'Amount exceeds your available balance.',
            confirmButtonColor: 'var(--primary-theme)',
            customClass: { popup: 'rounded-2xl' }
        });
        return;
    }
    
    // Step 1: Show transfer confirmation
    Swal.fire({
        title: 'Confirm Transfer',
        html: `
            <div class="text-left space-y-3 py-2">
                <div class="flex items-center gap-3 p-3 bg-slate-50 dark:bg-slate-800 rounded-xl">
                    <div class="w-10 h-10 rounded-full bg-theme/10 flex items-center justify-center text-theme font-bold text-sm">
                        ${name.split(' ').map(n => n[0]).join('').toUpperCase()}
                    </div>
                    <div>
                        <div class="text-sm font-bold text-slate-900 dark:text-white">${name}</div>
                        <div class="text-xs text-slate-500">${email}</div>
                    </div>
                </div>
                <div class="flex justify-between text-sm px-1">
                    <span class="text-slate-500">Amount:</span>
                    <span class="font-bold text-rose-500 text-lg">$${amount.toFixed(2)}</span>
                </div>
                <div class="flex justify-between text-sm px-1">
                    <span class="text-slate-500">Fee:</span>
                    <span class="font-bold text-emerald-500">FREE</span>
                </div>
                <div class="border-t border-slate-200 dark:border-slate-700 pt-2 flex justify-between text-sm px-1">
                    <span class="text-slate-500">Remaining:</span>
                    <span class="font-bold text-slate-900 dark:text-white">$${(currentBalance - amount).toFixed(2)}</span>
                </div>
            </div>
        `,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: 'var(--primary-theme)',
        cancelButtonColor: '#64748b',
        confirmButtonText: 'Continue',
        cancelButtonText: 'Cancel',
        reverseButtons: true,
        customClass: {
            popup: 'rounded-2xl',
            title: 'text-lg font-bold'
        }
    }).then((result) => {
        if (result.isConfirmed) {
            // Step 2: Ask for password
            promptForPassword(amount, name, email);
        }
    });
}

function promptForPassword(amount, name, email) {
    Swal.fire({
        title: 'Security Verification',
        html: `
            <div class="text-center mb-4">
                <div class="w-16 h-16 rounded-full bg-amber-500/10 flex items-center justify-center mx-auto mb-3">
                    <svg width="28" height="28" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-amber-500"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
                </div>
                <p class="text-sm text-slate-600 dark:text-slate-400">Enter your account password to authorize this transfer</p>
                <p class="text-xs text-slate-400 mt-1">Transferring <strong class="text-rose-500">$${amount.toFixed(2)}</strong> to <strong>${name}</strong></p>
            </div>
        `,
        input: 'password',
        inputPlaceholder: 'Your account password',
        inputAttributes: {
            autocapitalize: 'off',
            autocomplete: 'off'
        },
        showCancelButton: true,
        confirmButtonColor: 'var(--primary-theme)',
        cancelButtonColor: '#64748b',
        confirmButtonText: 'Authorize & Send',
        cancelButtonText: 'Cancel',
        reverseButtons: true,
        allowOutsideClick: false,
        customClass: {
            popup: 'rounded-2xl',
            title: 'text-lg font-bold',
            input: 'password-input'
        },
        inputValidator: (value) => {
            if (!value) {
                return 'Please enter your password';
            }
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const password = result.value;
            verifyPasswordAndTransfer(password, amount, name);
        }
    });
}

function verifyPasswordAndTransfer(password, amount, name) {
    // Show loading
    Swal.fire({
        title: 'Verifying...',
        html: 'Checking your password',
        allowOutsideClick: false,
        allowEscapeKey: false,
        didOpen: () => {
            Swal.showLoading();
        },
        customClass: { popup: 'rounded-2xl' }
    });
    
    // Verify password via AJAX
    const url = window.location.pathname.split('/').pop() + '?action=verify_password&password=' + encodeURIComponent(password);
    
    fetch(url)
        .then(r => r.json())
        .then(data => {
            if (data.valid) {
                // Password correct - set it in form and submit
                document.getElementById('transfer_password').value = password;
                
                Swal.fire({
                    title: 'Processing Transfer...',
                    html: 'Sending $' + amount.toFixed(2) + ' to ' + name,
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    didOpen: () => {
                        Swal.showLoading();
                    },
                    customClass: { popup: 'rounded-2xl' }
                });
                
                // Submit the form
                setTimeout(() => {
                    document.getElementById('transfer-form').submit();
                }, 800);
                
            } else {
                // Password incorrect
                Swal.fire({
                    icon: 'error',
                    title: 'Incorrect Password',
                    text: 'The password you entered is incorrect. Please try again.',
                    confirmButtonColor: '#f43f5e',
                    confirmButtonText: 'Try Again',
                    showCancelButton: true,
                    cancelButtonText: 'Cancel',
                    customClass: { popup: 'rounded-2xl' }
                }).then((result) => {
                    if (result.isConfirmed) {
                        promptForPassword(amount, name, document.getElementById('recipient_email').value);
                    }
                });
            }
        })
        .catch(err => {
            console.error('Password verification error:', err);
            Swal.fire({
                icon: 'error',
                title: 'Verification Failed',
                text: 'Unable to verify password. Please try again.',
                confirmButtonColor: '#f43f5e',
                customClass: { popup: 'rounded-2xl' }
            });
        });
}

// Show success/error with SweetAlert
<?php if ($success): ?>
document.addEventListener('DOMContentLoaded', () => {
    Swal.fire({
        icon: 'success',
        title: 'Transfer Successful!',
        html: '<div class="text-sm text-slate-600"><?= addslashes($success) ?></div>',
        confirmButtonColor: 'var(--primary-theme)',
        confirmButtonText: 'Awesome!',
        timer: 6000,
        timerProgressBar: true,
        customClass: { popup: 'rounded-2xl' }
    });
});
<?php endif; ?>

<?php if ($error): ?>
document.addEventListener('DOMContentLoaded', () => {
    Swal.fire({
        icon: 'error',
        title: 'Transfer Failed',
        html: '<div class="text-sm text-slate-600"><?= addslashes($error) ?></div>',
        confirmButtonColor: '#f43f5e',
        confirmButtonText: 'Try Again',
        customClass: { popup: 'rounded-2xl' }
    });
});
<?php endif; ?>

document.addEventListener('DOMContentLoaded', () => {
    if (typeof lucide !== 'undefined') lucide.createIcons();
});
</script>

</body>
</html>