<?php
require_once 'includes/init.php';

if (!isAuthenticated()) {
    redirect(APP_URL . '/login.php');
}

$pageTitle = 'Search';
$activePage = 'search';

$db = getDB();
$searchResults = [];
$searchQuery = '';

if (isset($_GET['q']) && !empty($_GET['q'])) {
    $searchQuery = sanitizeInput($_GET['q']);
    $searchTerm = '%' . $searchQuery . '%';
    
    $stmt = $db->prepare("
        SELECT id, unique_id, name, email, profile_photo, is_ghost_mode, last_seen
        FROM users 
        WHERE (unique_id LIKE ? OR name LIKE ? OR email LIKE ?)
        AND id != ?
        AND status = 'approved'
        LIMIT 20
    ");
    $stmt->execute([$searchTerm, $searchTerm, $searchTerm, $_SESSION['user_id']]);
    $searchResults = $stmt->fetchAll();
}

// Get recent chats for quick access
$stmt = $db->prepare("
    SELECT DISTINCT u.id, u.unique_id, u.name, u.profile_photo, u.is_ghost_mode
    FROM users u
    JOIN messages m ON (m.sender_id = u.id AND m.receiver_id = ?) OR (m.sender_id = ? AND m.receiver_id = u.id)
    WHERE u.id != ? AND u.status = 'approved'
    ORDER BY m.created_at DESC
    LIMIT 10
");
$stmt->execute([$_SESSION['user_id'], $_SESSION['user_id'], $_SESSION['user_id']]);
$recentChats = $stmt->fetchAll();

include 'includes/header.php';
?>

<div class="relative flex h-screen w-full flex-col overflow-hidden bg-background-light dark:bg-background-dark max-w-md mx-auto">
    <!-- Header -->
    <header class="flex items-center bg-background-light dark:bg-background-dark p-4 border-b border-slate-200 dark:border-slate-800 sticky top-0 z-10">
        <div class="flex items-center gap-3 flex-1">
            <a href="chats.php" class="text-slate-600 dark:text-slate-400 hover:text-primary transition-colors">
                <span class="material-symbols-outlined">arrow_back</span>
            </a>
            <h2 class="text-slate-900 dark:text-slate-100 text-lg font-bold">Find People</h2>
        </div>
        <button onclick="toggleDarkMode()" class="flex size-10 items-center justify-center rounded-full bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors">
            <span class="material-symbols-outlined" id="darkModeIcon"><?php echo isset($_COOKIE['darkMode']) && $_COOKIE['darkMode'] === 'true' ? 'light_mode' : 'dark_mode'; ?></span>
        </button>
    </header>

    <!-- Search Bar -->
    <div class="p-4 bg-background-light dark:bg-background-dark">
        <form method="GET" action="" class="relative">
            <span class="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">search</span>
            <input type="text" name="q" value="<?php echo htmlspecialchars($searchQuery); ?>" 
                class="w-full pl-12 pr-10 py-3 rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-primary/50"
                placeholder="Search by Unique ID or name..."
                autocomplete="off">
            <?php if ($searchQuery): ?>
            <a href="search.php" class="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600">
                <span class="material-symbols-outlined">close</span>
            </a>
            <?php endif; ?>
        </form>
    </div>

    <!-- Results -->
    <main class="flex-1 overflow-y-auto no-scrollbar pb-20">
        <?php if ($searchQuery): ?>
            <div class="px-4 py-2">
                <p class="text-sm text-slate-500 dark:text-slate-400 mb-3">
                    <?php echo count($searchResults); ?> result<?php echo count($searchResults) !== 1 ? 's' : ''; ?> for "<?php echo htmlspecialchars($searchQuery); ?>"
                </p>
            </div>
            
            <?php if (empty($searchResults)): ?>
                <div class="flex flex-col items-center justify-center py-12 text-center">
                    <div class="size-16 bg-slate-100 dark:bg-slate-800 rounded-full flex items-center justify-center mb-4">
                        <span class="material-symbols-outlined text-3xl text-slate-400">search_off</span>
                    </div>
                    <p class="text-slate-500 dark:text-slate-400">No users found</p>
                    <p class="text-xs text-slate-400 mt-1">Try a different search term</p>
                </div>
            <?php else: ?>
                <div class="flex flex-col">
                    <?php foreach ($searchResults as $user): ?>
                    <a href="chat.php?user=<?php echo htmlspecialchars($user['unique_id']); ?>" class="flex items-center gap-4 px-4 py-4 hover:bg-slate-50 dark:hover:bg-slate-800/50 border-b border-slate-100 dark:border-slate-800/50 transition-colors">
                        <div class="relative shrink-0">
                            <?php if ($user['profile_photo']): ?>
                            <div class="bg-center bg-no-repeat aspect-square bg-cover rounded-full h-14 w-14 border-2 border-primary/20" style="background-image: url('uploads/images/<?php echo htmlspecialchars($user['profile_photo']); ?>')"></div>
                            <?php else: ?>
                            <div class="size-14 rounded-full bg-primary/10 flex items-center justify-center border-2 border-primary/20">
                                <span class="material-symbols-outlined text-2xl text-primary">person</span>
                            </div>
                            <?php endif; ?>
                        </div>
                        <div class="flex flex-col flex-1 min-w-0">
                            <p class="text-slate-900 dark:text-slate-100 text-base font-semibold"><?php echo htmlspecialchars($user['name']); ?></p>
                            <p class="text-sm text-slate-500 dark:text-slate-400">@<?php echo htmlspecialchars($user['unique_id']); ?></p>
                        </div>
                        <span class="material-symbols-outlined text-slate-400">chevron_right</span>
                    </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        <?php else: ?>
            <!-- Recent Chats -->
            <?php if (!empty($recentChats)): ?>
            <div class="px-4 py-3">
                <h3 class="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-3">Recent Chats</h3>
                <div class="flex gap-4 overflow-x-auto no-scrollbar pb-2">
                    <?php foreach ($recentChats as $user): ?>
                    <a href="chat.php?user=<?php echo htmlspecialchars($user['unique_id']); ?>" class="flex flex-col items-center gap-2 min-w-[70px]">
                        <?php if ($user['profile_photo']): ?>
                        <div class="bg-center bg-no-repeat aspect-square bg-cover rounded-full h-14 w-14 border-2 border-primary/20" style="background-image: url('uploads/images/<?php echo htmlspecialchars($user['profile_photo']); ?>')"></div>
                        <?php else: ?>
                        <div class="size-14 rounded-full bg-primary/10 flex items-center justify-center border-2 border-primary/20">
                            <span class="material-symbols-outlined text-2xl text-primary">person</span>
                        </div>
                        <?php endif; ?>
                        <p class="text-xs text-slate-700 dark:text-slate-300 text-center truncate w-16"><?php echo htmlspecialchars(explode(' ', $user['name'])[0]); ?></p>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
            
            <!-- Quick Actions -->
            <div class="px-4 py-4">
                <h3 class="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-3">Quick Actions</h3>
                <div class="grid grid-cols-2 gap-3">
                    <button onclick="showMyId()" class="flex items-center gap-3 p-4 bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 hover:border-primary transition-colors">
                        <div class="size-10 rounded-full bg-primary/10 flex items-center justify-center">
                            <span class="material-symbols-outlined text-primary">badge</span>
                        </div>
                        <div class="text-left">
                            <p class="text-sm font-medium text-slate-900 dark:text-slate-100">My ID</p>
                            <p class="text-xs text-slate-500">Share your ID</p>
                        </div>
                    </button>
                    <button onclick="scanQr()" class="flex items-center gap-3 p-4 bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 hover:border-primary transition-colors">
                        <div class="size-10 rounded-full bg-primary/10 flex items-center justify-center">
                            <span class="material-symbols-outlined text-primary">qr_code_scanner</span>
                        </div>
                        <div class="text-left">
                            <p class="text-sm font-medium text-slate-900 dark:text-slate-100">Scan QR</p>
                            <p class="text-xs text-slate-500">Quick connect</p>
                        </div>
                    </button>
                </div>
            </div>
            
            <!-- Instructions -->
            <div class="px-4 py-4">
                <div class="bg-slate-100 dark:bg-slate-800/50 rounded-xl p-4">
                    <div class="flex items-center gap-2 mb-2">
                        <span class="material-symbols-outlined text-primary">lightbulb</span>
                        <p class="text-sm font-medium text-slate-900 dark:text-slate-100">How to find people</p>
                    </div>
                    <ul class="text-xs text-slate-500 dark:text-slate-400 space-y-1 ml-6">
                        <li>Search by their Unique ID (e.g., john_doe)</li>
                        <li>Search by name or email address</li>
                        <li>Share your Unique ID so others can find you</li>
                    </ul>
                </div>
            </div>
        <?php endif; ?>
    </main>
</div>

<!-- My ID Modal -->
<div id="my-id-modal" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
    <div class="bg-white dark:bg-slate-800 w-full max-w-sm rounded-2xl p-6 text-center">
        <div class="size-20 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-4">
            <span class="material-symbols-outlined text-4xl text-primary">badge</span>
        </div>
        <h3 class="text-lg font-bold text-slate-900 dark:text-slate-100 mb-2">Your Unique ID</h3>
        <div class="bg-slate-100 dark:bg-slate-700 rounded-xl p-4 mb-4">
            <p class="text-2xl font-mono font-bold text-primary"><?php echo $_SESSION['user_unique_id']; ?></p>
        </div>
        <p class="text-sm text-slate-500 dark:text-slate-400 mb-4">Share this ID with friends so they can find you</p>
        <div class="flex gap-3">
            <button onclick="copyMyId()" class="flex-1 py-3 bg-primary text-white rounded-xl font-medium">Copy ID</button>
            <button onclick="closeMyIdModal()" class="flex-1 py-3 bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-300 rounded-xl font-medium">Close</button>
        </div>
    </div>
</div>

<script>
    function showMyId() {
        document.getElementById('my-id-modal').classList.remove('hidden');
    }
    
    function closeMyIdModal() {
        document.getElementById('my-id-modal').classList.add('hidden');
    }
    
    function copyMyId() {
        const id = '<?php echo $_SESSION['user_unique_id']; ?>';
        navigator.clipboard.writeText(id);
        showToast('ID copied to clipboard', 'success');
    }
    
    function scanQr() {
        showToast('QR code scanner coming soon', 'info');
    }
</script>

<?php include 'includes/footer.php'; ?>
