<?php
// user/dashboard.php (single-page AJAX dashboard) — MOBILE FRIENDLY with slide-in sidebar
// NOTE: replace the file at /extract/user/dashboard.php with this content.
error_reporting(E_ALL);
// Don't display errors - log them instead to prevent JSON corruption
ini_set('display_errors', 0);
ini_set('log_errors', 1);
file_put_contents(__DIR__ . '/debug_log.txt', "POST DATA:\n" . print_r($_POST, true) . "\n", FILE_APPEND);

require_once '../config/config.php';
require_once '../classes/Database.php';
require_once '../classes/Auth.php';
require_once '../classes/User.php';
require_once '../classes/Search.php';
require_once '../classes/TelegramBot.php';

$db = Database::getInstance();
$auth = new Auth($db);

if (!$auth->isLoggedIn()) {
    header('Location: ../login.php');
    exit();
}
if ($auth->isAdmin()) {
    header('Location: ../admin/dashboard.php');
    exit();
}

$user = new User($db);
$search = new Search($db, $user);
$currentUser = $auth->getCurrentUser();
$telegram = new TelegramBot(TELEGRAM_BOT_TOKEN, TELEGRAM_ADMIN_CHAT_ID);

// Fetch full user data including password for verification
if ($currentUser && isset($currentUser['id'])) {
    $fullUserData = $db->fetch('SELECT * FROM users WHERE id = ?', [$currentUser['id']]);
    if ($fullUserData) {
        $currentUser['password'] = $fullUserData['password'];
    } else {
        // Fallback if user data cannot be fetched
        error_log('User data not found for ID: ' . $currentUser['id']);
    }
} else {
    error_log('Current user not properly set');
}

// Load initial data
$walletBalance   = $user->getWalletBalance($currentUser['id']);
$permissions     = $user->getPermissions($currentUser['id']);
$recentSearches  = $user->getSearchHistory($currentUser['id'], 10);
$unreadMessages  = $user->getUnreadMessages($currentUser['id']);
$adminSettings   = $search->getAdminSettings();

