<?php
require_once 'auth_helper.php';
require_login();
$user = get_user();

$pdo = db();
$electionId = get_active_election_id();
$query = $_GET['q'] ?? '';

$voters = [];
$candidates = [];
$logs = [];

if ($query) {
    $search = "%$query%";

    // Search Voters
    $stmt = $pdo->prepare("SELECT u.* FROM users u 
                           JOIN election_assignments ea ON u.id = ea.user_id 
                           WHERE ea.election_id = ? AND ea.role_in_election = 'Voter' 
                           AND (u.name LIKE ? OR u.email LIKE ? OR u.student_id LIKE ?)");
    $stmt->execute([$electionId, $search, $search, $search]);
    $voters = $stmt->fetchAll();

    // Search Candidates
    $stmt = $pdo->prepare("SELECT c.*, u.name as user_name, u.student_id 
                           FROM candidates c 
                           JOIN users u ON c.user_id = u.id 
                           WHERE c.election_id = ? 
                           AND (u.name LIKE ? OR c.position LIKE ? OR c.platform LIKE ?)");
    $stmt->execute([$electionId, $search, $search, $search]);
    $candidates = $stmt->fetchAll();

    // Search Records (Audit Logs)
    $stmt = $pdo->prepare("SELECT l.*, u.name as user_name 
                           FROM audit_logs l 
                           LEFT JOIN users u ON l.user_id = u.id 
                           WHERE (l.election_id = ? OR l.election_id IS NULL) 
                           AND (l.action LIKE ? OR l.details LIKE ? OR u.name LIKE ?)");
    $stmt->execute([$electionId, $search, $search, $search]);
    $logs = $stmt->fetchAll();
}

$projectDescription = $_SERVER['PROJECT_DESCRIPTION'] ?? 'Online Election System for Senior High School';
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Search Results | <?= htmlspecialchars($projectDescription) ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/dashboard.css?v=<?= time() ?>">
    <script src="https://unpkg.com/lucide@latest"></script>
    <style>
        .search-results-container { padding: 24px; }
        .result-section { margin-bottom: 40px; }
        .result-section h2 { font-size: 1.25rem; color: #1e293b; margin-bottom: 16px; display: flex; align-items: center; gap: 8px; }
        .result-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 16px; }
        .result-card { background: white; border: 1px solid #e2e8f0; border-radius: 12px; padding: 16px; transition: transform 0.2s; }
        .result-card:hover { transform: translateY(-2px); box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1); }
        .result-title { font-weight: 600; color: #1e293b; margin-bottom: 4px; }
        .result-meta { font-size: 0.875rem; color: #64748b; }
        .no-results { padding: 40px; text-align: center; color: #94a3b8; background: #f8fafc; border-radius: 12px; border: 2px dashed #e2e8f0; }
    </style>
</head>
<body class="dashboard-body <?= ($user['theme'] ?? 'light') === 'dark' ? 'dark-theme' : '' ?>">
    <?php require_once 'includes/sidebar.php'; ?>
    <div class="main-wrapper">
        <?php require_once 'includes/header.php'; ?>
        
        <main class="dashboard-content">
            <div class="search-results-container">
                <div style="margin-bottom: 24px;">
                    <h1 style="font-size: 1.875rem; color: #1e293b;">Search Results</h1>
                    <p style="color: #64748b;">Showing results for "<strong><?= htmlspecialchars($query) ?></strong>"</p>
                </div>

                <?php if (!$query): ?>
                    <div class="no-results">
                        <i data-lucide="search" style="width: 48px; height: 48px; margin-bottom: 16px; opacity: 0.5;"></i>
                        <p>Enter a search term to find voters, candidates, or records.</p>
                    </div>
                <?php elseif (empty($voters) && empty($candidates) && empty($logs)): ?>
                    <div class="no-results">
                        <i data-lucide="frown" style="width: 48px; height: 48px; margin-bottom: 16px; opacity: 0.5;"></i>
                        <p>No results found for "<?= htmlspecialchars($query) ?>".</p>
                    </div>
                <?php else: ?>
                    
                    <?php if (!empty($voters)): ?>
                        <div class="result-section">
                            <h2><i data-lucide="users"></i> Voters (<?= count($voters) ?>)</h2>
                            <div class="result-grid">
                                <?php foreach ($voters as $v): ?>
                                    <div class="result-card">
                                        <div class="result-title"><?= htmlspecialchars($v['name']) ?></div>
                                        <div class="result-meta"><?= htmlspecialchars($v['student_id']) ?> • <?= htmlspecialchars($v['email']) ?></div>
                                        <div style="margin-top: 12px;">
                                            <a href="voter_management.php?search=<?= urlencode($v['student_id']) ?>" style="font-size: 12px; color: #4f46e5; font-weight: 500; text-decoration: none;">View in Voters List →</a>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($candidates)): ?>
                        <div class="result-section">
                            <h2><i data-lucide="user-square"></i> Candidates (<?= count($candidates) ?>)</h2>
                            <div class="result-grid">
                                <?php foreach ($candidates as $c): ?>
                                    <div class="result-card">
                                        <div class="result-title"><?= htmlspecialchars($c['user_name']) ?></div>
                                        <div class="result-meta"><?= htmlspecialchars($c['position']) ?> • <?= htmlspecialchars($c['student_id']) ?></div>
                                        <div style="margin-top: 12px;">
                                            <a href="candidate_management.php?search=<?= urlencode($c['user_name']) ?>" style="font-size: 12px; color: #4f46e5; font-weight: 500; text-decoration: none;">View in Candidates →</a>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($logs)): ?>
                        <div class="result-section">
                            <h2><i data-lucide="file-text"></i> Audit Records (<?= count($logs) ?>)</h2>
                            <div class="result-grid">
                                <?php foreach ($logs as $l): ?>
                                    <div class="result-card">
                                        <div class="result-title"><?= htmlspecialchars($l['action']) ?></div>
                                        <div class="result-meta"><?= date('M d, Y H:i', strtotime($l['created_at'])) ?> by <?= htmlspecialchars($l['user_name'] ?? 'SYSTEM') ?></div>
                                        <div style="margin-top: 8px; font-size: 13px; color: #64748b; line-height: 1.5;">
                                            <?= htmlspecialchars($l['details']) ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>

                <?php endif; ?>
            </div>
        </main>
    </div>
    <script>lucide.createIcons();</script>
</body>
</html>