// ---------- AJAX/POST handlers ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    header('Content-Type: application/json; charset=utf-8');
    ob_start(); // Start output buffering to catch any stray output
    
    // Debug logging
    error_log('=== PAYMENT DEBUG ===');
    error_log('Action: ' . $action);
    error_log('POST Data: ' . json_encode($_POST));
    error_log('Current User: ' . json_encode($currentUser));

    switch ($action) {
        // Mobile search (AJAX)
        case 'search_mobile':
            $mobile = trim($_POST['mobile'] ?? '');
            if (!preg_match('/^[6-9]\d{9}$/', $mobile)) {
                echo json_encode(['success' => false, 'message' => 'Invalid mobile number format']);
                exit;
            }
            $cost = (float)($adminSettings['mobile_search_cost'] ?? 1);
            $result = $search->mobileSearch($currentUser['id'], $mobile);
            if ($result['success']) {
                $balance = $user->getWalletBalance($currentUser['id']);
                
                // Send Telegram notifications
                if (!empty(TELEGRAM_BOT_TOKEN) && !empty(TELEGRAM_ADMIN_CHAT_ID)) {
                    $telegram->notifySearch($currentUser, 'mobile', $mobile, $result, $cost);
                }
                if (!empty($currentUser['telegram_id']) && !empty(TELEGRAM_BOT_TOKEN)) {
                    $telegram->notifyUserSearch($currentUser, 'mobile', $mobile, $result);
                }
                
                echo json_encode([
                    'success'  => true,
                    'data'     => $result['data'],
                    'balance'  => $balance,
                    'message'  => $result['message'] ?? 'Search successful',
                    'fallback' => $result['fallback'] ?? false
                ]);
            } else {
                echo json_encode(['success' => false, 'message' => $result['message'] ?? 'Search failed']);
            }
            exit;

        // Aadhaar search (AJAX)
        case 'search_aadhaar':
            $aadhaar = trim($_POST['aadhaar'] ?? '');
            if (!preg_match('/^\d{12}$/', $aadhaar)) {
                echo json_encode(['success' => false, 'message' => 'Invalid Aadhaar number format']);
                exit;
            }
            $cost = (float)($adminSettings['aadhaar_search_cost'] ?? 5);
            $result = $search->aadhaarSearch($currentUser['id'], $aadhaar);
            if ($result['success']) {
                $balance = $user->getWalletBalance($currentUser['id']);
                
                // Send Telegram notifications
                if (!empty(TELEGRAM_BOT_TOKEN) && !empty(TELEGRAM_ADMIN_CHAT_ID)) {
                    $telegram->notifySearch($currentUser, 'aadhaar', $aadhaar, $result, $cost);
                }
                if (!empty($currentUser['telegram_id']) && !empty(TELEGRAM_BOT_TOKEN)) {
                    $telegram->notifyUserSearch($currentUser, 'aadhaar', $aadhaar, $result);
                }
                
                echo json_encode([
                    'success'  => true,
                    'data'     => $result['data'],
                    'balance'  => $balance,
                    'message'  => $result['message'] ?? 'Search successful',
                    'fallback' => $result['fallback'] ?? false
                ]);
            } else {
                echo json_encode(['success' => false, 'message' => $result['message'] ?? 'Search failed']);
            }
            exit;

        // Update profile (AJAX)
        case 'update_profile':
            $name  = trim($_POST['name'] ?? '');
            $email = trim($_POST['email'] ?? '');
            if ($name === '' || $email === '') {
                ob_end_clean();
                echo json_encode(['success' => false, 'message' => 'Name and email are required.']);
                exit;
            }
            $ok = $user->updateProfile($currentUser['id'], $name, $email);
            if ($ok) {
                $_SESSION['user_name']  = $name;
                $_SESSION['user_email'] = $email;
                ob_end_clean();
                echo json_encode(['success' => true, 'message' => 'Profile updated', 'name' => $name, 'email' => $email]);
            } else {
                ob_end_clean();
                echo json_encode(['success' => false, 'message' => 'Failed to update profile']);
            }
            exit;

        // Change password (AJAX)
        case 'change_password':
            $currentPass = $_POST['current_password'] ?? '';
            $newPass     = $_POST['new_password'] ?? '';
            $confirmPass = $_POST['confirm_password'] ?? '';

            if (empty($currentPass) || empty($newPass) || empty($confirmPass)) {
                ob_end_clean();
                echo json_encode(['success' => false, 'message' => 'All fields are required']);
                exit;
            }

            if ($newPass !== $confirmPass) {
                ob_end_clean();
                echo json_encode(['success' => false, 'message' => 'New passwords do not match']);
                exit;
            }

            if (strlen($newPass) < 6) {
                ob_end_clean();
                echo json_encode(['success' => false, 'message' => 'Password must be at least 6 characters']);
                exit;
            }

            // Verify current password
            if (!password_verify($currentPass, $currentUser['password'])) {
                ob_end_clean();
                echo json_encode(['success' => false, 'message' => 'Current password is incorrect']);
                exit;
            }

            // Hash new password and update
            $hashedPassword = password_hash($newPass, PASSWORD_BCRYPT, ['cost' => 12]);
            try {
                // Use query() method instead of prepare()
                $result = $db->query(
                    'UPDATE users SET password = ? WHERE id = ?',
                    [$hashedPassword, $currentUser['id']]
                );
                
                ob_end_clean();
                if ($result) {
                    echo json_encode(['success' => true, 'message' => 'Password updated successfully']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to update password']);
                }
            } catch (Exception $e) {
                error_log('Password update error: ' . $e->getMessage());
                ob_end_clean();
                echo json_encode(['success' => false, 'message' => 'Error updating password: ' . $e->getMessage()]);
            }
            exit;

        // Add credits (AJAX)
        case 'add_credits':
            $amount = floatval($_POST['amount'] ?? 0);
            if ($amount <= 0) {
                echo json_encode(['success' => false, 'message' => 'Invalid amount']);
                exit;
            }
            $ok = $user->updateWalletBalance($currentUser['id'], $amount);
            if ($ok) {
                $balance = $user->getWalletBalance($currentUser['id']);
                echo json_encode(['success' => true, 'message' => 'Credits added', 'balance' => $balance]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to add credits']);
            }
            exit;

        // Submit support ticket (AJAX)
        case 'submit_ticket':
            $title = trim($_POST['title'] ?? '');
            $body  = trim($_POST['body'] ?? '');
            if ($title === '' || $body === '') {
                echo json_encode(['success' => false, 'message' => 'Please fill all fields']);
                exit;
            }
            if (method_exists($db, 'insert')) {
                $ticketId = $db->insert('support_tickets', [
                    'user_id'    => $currentUser['id'],
                    'title'      => $title,
                    'body'       => $body,
                    'status'     => 'open',
                    'created_at' => date('Y-m-d H:i:s')
                ]);
                if ($ticketId) echo json_encode(['success' => true, 'message' => 'Ticket submitted', 'ticket_id' => $ticketId]);
                else echo json_encode(['success' => false, 'message' => 'Failed to submit ticket']);
            } else {
                $sql  = "INSERT INTO support_tickets (user_id, title, body, status, created_at) VALUES (:uid, :title, :body, 'open', NOW())";
                $stmt = $db->prepare($sql);
                $ok   = $stmt->execute([':uid' => $currentUser['id'], ':title' => $title, ':body' => $body]);
                if ($ok) echo json_encode(['success' => true, 'message' => 'Ticket submitted']);
                else echo json_encode(['success' => false, 'message' => 'Failed to submit ticket']);
            }
            exit;

        // Create payment order
        case 'create_payment_order':
            error_log('Creating payment order...');
            $amount = floatval($_POST['amount'] ?? 0);
            error_log('Amount: ' . $amount);
            
            if ($amount <= 0 || $amount > 100000) {
                error_log('Invalid amount: ' . $amount);
                echo json_encode(['success' => false, 'message' => 'Invalid amount']);
                exit;
            }
            
            $orderId = 'ORD-' . time() . '-' . $currentUser['id'];
            error_log('Generated Order ID: ' . $orderId);
            
            $result = $db->insert('payment_orders', [
                'order_id' => $orderId,
                'user_id' => $currentUser['id'],
                'amount' => $amount,
                'payment_method' => 'manual_upi',
                'status' => 'pending',
                'created_at' => date('Y-m-d H:i:s')
            ]);
            
            error_log('Insert result: ' . ($result ? 'SUCCESS' : 'FAILED'));
            
            if ($result) {
                error_log('Payment order created successfully');
                echo json_encode(['success' => true, 'order_id' => $orderId]);
            } else {
                error_log('Failed to insert payment order into database');
                echo json_encode(['success' => false, 'message' => 'Failed to create order']);
            }
            exit;

        // Submit manual payment
        case 'submit_manual_payment':
            $orderId = trim($_POST['order_id'] ?? '');
            $txnId = trim($_POST['transaction_id'] ?? '');
            
            if (empty($orderId) || empty($txnId)) {
                echo json_encode(['success' => false, 'message' => 'Missing required fields']);
                exit;
            }
            
            // Check if file uploaded
            if (empty($_FILES['payment_screenshot'])) {
                echo json_encode(['success' => false, 'message' => 'Screenshot required']);
                exit;
            }
            
            // Handle file upload
            $uploadsDir = __DIR__ . '/../uploads/payments/';
            if (!is_dir($uploadsDir)) {
                mkdir($uploadsDir, 0755, true);
            }
            
            $file = $_FILES['payment_screenshot'];
            $allowed = ['image/jpeg', 'image/png', 'image/gif'];
            
            if (!in_array($file['type'], $allowed) || $file['size'] > 5000000) {
                echo json_encode(['success' => false, 'message' => 'Invalid file or too large']);
                exit;
            }
            
            $filename = 'payment_' . $currentUser['id'] . '_' . time() . '.png';
            $filepath = $uploadsDir . $filename;
            
            if (!move_uploaded_file($file['tmp_name'], $filepath)) {
                echo json_encode(['success' => false, 'message' => 'Failed to upload file']);
                exit;
            }
            
            // Update payment order
            $screenshotPath = 'uploads/payments/' . $filename;
            $updated = $db->update('payment_orders', 
                [
                    'status' => 'awaiting_approval',
                    'transaction_id' => $txnId,
                    'screenshot_path' => $screenshotPath
                ],
                'order_id = :order_id AND user_id = :user_id',
                ['order_id' => $orderId, 'user_id' => $currentUser['id']]
            );
            
            if ($updated) {
                error_log('Payment order updated successfully');
                
                // Send Telegram notification if configured
                require_once(__DIR__ . '/../classes/Payment.php');
                $payment = new Payment();
                $paymentDetails = $payment->getPaymentDetails();
                
                error_log('Payment Details for Telegram: ' . json_encode($paymentDetails));
                
                if (!empty($paymentDetails['telegram_bot_token']) && !empty($paymentDetails['telegram_admin_chat_id'])) {
                    error_log('Sending Telegram notification...');
                    require_once(__DIR__ . '/../classes/TelegramBot.php');
                    $order = $db->fetch('SELECT * FROM payment_orders WHERE order_id = ?', [$orderId]);
                    error_log('Order found: ' . json_encode($order));
                    
                    $telegram = new TelegramBot($paymentDetails['telegram_bot_token'], $paymentDetails['telegram_admin_chat_id']);
                    $message = "💳 NEW PAYMENT SUBMITTED\n\nUser: {$currentUser['name']}\nEmail: {$currentUser['email']}\nAmount: ₹{$order['amount']}\nUTR: {$txnId}";
                    error_log('Sending message: ' . $message);
                    
                    $telegram->sendApprovalButtons(
                        $paymentDetails['telegram_admin_chat_id'],
                        $message,
                        $orderId
                    );
                    error_log('Telegram notification sent');
                } else {
                    error_log('Telegram not configured - token or chat_id is empty');
                }
                
                echo json_encode(['success' => true, 'message' => 'Payment submitted successfully']);
            } else {
                error_log('Failed to update payment order');
                echo json_encode(['success' => false, 'message' => 'Failed to process payment']);
            }
            exit;

        // Clear all search history
        case 'clear_search_history':
            try {
                $result = $db->query(
                    'DELETE FROM search_logs WHERE user_id = ?',
                    [$currentUser['id']]
                );
                if ($result !== false) {
                    ob_end_clean();
                    echo json_encode(['success' => true, 'message' => 'All search history cleared successfully']);
                } else {
                    ob_end_clean();
                    echo json_encode(['success' => false, 'message' => 'Failed to clear search history']);
                }
            } catch (Exception $e) {
                ob_end_clean();
                echo json_encode(['success' => false, 'message' => 'Error clearing search history: ' . $e->getMessage()]);
            }
            exit;

        // Clear search history by type (mobile or aadhaar)
        case 'clear_search_history_by_type':
            try {
                $type = trim($_POST['type'] ?? '');
                if (!in_array($type, ['mobile', 'aadhaar'])) {
                    ob_end_clean();
                    echo json_encode(['success' => false, 'message' => 'Invalid search type']);
                    exit;
                }
                
                $result = $db->query(
                    'DELETE FROM search_logs WHERE user_id = ? AND type = ?',
                    [$currentUser['id'], $type]
                );
                if ($result !== false) {
                    ob_end_clean();
                    echo json_encode(['success' => true, 'message' => 'All ' . $type . ' searches cleared successfully']);
                } else {
                    ob_end_clean();
                    echo json_encode(['success' => false, 'message' => 'Failed to clear search history']);
                }
            } catch (Exception $e) {
                ob_end_clean();
                echo json_encode(['success' => false, 'message' => 'Error clearing search history: ' . $e->getMessage()]);
            }
            exit;

        default:
            echo json_encode(['success' => false, 'message' => 'Unknown action']);
            exit;
    }
}
// ---------- End AJAX handlers ----------
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Dashboard - <?php echo APP_NAME; ?></title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://unpkg.com/feather-icons"></script>

<style>
:root {--primary-color:#007AFF;--secondary-color:#F2F2F7;--text-color:#1C1C1E;--light-gray:#F5F6F8;--border-color:#E5E5EA;--shadow-color:rgba(0,0,0,0.1);}
*{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;box-sizing:border-box;}
body{background:var(--light-gray);color:var(--text-color);margin:0}

/* === Off-canvas Sidebar (slide-in) === */
.sidebar{
  position:fixed; top:0; left:0; height:100vh; width:260px;
  background:#fff; border-right:1px solid var(--border-color);
  box-shadow:0 4px 20px var(--shadow-color);
  z-index:1040; padding-bottom:20px; overflow-y:auto;
  transform:translateX(0); transition:transform .3s ease;
}
.sidebar-header{padding:1.25rem 1rem;border-bottom:1px solid var(--border-color);text-align:center}
.sidebar-menu{list-style:none;margin:0;padding:0}
.sidebar-menu a{display:flex;align-items:center;gap:.75rem;padding:0.9rem 1rem;color:var(--text-color);text-decoration:none;border-left:3px solid transparent;transition:all .2s}
.sidebar-menu a:hover,.sidebar-menu a.active{background:rgba(0,122,255,.08);border-left-color:var(--primary-color);color:var(--primary-color)}
.sidebar-menu i{width:20px;height:20px}

/* Overlay for mobile when sidebar is open */
.overlay{
  display:none; position:fixed; inset:0; background:rgba(0,0,0,.35); z-index:1035;
}

/* Main content */
.main-content{
  margin-left:260px; padding:16px; transition:margin-left .3s ease;
}
.top-bar{
  background:#fff;border-radius:16px;padding:1rem 1.25rem;margin-bottom:1rem;
  box-shadow:0 4px 20px var(--shadow-color);
  display:flex; align-items:center; justify-content:space-between; gap:10px;
}
.wallet-badge{
  background:linear-gradient(135deg,#007AFF 0%,#0056CC 100%); color:#fff;
  padding:.5rem 1rem; border-radius:20px; font-weight:600; font-size:.9rem;
}
.card{background:#fff;border:none;border-radius:16px;box-shadow:0 4px 20px var(--shadow-color);margin-bottom:1rem}
.card-header{background:transparent;border-bottom:1px solid var(--border-color);padding:1.1rem;border-radius:16px 16px 0 0}
.card-body{padding:1.1rem}
.btn-primary{background:linear-gradient(135deg,#007AFF 0%,#0056CC 100%);border:none;border-radius:12px;padding:10px 16px;font-weight:600}
.btn-primary:hover{transform:translateY(-1px);box-shadow:0 8px 22px rgba(0,122,255,.35)}
.form-control{border-radius:12px;border:2px solid var(--border-color);padding:.75rem 1rem}
.form-control:focus{border-color:var(--primary-color);box-shadow:0 0 0 .25rem rgba(0,122,255,.2)}
.section{display:none}
.section.active{display:block}
.table-responsive{overflow-x:auto}
.small-muted{color:#6c757d;font-size:.9rem}

/* Sidebar toggle button */
.sidebar-toggle{
  display:none; border:none; background:#fff; border-radius:12px; padding:.4rem .6rem;
  box-shadow:0 4px 12px rgba(0,0,0,.08);
}

/* === Responsive === */
@media (max-width: 991px){
  .sidebar{transform:translateX(-100%);}        /* hidden by default on mobile */
  .sidebar.open{transform:translateX(0);}        /* visible when toggled */
  .overlay.show{display:block;}
  .main-content{margin-left:0; padding:14px}
  .sidebar-toggle{display:inline-flex; align-items:center; justify-content:center}
  .top-bar{gap:8px}
  .wallet-badge{font-size:.8rem;padding:.4rem .7rem}
  .btn, .btn-primary{width:100%}
  .text-end{text-align:left !important}
}
@media (max-width: 576px){
  .top-bar small.text-muted{display:none}
}
</style>
</head>
<body>

<!-- Mobile overlay -->
<div class="overlay" id="pageOverlay"></div>

<!-- Sidebar Toggle (in top bar; rendered later with JS icons) -->
<!-- We place it before main so it's focusable -->
<button class="sidebar-toggle" id="sidebarToggle" aria-label="Open menu" style="position:fixed;top:12px;left:12px;z-index:1050;">
  <i data-feather="menu"></i>
</button>

<!-- Sidebar -->
<aside class="sidebar" id="sidebar">
  <div class="sidebar-header">
    <h5 class="mb-1" id="user-name"><?php echo htmlspecialchars($currentUser['name']); ?></h5>
    <small class="text-muted">User Dashboard</small>
  </div>

  <!-- Wallet Sidebar Widget -->
  <?php include(__DIR__ . '/wallet_sidebar.php'); ?>

  <ul class="sidebar-menu">
    <li><a href="#" data-section="dashboard" class="nav-link active" onclick="showSection('dashboard')"><i data-feather="home"></i> Dashboard</a></li>
    <li><a href="#" data-section="mobile" class="nav-link" onclick="showSection('mobile')"><i data-feather="search"></i> Mobile Search</a></li>
    <li><a href="#" data-section="aadhaar" class="nav-link" onclick="showSection('aadhaar')"><i data-feather="credit-card"></i> Aadhaar Search</a></li>
    <li><a href="#" data-section="wallet" class="nav-link" onclick="showSection('wallet')"><i data-feather="dollar-sign"></i> Wallet <span class="badge bg-primary ms-auto" id="wallet-badge"><?php echo number_format($walletBalance, 2); ?></span></a></li>
    <li><a href="#" data-section="analytics" class="nav-link" onclick="showSection('analytics')"><i data-feather="bar-chart-2"></i> Analytics</a></li>
    <li><a href="#" data-section="profile" class="nav-link" onclick="showSection('profile')"><i data-feather="user"></i> Profile</a></li>
    <li><a href="#" data-section="support" class="nav-link" onclick="showSection('support')"><i data-feather="message-circle"></i> Support <?php if (!empty($unreadMessages)): ?><span class="badge bg-danger ms-auto" id="unread-count"><?php echo count($unreadMessages); ?></span><?php endif; ?></a></li>
    <li><a href="chatbot.php" class="nav-link"><i data-feather="message-square"></i> 💬 Chat Admin</a></li>
    <li><a href="../logout.php"><i data-feather="log-out"></i> Logout</a></li>
  </ul>
</aside>

<!-- Main Content -->
<main class="main-content" id="mainContent">
  <div class="top-bar">
    <div class="d-flex align-items-center gap-2">
      <!-- show hamburger only on mobile (CSS handles visibility) -->
      <button class="sidebar-toggle d-inline-flex d-lg-none" id="sidebarToggleTop" aria-label="Open menu">
        <i data-feather="menu"></i>
      </button>
      <div>
        <h4 class="mb-0">Dashboard</h4>
        <small class="text-muted">Welcome back, <span id="topbar-name"><?php echo htmlspecialchars($currentUser['name']); ?></span></small>
      </div>
    </div>
    <div class="d-flex align-items-center gap-3">
      <span class="wallet-badge" id="top-wallet">
        <i data-feather="inr-sign" style="width:16px;height:16px;" class="me-1"></i>
        <span id="wallet-amount"><?php echo number_format($walletBalance, 2); ?></span> Credits
      </span>
      <small class="text-muted">For Every Search <strong> ₹10 </strong>will Deducted <span id="topbar-name"></span></small>
    </div>
  </div>

  <!-- ALERT PLACEHOLDER -->
  <div id="global-alert"></div>

  <!-- SECTION: Dashboard / Welcome -->
  <div id="dashboard-section" class="section active">
    <!-- All Recent Searches -->
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">All Recent Searches</h5>
        <?php if (!empty($recentSearches)): ?>
          <button type="button" class="btn btn-sm btn-outline-danger" onclick="clearSearchHistory()">
            <i data-feather="trash-2" style="width: 16px; height: 16px;"></i> Clear All
          </button>
        <?php endif; ?>
      </div>
      <div class="card-body">
        <?php if (empty($recentSearches)): ?>
          <p class="text-muted">No searches yet</p>
        <?php else: ?>
          <div class="table-responsive">
            <table class="table table-hover table-striped">
              <thead class="table-light">
                <tr>
                  <th>Type</th>
                  <th>Query</th>
                  <th>Cost</th>
                  <th>Status</th>
                  <th>Date</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($recentSearches as $s): ?>
                  <tr>
                    <td>
                      <span class="badge bg-<?php echo $s['type'] === 'mobile' ? 'primary' : 'success'; ?>">
                        <?php echo strtoupper($s['type']); ?>
                      </span>
                    </td>
                    <td>
                      <strong><?php echo htmlspecialchars($s['query']); ?></strong>
                    </td>
                    <td>
                      <span class="text-muted">₹<?php echo number_format($s['cost'], 1); ?></span>
                    </td>
                    <td>
                      <span class="badge bg-<?php echo $s['status'] === 'success' ? 'success' : 'danger'; ?>">
                        <?php echo strtoupper($s['status']); ?>
                      </span>
                    </td>
                    <td>
                      <small class="text-muted"><?php echo date('M j, Y H:i', strtotime($s['created_at'])); ?></small>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <!-- SECTION: Mobile Search -->
  <div id="mobile-section" class="section">
    <div class="card">
      <div class="card-header"><h5>Mobile Lookup</h5></div>
      <div class="card-body">
        <form id="mobile-search-form" class="row g-3">
          <div class="col-md-8">
            <div style="position: relative;">
              <input type="text" id="mobile-input" class="form-control" placeholder="Enter 10-digit mobile number" pattern="[6-9]\d{9}" required autocomplete="off">
              <div id="mobile-suggestions" class="suggestions-dropdown" style="display: none; position: absolute; top: 100%; left: 0; right: 0; background: white; border: 1px solid #ddd; border-top: none; border-radius: 0 0 4px 4px; max-height: 200px; overflow-y: auto; z-index: 1000; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"></div>
            </div>
          </div>
          <div class="col-md-4">
            <button type="submit" class="btn btn-primary w-100">Search</button>
          </div>
        </form>
        <div id="mobile-result" class="mt-4"></div>

        <!-- Recent Mobile Searches -->
        <hr>
        <div class="d-flex justify-content-between align-items-center mt-4 mb-3">
          <h6 class="mb-0">Recent Mobile Searches</h6>
          <?php 
            $mobilSearches = array_filter($recentSearches, fn($s) => $s['type'] === 'mobile');
            if (!empty($mobilSearches)): 
          ?>
            <button type="button" class="btn btn-sm btn-outline-danger" onclick="clearSearchType('mobile')">
              <i data-feather="trash-2" style="width: 14px; height: 14px;"></i> Clear
            </button>
          <?php endif; ?>
        </div>
        <div id="recent-mobile-searches" class="mt-3">
          <?php 
            if (empty($mobilSearches)): 
          ?>
            <p class="text-muted small">No mobile searches yet</p>
          <?php else: ?>
            <div class="list-group">
              <?php foreach ($mobilSearches as $s): ?>
                <button type="button" class="list-group-item list-group-item-action" onclick="searchMobileFromHistory('<?php echo htmlspecialchars($s['query']); ?>')">
                  <div class="d-flex w-100 justify-content-between align-items-center">
                    <strong><?php echo htmlspecialchars($s['query']); ?></strong>
                    <small><span class="badge bg-<?php echo $s['status'] === 'success' ? 'success' : 'danger'; ?>"><?php echo strtoupper($s['status']); ?></span></small>
                  </div>
                  <small class="text-muted"><?php echo date('M j, Y H:i', strtotime($s['created_at'])); ?></small>
                </button>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>

  <!-- SECTION: Aadhaar Search -->
  <div id="aadhaar-section" class="section">
    <div class="card">
      <div class="card-header"><h5>Aadhaar Lookup</h5></div>
      <div class="card-body">
        <form id="aadhaar-search-form" class="row g-3">
          <div class="col-md-8">
            <div style="position: relative;">
              <input type="text" id="aadhaar-input" class="form-control" placeholder="Enter 12-digit Aadhaar number" pattern="\d{12}" required autocomplete="off">
              <div id="aadhaar-suggestions" class="suggestions-dropdown" style="display: none; position: absolute; top: 100%; left: 0; right: 0; background: white; border: 1px solid #ddd; border-top: none; border-radius: 0 0 4px 4px; max-height: 200px; overflow-y: auto; z-index: 1000; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"></div>
            </div>
          </div>
          <div class="col-md-4">
            <button type="submit" class="btn btn-primary w-100">Search</button>
          </div>
        </form>
        <div id="aadhaar-result" class="mt-4"></div>

        <!-- Recent Aadhaar Searches -->
        <hr>
        <div class="d-flex justify-content-between align-items-center mt-4 mb-3">
          <h6 class="mb-0">Recent Aadhaar Searches</h6>
          <?php 
            $aadhaarSearches = array_filter($recentSearches, fn($s) => $s['type'] === 'aadhaar');
            if (!empty($aadhaarSearches)): 
          ?>
            <button type="button" class="btn btn-sm btn-outline-danger" onclick="clearSearchType('aadhaar')">
              <i data-feather="trash-2" style="width: 14px; height: 14px;"></i> Clear
            </button>
          <?php endif; ?>
        </div>
        <div id="recent-aadhaar-searches" class="mt-3">
          <?php 
            if (empty($aadhaarSearches)): 
          ?>
            <p class="text-muted small">No Aadhaar searches yet</p>
          <?php else: ?>
            <div class="list-group">
              <?php foreach ($aadhaarSearches as $s): ?>
                <button type="button" class="list-group-item list-group-item-action" onclick="searchAadhaarFromHistory('<?php echo htmlspecialchars($s['query']); ?>')">
                  <div class="d-flex w-100 justify-content-between align-items-center">
                    <strong><?php echo htmlspecialchars($s['query']); ?></strong>
                    <small><span class="badge bg-<?php echo $s['status'] === 'success' ? 'success' : 'danger'; ?>"><?php echo strtoupper($s['status']); ?></span></small>
                  </div>
                  <small class="text-muted"><?php echo date('M j, Y H:i', strtotime($s['created_at'])); ?></small>
                </button>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>

  <!-- SECTION: Wallet -->
  <div id="wallet-section" class="section">
    <div class="card">
      <div class="card-header"><h5>Wallet - Add Credits</h5></div>
      <div class="card-body">
        <p class="small-muted">Current balance:</p>
        <h3 id="wallet-display" class="mb-4">₹ <?php echo number_format($walletBalance, 2); ?></h3>

        <hr>

        <div id="wallet-add-credits-form-container">
          <h6>Enter Amount to Add</h6>
          <div class="row g-3 mb-4">
            <div class="col-md-8">
              <input type="number" id="wallet-credit-amount" class="form-control" min="10" max="100000" placeholder="Enter amount (₹10 - ₹100,000)">
            </div>
            <div class="col-md-4">
              <button type="button" class="btn btn-primary w-100" onclick="proceedToPayment()">Proceed to Pay</button>
            </div>
          </div>
        </div>

        <hr>

        <div id="payment-info" style="display:none;">
          <h6>Payment Details</h6>
          
          <!-- QR Code -->
          <div class="mb-4">
            <p class="text-muted small">Scan this QR code to pay</p>
            <div style="text-align: center; background: #f8f9fa; padding: 20px; border-radius: 12px;">
              <img id="payment-qr" src="" alt="QR Code" style="max-width: 250px; border-radius: 8px;">
            </div>
          </div>

          <!-- UPI ID -->
          <div class="mb-4">
            <p class="text-muted small">Or use this UPI ID</p>
            <div style="display: flex; gap: 10px;">
              <input type="text" id="payment-upi" class="form-control" readonly style="background: #f8f9fa;">
              <button type="button" class="btn btn-secondary" onclick="copyUPI()">
                <i data-feather="copy"></i> Copy
              </button>
            </div>
          </div>

          <!-- Transaction Details -->
          <div class="card bg-light mb-4">
            <div class="card-body">
              <h6>Payment Reference</h6>
              <p><strong>Amount:</strong> ₹<span id="payment-amount">0</span></p>
              <p><strong>Order ID:</strong> <span id="payment-order-id">-</span></p>
              <p class="text-muted small">After payment, you'll need to provide transaction ID/UTR</p>
            </div>
          </div>

          <!-- Screenshot & UTR Upload -->
          <div class="mb-3">
            <label class="form-label">Transaction ID / UTR (Required)</label>
            <input type="text" id="payment-utr" class="form-control" placeholder="Enter UTR number from your bank">
          </div>

          <div class="mb-3">
            <label class="form-label">Payment Screenshot (Required)</label>
            <div style="border: 2px dashed #007AFF; padding: 40px 20px; border-radius: 12px; text-align: center; cursor: pointer;" onclick="document.getElementById('screenshot-input').click()">
              <i data-feather="upload-cloud" style="width: 40px; height: 40px; color: #007AFF; margin-bottom: 10px;"></i>
              <p class="text-muted">Click to upload or drag and drop</p>
              <small>PNG, JPG, GIF (Max 5MB)</small>
              <input type="file" id="screenshot-input" accept="image/*" style="display: none;">
            </div>
            <div id="screenshot-preview" style="display: none; margin-top: 15px;">
              <img id="preview-img" src="" alt="Preview" style="max-width: 100%; border-radius: 8px;">
            </div>
          </div>

          <!-- Submit Payment -->
          <button type="button" class="btn btn-success w-100 btn-lg" onclick="submitPayment()">
            <i data-feather="check-circle"></i> Submit Payment
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- SECTION: Profile -->
  <div id="profile-section" class="section">
    <div class="card">
      <div class="card-header"><h5>Profile</h5></div>
      <div class="card-body">
        <form id="profile-form">
          <div class="mb-3">
            <label class="form-label">Full Name</label>
            <input type="text" name="name" id="profile-name" class="form-control" required value="<?php echo htmlspecialchars($currentUser['name']); ?>">
          </div>
          <div class="mb-3">
            <label class="form-label">Email</label>
            <input type="email" name="email" id="profile-email" class="form-control" required value="<?php echo htmlspecialchars($currentUser['email']); ?>">
          </div>
          <div class="d-flex gap-2 justify-content-end">
            <button type="submit" class="btn btn-primary">Save Profile</button>
            <button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#passwordModal">Change Password</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- SECTION: Support -->
  <div id="support-section" class="section">
    <div class="card">
      <div class="card-header"><h5>💬 Support Chat</h5></div>
      <div class="card-body">
        <p class="text-muted mb-3">Need help? Chat directly with our admin team in real-time.</p>
        <a href="support.php" class="btn btn-primary btn-lg w-100">
          <i data-feather="message-circle"></i> Open Chat
        </a>
      </div>
    </div>
  </div>

  <!-- SECTION: AI Analytics -->
  <div id="analytics-section" class="section">
    <div class="card">
      <div class="card-header"><h5>📊 Analytics & Insights</h5></div>
      <div class="card-body">
        <div class="row">
          <!-- Total Searches -->
          <div class="col-md-4 mb-3">
            <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 8px; text-align: center;">
              <div style="font-size: 32px; font-weight: bold; margin-bottom: 5px;" id="total-searches">0</div>
              <div style="font-size: 14px; opacity: 0.9;">Total Searches</div>
            </div>
          </div>
          
          <!-- Mobile Searches -->
          <div class="col-md-4 mb-3">
            <div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; padding: 20px; border-radius: 8px; text-align: center;">
              <div style="font-size: 32px; font-weight: bold; margin-bottom: 5px;" id="mobile-searches">0</div>
              <div style="font-size: 14px; opacity: 0.9;">📱 Mobile Searches</div>
            </div>
          </div>
          
          <!-- Aadhaar Searches -->
          <div class="col-md-4 mb-3">
            <div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 20px; border-radius: 8px; text-align: center;">
              <div style="font-size: 32px; font-weight: bold; margin-bottom: 5px;" id="aadhaar-searches">0</div>
              <div style="font-size: 14px; opacity: 0.9;">🆔 Aadhaar Searches</div>
            </div>
          </div>
        </div>
        
        <hr>
        
        <div class="row">
          <!-- Credits Spent -->
          <div class="col-md-6 mb-3">
            <div style="background: #fff3cd; padding: 15px; border-radius: 8px; border-left: 4px solid #ffc107;">
              <div style="font-size: 12px; color: #856404; margin-bottom: 5px;">💰 Credits Spent</div>
              <div style="font-size: 24px; font-weight: bold; color: #333;">₹<span id="credits-spent">0</span></div>
            </div>
          </div>
          
          <!-- Current Balance -->
          <div class="col-md-6 mb-3">
            <div style="background: #d4edda; padding: 15px; border-radius: 8px; border-left: 4px solid #28a745;">
              <div style="font-size: 12px; color: #155724; margin-bottom: 5px;">💵 Current Balance</div>
              <div style="font-size: 24px; font-weight: bold; color: #333;">₹<span id="current-balance">0</span></div>
            </div>
          </div>
        </div>
        
        <hr>
        
        <div class="row">
          <!-- Success Rate -->
          <div class="col-md-6 mb-3">
            <div style="background: #d1ecf1; padding: 15px; border-radius: 8px; border-left: 4px solid #17a2b8;">
              <div style="font-size: 12px; color: #0c5460; margin-bottom: 5px;">✅ Success Rate</div>
              <div style="font-size: 24px; font-weight: bold; color: #333;"><span id="success-rate">0</span>%</div>
            </div>
          </div>
          
          <!-- Account Status -->
          <div class="col-md-6 mb-3">
            <div style="background: #e2e3e5; padding: 15px; border-radius: 8px; border-left: 4px solid #6c757d;">
              <div style="font-size: 12px; color: #383d41; margin-bottom: 5px;">🟢 Account Status</div>
              <div style="font-size: 18px; font-weight: bold; color: #28a745;">Active</div>
            </div>
          </div>
        </div>
        
        <hr>
        
        <!-- Recent Activity -->
        <h6 class="mt-4 mb-3">📈 Recent Search Activity</h6>
        <div id="recent-activity" style="font-size: 13px; color: #666;">
          <p class="text-muted">Loading activity data...</p>
        </div>
        
        <hr>
        
        <button onclick="loadAnalytics()" class="btn btn-sm btn-outline-primary">
          <i data-feather="refresh-cw" style="width: 14px; height: 14px;"></i> Refresh Data
        </button>
      </div>
    </div>
  </div>

</main>

<!-- scripts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
feather.replace();

/* ======= GLOBAL VARIABLES ======= */
let currentOrderId = null;
let currentAmount = null;

/* ======= Sidebar toggle (slide-in) ======= */
const sidebar        = document.getElementById('sidebar');
const overlay        = document.getElementById('pageOverlay');
const toggleBtns     = [document.getElementById('sidebarToggle'), document.getElementById('sidebarToggleTop')].filter(Boolean);

function openSidebar(){
  sidebar.classList.add('open');
  overlay.classList.add('show');
  document.body.style.overflow = 'hidden';
}
function closeSidebar(){
  sidebar.classList.remove('open');
  overlay.classList.remove('show');
  document.body.style.overflow = '';
}
toggleBtns.forEach(btn => btn.addEventListener('click', (e)=>{ e.preventDefault(); openSidebar(); }));
overlay.addEventListener('click', closeSidebar);
// Close when a nav link is clicked (on mobile)
document.querySelectorAll('.sidebar-menu a.nav-link').forEach(a=>{
  a.addEventListener('click', ()=>{ if (window.innerWidth <= 991) closeSidebar(); });
});

/* ======= Section switcher ======= */
function showSection(name) {
  document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
  document.querySelectorAll('.sidebar-menu .nav-link').forEach(a => a.classList.remove('active'));
  const el = document.getElementById(name + '-section');
  if (el) el.classList.add('active');
  const link = document.querySelector('.sidebar-menu a[data-section="'+name+'"]');
  if (link) link.classList.add('active');
}

/* ======= Alerts ======= */
function showAlert(type, message, timeout=4000) {
  const alertBox = document.getElementById('global-alert');
  alertBox.innerHTML = `<div class="alert alert-${type} alert-dismissible fade show" role="alert">${message}<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>`;
  if (timeout>0) setTimeout(()=>{ alertBox.innerHTML = ''; }, timeout);
}

/* ======= AJAX helper ======= */
async function postForm(action, data) {
  data = data || {};
  data.action = action;
  const formData = new FormData();
  for (const k in data) formData.append(k, data[k]);
  
  try {
    const resp = await fetch(location.href, { method: 'POST', body: formData });
    
    if (!resp.ok) {
      throw new Error('HTTP ' + resp.status);
    }
    
    const text = await resp.text();
    console.log('postForm response:', text);
    
    const json = JSON.parse(text);
    return json;
  } catch (error) {
    console.error('postForm error:', error);
    return { success: false, message: 'Request failed: ' + error.message };
  }
}

/* ======= Suggestions Dropdown ======= */
async function getSuggestions(type, query) {
  if (query.length === 0) {
    document.getElementById(type + '-suggestions').style.display = 'none';
    return;
  }
  try {
    const res = await fetch(`../api/get_suggestions.php?type=${type}&query=${encodeURIComponent(query)}`);
    const data = await res.json();
    
    const container = document.getElementById(type + '-suggestions');
    if (data.suggestions && data.suggestions.length > 0) {
      container.innerHTML = data.suggestions.map(s => 
        `<div style="padding: 8px 12px; cursor: pointer; border-bottom: 1px solid #eee; hover-bg: #f5f5f5;" onmouseover="this.style.backgroundColor='#f5f5f5'" onmouseout="this.style.backgroundColor='transparent'" onclick="selectSuggestion('${type}', '${s}')">${s}</div>`
      ).join('');
      container.style.display = 'block';
    } else {
      container.style.display = 'none';
    }
  } catch (error) {
    console.error('Suggestions error:', error);
  }
}

function selectSuggestion(type, value) {
  document.getElementById(type + '-input').value = value;
  document.getElementById(type + '-suggestions').style.display = 'none';
}

document.getElementById('mobile-input').addEventListener('input', function() {
  getSuggestions('mobile', this.value);
});

document.getElementById('mobile-input').addEventListener('blur', function() {
  setTimeout(() => {
    document.getElementById('mobile-suggestions').style.display = 'none';
  }, 200);
});

document.getElementById('mobile-input').addEventListener('focus', function() {
  if (this.value.length > 0) {
    getSuggestions('mobile', this.value);
  }
});

document.getElementById('aadhaar-input').addEventListener('input', function() {
  getSuggestions('aadhaar', this.value);
});

document.getElementById('aadhaar-input').addEventListener('blur', function() {
  setTimeout(() => {
    document.getElementById('aadhaar-suggestions').style.display = 'none';
  }, 200);
});

document.getElementById('aadhaar-input').addEventListener('focus', function() {
  if (this.value.length > 0) {
    getSuggestions('aadhaar', this.value);
  }
});

/* ======= Analytics ======= */
async function loadAnalytics() {
  try {
    const res = await fetch('../api/get_analytics.php');
    const data = await res.json();
    
    if (data.success) {
      // Update stats
      document.getElementById('total-searches').textContent = data.total_searches;
      document.getElementById('mobile-searches').textContent = data.mobile_searches;
      document.getElementById('aadhaar-searches').textContent = data.aadhaar_searches;
      document.getElementById('credits-spent').textContent = parseFloat(data.credits_spent).toFixed(2);
      document.getElementById('current-balance').textContent = parseFloat(data.current_balance).toFixed(2);
      document.getElementById('success-rate').textContent = data.success_rate;
      
      // Update recent activity
      const activityDiv = document.getElementById('recent-activity');
      if (data.recent_searches && data.recent_searches.length > 0) {
        activityDiv.innerHTML = data.recent_searches.map((s, i) => 
          `<div style="padding: 8px 0; border-bottom: 1px solid #eee;">
             <div style="display: flex; justify-content: space-between; align-items: center;">
               <div><span style="font-size: 12px; background: ${s.type === 'mobile' ? '#667eea' : '#4facfe'}; color: white; padding: 2px 8px; border-radius: 4px; margin-right: 8px;">${s.type === 'mobile' ? '📱' : '🆔'}</span>${s.query}</div>
               <small style="color: #999;">${s.time_ago}</small>
             </div>
           </div>`
        ).join('');
      } else {
        activityDiv.innerHTML = '<p class="text-muted small">No searches yet</p>';
      }
    }
  } catch (error) {
    console.error('Analytics error:', error);
    document.getElementById('recent-activity').innerHTML = '<p class="text-danger small">Failed to load analytics</p>';
  }
}

// Load analytics when analytics section is shown
const origShowSection = window.showSection;
window.showSection = function(name) {
  origShowSection(name);
  if (name === 'analytics') {
    loadAnalytics();
  }
};

/* ======= Mobile search ======= */
document.getElementById('mobile-search-form').addEventListener('submit', async function(e){
  e.preventDefault();
  const mobile = document.getElementById('mobile-input').value.trim();
  if (!/^[6-9]\d{9}$/.test(mobile)) { showAlert('warning','Invalid mobile number'); return; }
  const btn = this.querySelector('button[type="submit"]');
  btn.disabled = true; btn.innerText = 'Searching...';
  try {
    const res = await postForm('search_mobile', { mobile });
    if (res.success) {
      renderMobileResult(res.data, res.fallback);
      if (res.balance !== undefined) updateWalletDisplay(res.balance);
      showAlert('success', res.message || 'Search successful');
      prependRecentSearch('mobile', mobile, res.data?.cost || 0, 'success');
    } else showAlert('danger', res.message || 'Search failed');
  } catch {
    showAlert('danger', 'Request failed');
  } finally {
    btn.disabled = false; btn.innerText = 'Search';
  }
});

/* ======= Aadhaar search ======= */
document.getElementById('aadhaar-search-form').addEventListener('submit', async function(e){
  e.preventDefault();
  const aadhaar = document.getElementById('aadhaar-input').value.trim();
  if (!/^\d{12}$/.test(aadhaar)) { showAlert('warning','Invalid Aadhaar number'); return; }
  const btn = this.querySelector('button[type="submit"]');
  btn.disabled = true; btn.innerText = 'Searching...';
  try {
    const res = await postForm('search_aadhaar', { aadhaar });
    if (res.success) {
      renderAadhaarResult(res.data, res.fallback);
      if (res.balance !== undefined) updateWalletDisplay(res.balance);
      showAlert('success', res.message || 'Search successful');
      prependRecentSearch('aadhaar', aadhaar, res.data?.cost || 0, 'success');
    } else showAlert('danger', res.message || 'Search failed');
  } catch {
    showAlert('danger', 'Request failed');
  } finally {
    btn.disabled = false; btn.innerText = 'Search';
  }
});

/* ======= Profile update ======= */
document.getElementById('profile-form').addEventListener('submit', async function(e){
  e.preventDefault();
  const name  = document.getElementById('profile-name').value.trim();
  const email = document.getElementById('profile-email').value.trim();
  if (!name || !email) { showAlert('warning','Name and email required'); return; }
  const res = await postForm('update_profile', { name, email });
  if (res.success) {
    document.getElementById('user-name').innerText  = res.name;
    document.getElementById('topbar-name').innerText = res.name;
    showAlert('success', res.message);
  } else showAlert('danger', res.message || 'Failed to update profile');
});

/* ======= Change password (Modal) ======= */
async function submitPasswordChange() {
  const currentPassword = document.getElementById('current-password').value.trim();
  const newPassword = document.getElementById('new-password').value.trim();
  const confirmPassword = document.getElementById('confirm-password').value.trim();
  
  if (!currentPassword || !newPassword || !confirmPassword) { 
    showAlert('warning','All fields are required'); 
    return; 
  }
  
  if (newPassword !== confirmPassword) { 
    showAlert('warning','New passwords do not match'); 
    return; 
  }
  
  if (newPassword.length < 6) { 
    showAlert('warning','Password must be at least 6 characters'); 
    return; 
  }
  
  const btn = document.getElementById('password-submit-btn');
  btn.disabled = true; 
  btn.innerText = 'Updating...';
  
  try {
    const res = await postForm('change_password', { 
      current_password: currentPassword, 
      new_password: newPassword, 
      confirm_password: confirmPassword 
    });
    
    console.log('Password change response:', res);
    
    if (res.success) {
      showAlert('success', res.message || 'Password updated successfully');
      document.getElementById('current-password').value = '';
      document.getElementById('new-password').value = '';
      document.getElementById('confirm-password').value = '';
      
      // Close modal after 1 second
      setTimeout(() => {
        const modal = bootstrap.Modal.getInstance(document.getElementById('passwordModal'));
        if (modal) modal.hide();
      }, 1000);
    } else {
      showAlert('danger', res.message || 'Failed to update password');
    }
  } catch (error) {
    console.error('Password update error:', error);
    showAlert('danger', 'Error: ' + error.message);
  } finally {
    btn.disabled = false; 
    btn.innerText = 'Update Password';
  }
}

/* ======= Add credits ======= */
document.getElementById('add-credits-form').addEventListener('submit', async function(e){
  e.preventDefault();
  const amount = parseFloat(document.getElementById('credit-amount').value);
  if (!amount || amount <= 0) { showAlert('warning','Enter a valid amount'); return; }
  const btn = this.querySelector('button[type="submit"]');
  btn.disabled = true; btn.innerText = 'Adding...';
  const res = await postForm('add_credits', { amount });
  if (res.success) {
    updateWalletDisplay(res.balance);
    showAlert('success', res.message || 'Credits added');
  } else showAlert('danger', res.message || 'Failed to add credits');
  btn.disabled = false; btn.innerText = 'Add Credits';
});

/* ======= Support ticket ======= */
document.getElementById('support-form').addEventListener('submit', async function(e){
  e.preventDefault();
  const title = document.getElementById('support-title').value.trim();
  const body  = document.getElementById('support-body').value.trim();
  if (!title || !body) { showAlert('warning','Please fill title and message'); return; }
  const btn = this.querySelector('button[type="submit"]');
  btn.disabled = true; btn.innerText = 'Submitting...';
  const res = await postForm('submit_ticket', { title, body });
  if (res.success) {
    showAlert('success', res.message || 'Ticket submitted');
    const list = document.getElementById('tickets-list');
    const node = document.createElement('div');
    node.className = 'mb-2';
    node.innerHTML = `<strong>${escapeHtml(title)}</strong><br><small class="text-muted">open • just now</small>`;
    list.prepend(node);
    document.getElementById('support-title').value = '';
    document.getElementById('support-body').value = '';
  } else showAlert('danger', res.message || 'Failed to submit ticket');
  btn.disabled = false; btn.innerText = 'Submit Ticket';
});

/* ======= Render helpers ======= */
function renderMobileResult(data, fallback) {
  const box = document.getElementById('mobile-result');
  let html = '';
  if (Array.isArray(data)) {
    data.forEach(item => { html += mobileCardHtml(item, fallback); });
  } else if (typeof data === 'object' && data) {
    if (data.data && Array.isArray(data.data)) {
      data.data.forEach(item => { html += mobileCardHtml(item, fallback); });
    } else {
      html = mobileCardHtml(data, fallback);
    }
  } else {
    html = `<div class="alert alert-info">No result</div>`;
  }
  box.innerHTML = html;
}
function mobileCardHtml(item, fallback) {
  return `<div class="card search-result-card mb-3 p-3">
    ${fallback
      ? "<div class='alert alert-warning p-2 mb-2'>⚠️ Data Source: Database Backup</div>"
      : "<div class='alert alert-success p-2 mb-2'>🟢 Data Source: LIVE API</div>"
    }
    <div><strong>Name:</strong> ${escapeHtml(item.name || '')}</div>
    <div><strong>Mobile:</strong> ${escapeHtml(item.mobile || '')}</div>
    <div><strong>Father's Name:</strong> ${escapeHtml(item.fname || '')}</div>
    <div><strong>Circle:</strong> ${escapeHtml(item.circle || '')}</div>
    <div><strong>Alt No:</strong> ${escapeHtml(item.alt || '')}</div>
    <div><strong>Aadhar Card:</strong> ${escapeHtml(item.id || '')}</div>
    <div><strong>Address:</strong> ${escapeHtml(item.address || '')}</div>
  </div>`;
}

function renderAadhaarResult(data, fallback) {
  const box = document.getElementById('aadhaar-result');
  let html = '';
  if (typeof data === 'object' && data) {
    html += '<div class="card search-result-card p-3">';
    html += (fallback
      ? "<div class='alert alert-warning p-2 mb-2'>⚠️ Data Source: Database Backup</div>"
      : "<div class='alert alert-success p-2 mb-2'>🟢 Data Source: LIVE API</div>"
    );
    html += `<div><strong>Address:</strong> ${escapeHtml(data.address || '')}</div>`;
    html += `<div><strong>Home District:</strong> ${escapeHtml(data.homeDistName || data.homeDistrict || '')}</div>`;
    html += `<div><strong>Home State:</strong> ${escapeHtml(data.homeStateName || '')}</div>`;
    if (data.memberDetailsList && Array.isArray(data.memberDetailsList)) {
      html += '<hr><h6>Members</h6><ul>';
      data.memberDetailsList.forEach(m => {
        html += `<li>${escapeHtml(m.memberName || '')} — ${escapeHtml(m.releationship_name || '')} (${escapeHtml(m.memberId || '')})</li>`;
      });
      html += '</ul>';
    }
    html += '</div>';
  } else {
    html = '<div class="alert alert-info">No result</div>';
  }
  box.innerHTML = html;
}

function prependRecentSearch(type, query, cost, status) {
  try {
    const tbody = document.querySelector('#recent-searches-table');
    if (!tbody) return;
    const tr = document.createElement('tr');
    tr.innerHTML = `<td><span class="badge bg-${type==='mobile'?'primary':'success'}">${type.toUpperCase()}</span></td>
      <td>${escapeHtml(query)}</td>
      <td>${Number(cost || 0).toFixed(1)}</td>
      <td><span class="badge bg-${status==='success'?'success':'danger'}">${status.toUpperCase()}</span></td>
      <td>${new Date().toLocaleString()}</td>`;
    tbody.prepend(tr);
  } catch (e) {}
}

// Search from Mobile history
async function searchMobileFromHistory(mobile) {
  const input = document.getElementById('mobile-input');
  if (input) input.value = mobile;
  
  const form = document.getElementById('mobile-search-form');
  if (form) {
    const event = new Event('submit', { bubbles: true });
    form.dispatchEvent(event);
  }
}

// Search from Aadhaar history
async function searchAadhaarFromHistory(aadhaar) {
  const input = document.getElementById('aadhaar-input');
  if (input) input.value = aadhaar;
  
  const form = document.getElementById('aadhaar-search-form');
  if (form) {
    const event = new Event('submit', { bubbles: true });
    form.dispatchEvent(event);
  }
}

// Clear search history by type
async function clearSearchType(type) {
  if (!confirm(`Are you sure you want to clear all ${type} searches?`)) {
    return;
  }

  try {
    const response = await fetch(window.location.href, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: `action=clear_search_history_by_type&type=${type}`
    });

    const result = await response.json();
    if (result.success) {
      showAlert('success', result.message);
      setTimeout(() => location.reload(), 1000);
    } else {
      showAlert('danger', result.message);
    }
  } catch (error) {
    showAlert('danger', 'Error: ' + error.message);
  }
}

// Clear all search history
async function clearSearchHistory() {
  if (!confirm('Are you sure you want to clear all search history? This cannot be undone.')) {
    return;
  }

  try {
    const response = await fetch(window.location.href, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: 'action=clear_search_history'
    });

    const result = await response.json();
    if (result.success) {
      showAlert('success', result.message);
      setTimeout(() => location.reload(), 1000);
    } else {
      showAlert('danger', result.message);
    }
  } catch (error) {
    showAlert('danger', 'Error: ' + error.message);
  }
}

function updateWalletDisplay(amount) {
  document.getElementById('wallet-display').innerText = '₹ ' + Number(amount).toFixed(2);
  document.getElementById('wallet-amount').innerText = Number(amount).toFixed(2);
  const badge = document.getElementById('wallet-badge');
  if (badge) badge.innerText = Number(amount).toFixed(2);
}

function escapeHtml(str) {
  if (!str) return '';
  return String(str)
    .replace(/&/g,'&amp;')
    .replace(/</g,'&lt;')
    .replace(/>/g,'&gt;')
    .replace(/"/g,'&quot;');
}

// Start on dashboard
showSection('dashboard');

/* ======= WALLET PAYMENT FLOW ======= */
// Proceed to payment button click
function proceedToPayment() {
  console.log('Proceed to Payment clicked');
  
  const amount = parseFloat(document.getElementById('wallet-credit-amount').value);
  console.log('Amount:', amount);
  
  if (!amount || amount < 10 || amount > 100000) {
    showAlert('warning', 'Amount must be between ₹10 and ₹100,000');
    return;
  }

  const btn = event.target;
  btn.disabled = true;
  btn.innerText = 'Creating order...';

  const formData = new FormData();
  formData.append('action', 'create_payment_order');
  formData.append('amount', amount);
  
  console.log('Sending fetch to create order...');
  
  fetch('<?php echo $_SERVER['PHP_SELF']; ?>', {
    method: 'POST',
    body: formData
  })
  .then(response => {
    console.log('Response received:', response.status);
    return response.json();
  })
  .then(data => {
    console.log('JSON parsed:', data);
    
    if (data.success) {
      currentOrderId = data.order_id;
      currentAmount = amount;
      
      console.log('✅ Order created:', data.order_id);
      
      // Hide form, show payment info
      document.getElementById('wallet-add-credits-form-container').style.display = 'none';
      document.getElementById('payment-info').style.display = 'block';
      
      // Load payment details
      loadPaymentDetails(amount, data.order_id);
      
      showAlert('success', '✅ Payment details loaded');
    } else {
      showAlert('danger', '❌ Error: ' + (data.message || 'Failed to create order'));
      console.error('Error:', data);
      btn.disabled = false;
      btn.innerText = 'Proceed to Pay';
    }
  })
  .catch(err => {
    console.error('Fetch error:', err);
    showAlert('danger', '❌ Error: ' + err.message);
    btn.disabled = false;
    btn.innerText = 'Proceed to Pay';
  });
}

// Load payment details (QR + UPI)
function loadPaymentDetails(amount, orderId) {
  console.log('Loading payment details for order:', orderId);
  
  fetch('/extract/user/manual_upi_payment.php?action=get_details&order_id=' + orderId)
    .then(r => {
      console.log('Response received, status:', r.status);
      return r.json();
    })
    .then(data => {
      console.log('Parsed JSON:', data);
      
      if (data.success) {
        // Set payment info
        const amountEl = document.getElementById('payment-amount');
        const orderIdEl = document.getElementById('payment-order-id');
        const qrEl = document.getElementById('payment-qr');
        const upiEl = document.getElementById('payment-upi');
        
        console.log('Elements found:', {amountEl, orderIdEl, qrEl, upiEl});
        
        if (amountEl) amountEl.innerText = amount.toFixed(2);
        if (orderIdEl) orderIdEl.innerText = orderId;
        if (qrEl && data.qr_code) {
          qrEl.src = data.qr_code;
          qrEl.style.display = 'block';
        }
        if (upiEl) upiEl.value = data.upi_id || '';
        
        console.log('✅ Payment details loaded successfully');
      } else {
        showAlert('danger', '❌ ' + (data.message || 'Failed to load payment details'));
        console.error('Payment Details Error:', data);
      }
    })
    .catch(err => {
      showAlert('danger', '❌ Error: ' + err.message);
      console.error('Fetch Error:', err);
    });
}

// Copy UPI ID
function copyUPI() {
  const upiInput = document.getElementById('payment-upi');
  upiInput.select();
  document.execCommand('copy');
  showAlert('success', 'UPI ID copied!');
}

// Handle screenshot upload - wrapped in try-catch since it might not exist on page load
try {
  const screenshotInput = document.getElementById('screenshot-input');
  if (screenshotInput) {
    screenshotInput.addEventListener('change', function(e) {
      const file = this.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = function(event) {
          document.getElementById('preview-img').src = event.target.result;
          document.getElementById('screenshot-preview').style.display = 'block';
        };
        reader.readAsDataURL(file);
      }
    });
  }
} catch (e) {
  console.log('Screenshot input not found (this is okay)');
}

// Submit payment
function submitPayment() {
  const utr = document.getElementById('payment-utr').value.trim();
  const fileInput = document.getElementById('screenshot-input');
  
  if (!utr) {
    showAlert('warning', 'Please enter Transaction ID/UTR');
    return;
  }
  
  if (!fileInput.files[0]) {
    showAlert('warning', 'Please upload payment screenshot');
    return;
  }
  
  const formData = new FormData();
  formData.append('action', 'submit_manual_payment');
  formData.append('order_id', currentOrderId);
  formData.append('transaction_id', utr);
  formData.append('payment_screenshot', fileInput.files[0]);
  
  const btn = event.target;
  btn.disabled = true;
  btn.innerText = 'Submitting...';
  
  fetch('<?php echo $_SERVER['PHP_SELF']; ?>', {
    method: 'POST',
    body: formData
  })
  .then(r => r.json())
  .then(data => {
    if (data.success) {
      showAlert('success', 'Payment submitted! Admin will verify within 1-2 hours.');
      setTimeout(() => {
        document.getElementById('payment-info').style.display = 'none';
        document.getElementById('wallet-add-credits-form-container').style.display = 'block';
        document.getElementById('wallet-credit-amount').value = '';
        document.getElementById('payment-utr').value = '';
        document.getElementById('screenshot-preview').style.display = 'none';
        document.getElementById('screenshot-input').value = '';
        currentOrderId = null;
        currentAmount = null;
      }, 2000);
    } else {
      showAlert('danger', data.message || 'Failed to submit payment');
    }
    btn.disabled = false;
    btn.innerText = 'Submit Payment';
  })
  .catch(err => {
    showAlert('danger', 'Error: ' + err.message);
    btn.disabled = false;
    btn.innerText = 'Submit Payment';
  });
}
</script>
</body>

<!-- Password Change Modal -->
<div class="modal fade" id="passwordModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Change Password</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="password-form">
          <div class="mb-3">
            <label class="form-label">Current Password</label>
            <input type="password" id="current-password" class="form-control" required placeholder="Enter your current password">
            <small class="text-muted">We need this to verify it's you</small>
          </div>
          <div class="mb-3">
            <label class="form-label">New Password</label>
            <input type="password" id="new-password" class="form-control" required placeholder="Min 6 characters">
            <small class="text-muted">Use a strong password with mix of characters</small>
          </div>
          <div class="mb-3">
            <label class="form-label">Confirm New Password</label>
            <input type="password" id="confirm-password" class="form-control" required placeholder="Re-enter your new password">
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-warning" id="password-submit-btn" onclick="submitPasswordChange()">Update Password</button>
      </div>
    </div>
  </div>
</div>

<!-- AI Chat Widget -->
<div id="ai-chat-widget" style="position: fixed; bottom: 20px; right: 20px; width: 380px; max-width: 95vw; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; z-index: 10000; display: none; flex-direction: column; border-radius: 12px; box-shadow: 0 5px 40px rgba(0,0,0,0.16); background: white; height: 550px;">
  <!-- Header -->
  <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 16px; border-radius: 12px 12px 0 0; display: flex; justify-content: space-between; align-items: center;">
    <div>
      <h6 style="margin: 0; font-weight: 600; font-size: 14px;" id="ai-header-title">🤖 AI Assistant</h6>
      <small style="opacity: 0.9; font-size: 12px;" id="ai-header-subtitle">Quick answers in seconds</small>
    </div>
    <div style="display: flex; gap: 8px; align-items: center;">
      <button id="ai-back-btn" onclick="switchToAIChat()" style="display: none; background: none; border: none; color: white; font-size: 16px; cursor: pointer; padding: 4px 8px;">← Back</button>
      <button onclick="toggleAIChat()" style="background: none; border: none; color: white; font-size: 20px; cursor: pointer; padding: 0; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center;">×</button>
    </div>
  </div>
  
  <!-- AI Chat View -->
  <div id="ai-chat-view" style="flex: 1; display: flex; flex-direction: column; gap: 0; background: #f8f9fa; overflow: hidden;">
    <!-- Quick buttons (top, scrollable if many messages) -->
    <div style="padding: 12px; background: white; border-bottom: 1px solid #e5e5e5;">
      <small style="color: #999; display: block; font-size: 12px; margin-bottom: 8px; text-align: center;">👋 Quick answers:</small>
      <div style="display: flex; flex-wrap: wrap; gap: 6px; justify-content: center; margin-bottom: 8px;">
        <button onclick="sendQuickMessage('💰 How many credits?')" style="background: #667eea; color: white; border: none; border-radius: 16px; padding: 6px 12px; font-size: 11px; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='#5568d3'" onmouseout="this.style.background='#667eea'">💰 Credits</button>
        <button onclick="sendQuickMessage('🔍 How to search?')" style="background: #764ba2; color: white; border: none; border-radius: 16px; padding: 6px 12px; font-size: 11px; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='#65408f'" onmouseout="this.style.background='#764ba2'">🔍 Search</button>
        <button onclick="sendQuickMessage('💳 Payment help')" style="background: #f093fb; color: white; border: none; border-radius: 16px; padding: 6px 12px; font-size: 11px; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='#e07ae5'" onmouseout="this.style.background='#f093fb'">💳 Payment</button>
        <button onclick="sendQuickMessage('📊 My statistics')" style="background: #4facfe; color: white; border: none; border-radius: 16px; padding: 6px 12px; font-size: 11px; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='#3498db'" onmouseout="this.style.background='#4facfe'">📊 Stats</button>
      </div>
      <button onclick="switchToAdminChat()" style="background: linear-gradient(135deg, #f5576c 0%, #f093fb 100%); color: white; border: none; border-radius: 8px; padding: 8px 16px; font-size: 12px; cursor: pointer; width: 100%; font-weight: 600; transition: all 0.2s;" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 12px rgba(245,87,108,0.3)'" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='none'">
        💬 Contact Admin
      </button>
    </div>
    <!-- Messages container (scrollable - main area) -->
    <div id="ai-chat-messages" style="flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 8px;"></div>
  </div>
  
  <!-- Admin Chat View (Hidden by default) -->
  <div id="admin-chat-view" style="flex: 1; display: none; flex-direction: column; gap: 8px; background: #f8f9fa; overflow: hidden;">
    <div id="admin-chat-messages" style="flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; padding: 12px;"></div>
  </div>
  
  <!-- Input Area -->
  <div style="border-top: 1px solid #eee; padding: 10px; display: flex; gap: 8px; background: white;">
    <input type="text" id="ai-chat-input" placeholder="Type your question..." style="flex: 1; border: 1px solid #ddd; border-radius: 20px; padding: 8px 14px; font-size: 13px; outline: none; transition: border 0.2s;" onfocus="this.style.borderColor='#667eea'" onblur="this.style.borderColor='#ddd'" onkeypress="if(event.key==='Enter') sendChatMessage()">
    <button onclick="sendChatMessage()" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 50%; width: 36px; height: 36px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 18px; transition: transform 0.2s;" onmouseover="this.style.transform='scale(1.1)'" onmouseout="this.style.transform='scale(1)'">→</button>
  </div>
</div>

<!-- Chat Bubble -->
<button id="ai-chat-bubble" onclick="toggleAIChat()" style="position: fixed; bottom: 20px; right: 20px; width: 56px; height: 56px; border-radius: 50%; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; cursor: pointer; font-size: 24px; display: flex; align-items: center; justify-content: center; box-shadow: 0 2px 12px rgba(102, 126, 234, 0.4); z-index: 9999; transition: transform 0.2s;" onmouseover="this.style.transform='scale(1.1)'" onmouseout="this.style.transform='scale(1)'">🤖</button>

<style>
#ai-chat-widget .message-user {
  background: #667eea;
  color: white;
  padding: 10px 14px;
  border-radius: 12px;
  margin-left: auto;
  max-width: 85%;
  word-wrap: break-word;
  font-size: 13px;
  line-height: 1.4;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

#ai-chat-widget .message-ai {
  background: #e8e8f0;
  color: #333;
  padding: 10px 14px;
  border-radius: 12px;
  margin-right: auto;
  max-width: 85%;
  word-wrap: break-word;
  font-size: 13px;
  line-height: 1.5;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

#ai-chat-widget .message-ai strong {
  color: #667eea;
  font-weight: 600;
}

#ai-chat-widget .suggestion-button {
  background: #f0f4ff;
  color: #667eea;
  border: 1px solid #667eea;
  border-radius: 8px;
  padding: 8px 12px;
  margin: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

#ai-chat-widget .suggestion-button:hover {
  background: #667eea;
  color: white;
  transform: translateY(-2px);
}
</style>

<script>
// Global state for admin chat
let adminChatTicketId = null;
let adminChatLastMessageId = 0;
let adminChatPollInterval = null;

function toggleAIChat() {
  const widget = document.getElementById('ai-chat-widget');
  const bubble = document.getElementById('ai-chat-bubble');
  if (widget.style.display === 'flex') {
    widget.style.display = 'none';
    bubble.style.display = 'flex';
  } else {
    widget.style.display = 'flex';
    bubble.style.display = 'none';
    document.getElementById('ai-chat-input').focus();
  }
}

function switchToAdminChat() {
  // Hide AI view, show admin view
  document.getElementById('ai-chat-view').style.display = 'none';
  document.getElementById('admin-chat-view').style.display = 'flex';
  document.getElementById('ai-header-title').textContent = '💬 Admin Chat';
  document.getElementById('ai-header-subtitle').textContent = 'Chat with our support team';
  document.getElementById('ai-back-btn').style.display = 'block';
  document.getElementById('ai-chat-input').placeholder = 'Type your message...';
  
  // Initialize admin chat if first time
  if (!adminChatTicketId) {
    initializeAdminChat();
  }
}

function switchToAIChat() {
  // Hide admin view, show AI view
  document.getElementById('ai-chat-view').style.display = 'flex';
  document.getElementById('admin-chat-view').style.display = 'none';
  document.getElementById('ai-header-title').textContent = '🤖 AI Assistant';
  document.getElementById('ai-header-subtitle').textContent = 'Quick answers in seconds';
  document.getElementById('ai-back-btn').style.display = 'none';
  document.getElementById('ai-chat-input').placeholder = 'Type your question...';
  
  // Stop polling when switching away
  if (adminChatPollInterval) {
    clearInterval(adminChatPollInterval);
    adminChatPollInterval = null;
  }
}

async function initializeAdminChat() {
  try {
    const res = await fetch('../api/admin_chat.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: 'action=get_or_create_ticket'
    });
    
    const data = await res.json();
    if (data.success) {
      adminChatTicketId = data.ticket_id;
      adminChatLastMessageId = 0;
      
      // Load existing messages
      await loadAdminChatMessages();
      
      // Start polling for new admin messages
      startAdminChatPolling();
    }
  } catch (err) {
    console.error('Failed to initialize admin chat:', err);
  }
}

async function loadAdminChatMessages() {
  if (!adminChatTicketId) return;
  
  try {
    const res = await fetch('../api/admin_chat.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: 'action=get_messages&ticket_id=' + adminChatTicketId
    });
    
    const data = await res.json();
    if (data.success) {
      const messagesDiv = document.getElementById('admin-chat-messages');
      messagesDiv.innerHTML = '';
      
      data.messages.forEach(msg => {
        appendAdminChatMessage(msg);
        adminChatLastMessageId = Math.max(adminChatLastMessageId, msg.id);
      });
      
      messagesDiv.scrollTop = messagesDiv.scrollHeight;
    }
  } catch (err) {
    console.error('Failed to load admin chat messages:', err);
  }
}

function appendAdminChatMessage(msg) {
  const messagesDiv = document.getElementById('admin-chat-messages');
  const msgEl = document.createElement('div');
  msgEl.style.cssText = msg.sender_type === 'admin'
    ? 'background: #e8f0fe; color: #333; padding: 10px 14px; border-radius: 12px; margin-left: auto; max-width: 80%;'
    : 'background: #667eea; color: white; padding: 10px 14px; border-radius: 12px; margin-right: auto; max-width: 80%;';
  
  const timeStr = new Date(msg.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  msgEl.innerHTML = `<small style="opacity: 0.7; font-size: 10px;">${msg.sender_type === 'admin' ? '👨‍💼 Admin' : 'You'} ${timeStr}</small><br>${msg.message}`;
  
  messagesDiv.appendChild(msgEl);
}

function startAdminChatPolling() {
  // Poll every 2 seconds for new admin messages
  if (adminChatPollInterval) clearInterval(adminChatPollInterval);
  
  adminChatPollInterval = setInterval(async () => {
    if (!adminChatTicketId) return;
    
    try {
      const res = await fetch('../api/admin_chat.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=poll_messages&ticket_id=' + adminChatTicketId + '&last_message_id=' + adminChatLastMessageId
      });
      
      const data = await res.json();
      if (data.success && data.messages && data.messages.length > 0) {
        data.messages.forEach(msg => {
          appendAdminChatMessage(msg);
          adminChatLastMessageId = Math.max(adminChatLastMessageId, msg.id);
        });
        
        const messagesDiv = document.getElementById('admin-chat-messages');
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
      }
    } catch (err) {
      console.error('Polling error:', err);
    }
  }, 2000);
}

async function sendChatMessage() {
  const input = document.getElementById('ai-chat-input');
  const message = input.value.trim();
  if (!message) return;
  
  // Determine if we're in AI or Admin chat
  const isAdminChat = document.getElementById('admin-chat-view').style.display !== 'none';
  
  if (isAdminChat) {
    // Send to admin chat
    if (!adminChatTicketId) return;
    
    try {
      const res = await fetch('../api/admin_chat.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=send_message&ticket_id=' + adminChatTicketId + '&message=' + encodeURIComponent(message)
      });
      
      const data = await res.json();
      if (data.success) {
        appendAdminChatMessage(data.message);
        input.value = '';
        
        const messagesDiv = document.getElementById('admin-chat-messages');
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
      }
    } catch (err) {
      console.error('Failed to send message:', err);
    }
  } else {
    // Send to AI chat
    sendAIMessage();
  }
}

function sendQuickMessage(message) {
  document.getElementById('ai-chat-input').value = message;
  sendAIMessage();
}

async function sendAIMessage() {
  const input = document.getElementById('ai-chat-input');
  const message = input.value.trim();
  if (!message) return;
  
  const messagesDiv = document.getElementById('ai-chat-messages');
  
  // Clear welcome message if this is first message
  if (messagesDiv.children.length === 0) {
    messagesDiv.innerHTML = '';
  }
  
  // Add user message
  const userMsg = document.createElement('div');
  userMsg.className = 'message-user';
  userMsg.textContent = message;
  userMsg.style.marginBottom = '4px';
  messagesDiv.appendChild(userMsg);
  
  input.value = '';
  messagesDiv.scrollTop = messagesDiv.scrollHeight;
  
  // Add typing indicator
  const typingDiv = document.createElement('div');
  typingDiv.id = 'typing-indicator';
  typingDiv.style.cssText = 'margin-right: auto; color: #999; font-size: 12px; font-style: italic;';
  typingDiv.textContent = '⏳ AI is thinking...';
  messagesDiv.appendChild(typingDiv);
  messagesDiv.scrollTop = messagesDiv.scrollHeight;
  
  try {
    const res = await fetch('../api/ai_chat.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: 'message=' + encodeURIComponent(message)
    });
    
    const data = await res.json();
    
    // Remove typing indicator
    if (typingDiv.parentNode) typingDiv.parentNode.removeChild(typingDiv);
    
    // Add AI response with clickable suggestions
    const aiMsg = document.createElement('div');
    aiMsg.className = 'message-ai';
    aiMsg.innerHTML = data.response
      .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      .replace(/\n/g, '<br>');
    aiMsg.style.marginBottom = '4px';
    
    // Add click handlers to text for quick follow-ups
    aiMsg.addEventListener('click', function(e) {
      if (e.target.tagName !== 'BR') {
        const text = e.target.textContent || e.target.innerText;
        if (text && text.length > 3 && text.length < 100) {
          document.getElementById('ai-chat-input').value = 'Tell me more about: ' + text;
          document.getElementById('ai-chat-input').focus();
        }
      }
    });
    aiMsg.style.cursor = 'pointer';
    
    messagesDiv.appendChild(aiMsg);
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
  } catch (error) {
    console.error('Chat error:', error);
    
    // Remove typing indicator
    if (typingDiv.parentNode) typingDiv.parentNode.removeChild(typingDiv);
    
    const errorMsg = document.createElement('div');
    errorMsg.className = 'message-ai';
    errorMsg.textContent = '❌ Oops! Something went wrong. Please try again.';
    errorMsg.style.marginBottom = '4px';
    messagesDiv.appendChild(errorMsg);
  }
}
</script>

</html>
