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

$pdo = db();
$electionId = get_active_election_id();
$election = get_active_election();

// Fetch officers assigned to this election grouped by role
$query = "SELECT u.* FROM users u 
          JOIN election_assignments ea ON u.id = ea.user_id 
          WHERE ea.election_id = ? AND u.deleted_at IS NULL";

$stmt = $pdo->prepare($query . " AND u.role = 'Admin' ORDER BY u.name");
$stmt->execute([$electionId]);
$admins = $stmt->fetchAll();

$stmt = $pdo->prepare($query . " AND u.role = 'Adviser' ORDER BY u.name");
$stmt->execute([$electionId]);
$advisers = $stmt->fetchAll();

$stmt = $pdo->prepare($query . " AND u.role = 'Officer' ORDER BY u.name");
$stmt->execute([$electionId]);
$officers = $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>Officer Management | <?= htmlspecialchars($projectDescription) ?></title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <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() ?>">
    <link rel="stylesheet" href="assets/css/officers_management.css?v=<?= time() ?>">
    <script src="https://unpkg.com/lucide@latest"></script>
</head>
<body class="dashboard-body <?= ($user['theme'] ?? 'light') === 'dark' ? 'dark-theme' : '' ?>">

    <?php require_once 'includes/sidebar.php'; ?>

    <!-- Main Content -->
    <div class="main-wrapper">
        <?php require_once 'includes/header.php'; ?>

        <main class="dashboard-content animate-fade-in">
            <div class="dashboard-header">
                <div style="display: flex; align-items: center; gap: 16px;">
                    <div class="header-icon-container">
                        <i data-lucide="shield-check" style="width: 24px; color: #4f46e5;"></i>
                    </div>
                    <div>
                        <h1 style="margin: 0; font-size: 1.5rem; color: #1e293b;">Officer Management</h1>
                        <p style="margin: 4px 0 0 0; color: #64748b; font-size: 0.875rem;">Personnel for <?= htmlspecialchars($election['title'] ?? 'Selected Election') ?></p>
                    </div>
                </div>
            </div>

            <!-- Register New Officer Form -->
            <section class="registration-section animate-stagger">
                <div class="registration-header">
                    <i data-lucide="plus-circle" style="width: 20px; color: #2563eb;"></i>
                    Assign New Officer to Election
                </div>
                <form class="registration-form" action="api/add_officer.php" method="POST">
                    <input type="hidden" name="election_id" value="<?= $electionId ?>">
                    <div class="form-row">
                        <div class="form-group">
                            <label>Full Name</label>
                            <input type="text" name="name" placeholder="Enter name" required>
                        </div>
                        <div class="form-group">
                            <label>Student ID / Personnel ID</label>
                            <input type="text" name="student_id" placeholder="XX-XXXX" required>
                        </div>
                        <div class="form-group">
                            <label>Email</label>
                            <input type="email" name="email" placeholder="email@school.edu" required>
                        </div>
                        <div class="form-group">
                            <label>Role</label>
                            <select name="role" required>
                                <option value="Admin">Admin</option>
                                <option value="Adviser">Adviser</option>
                                <option value="Officer" selected>Officer</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Password</label>
                            <input type="text" name="password" value="iloilohns" required>
                        </div>
                    </div>
                    <div style="margin-top: 20px; display: flex; justify-content: flex-end;">
                        <button type="submit" class="btn-save-officer">
                            <i data-lucide="save" style="width: 18px;"></i>
                            ASSIGN TO ELECTION
                        </button>
                    </div>
                </form>
            </section>

            <!-- Officer Categories Grid -->
            <div class="officer-management-grid animate-fade-in">
                <!-- Admins -->
                <div class="officer-category-card">
                    <div class="category-header">
                        <div class="category-title">
                            <i data-lucide="user-cog" style="width: 18px; color: #4f46e5;"></i>
                            Admins
                        </div>
                        <span class="active-count"><?= count($admins) ?> ACTIVE</span>
                    </div>
                    <div class="officer-list">
                        <?php foreach ($admins as $o): ?>
                            <div class="officer-item">
                                <div class="officer-main-info">
                                    <div class="officer-avatar"><?= strtoupper(substr($o['name'], 0, 1)) ?></div>
                                    <div class="officer-details">
                                        <span class="officer-name"><?= htmlspecialchars($o['name']) ?></span>
                                        <span class="officer-meta"><?= htmlspecialchars($o['student_id']) ?> | <?= htmlspecialchars($o['email']) ?></span>
                                    </div>
                                </div>
                                <div class="officer-actions">
                                    <button title="Edit" onclick='editOfficer(<?= json_encode($o) ?>)'><i data-lucide="edit-3" style="width: 16px;"></i></button>
                                    <button title="Delete" style="color: #ef4444;" onclick="deleteOfficer('<?= $o['id'] ?>', '<?= htmlspecialchars($o['name']) ?>')"><i data-lucide="trash-2" style="width: 16px;"></i></button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <?php if (empty($admins)): ?>
                            <div class="empty-state">No admins assigned.</div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- COMEA Advisers -->
                <div class="officer-category-card">
                    <div class="category-header">
                        <div class="category-title">
                            <i data-lucide="user-check" style="width: 18px; color: #f97316;"></i>
                            Advisers
                        </div>
                        <span class="active-count" style="background: #fff7ed; color: #ea580c;"><?= count($advisers) ?> ACTIVE</span>
                    </div>
                    <div class="officer-list">
                        <?php foreach ($advisers as $o): ?>
                            <div class="officer-item">
                                <div class="officer-main-info">
                                    <div class="officer-avatar" style="background: #eff6ff; color: #2563eb;"><?= strtoupper(substr($o['name'], 0, 1)) ?></div>
                                    <div class="officer-details">
                                        <span class="officer-name"><?= htmlspecialchars($o['name']) ?></span>
                                        <span class="officer-meta"><?= htmlspecialchars($o['student_id']) ?> | <?= htmlspecialchars($o['email']) ?></span>
                                    </div>
                                </div>
                                <div class="officer-actions">
                                    <button title="Edit" onclick='editOfficer(<?= json_encode($o) ?>)'><i data-lucide="edit-3" style="width: 16px;"></i></button>
                                    <button title="Delete" style="color: #ef4444;" onclick="deleteOfficer('<?= $o['id'] ?>', '<?= htmlspecialchars($o['name']) ?>')"><i data-lucide="trash-2" style="width: 16px;"></i></button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <?php if (empty($advisers)): ?>
                            <div class="empty-state">No advisers assigned.</div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- COMEA Officers -->
                <div class="officer-category-card">
                    <div class="category-header">
                        <div class="category-title">
                            <i data-lucide="users" style="width: 18px; color: #10b981;"></i>
                            COMEA Officers
                        </div>
                        <span class="active-count" style="background: #f0fdf4; color: #16a34a;"><?= count($officers) ?> ACTIVE</span>
                    </div>
                    <div class="officer-list">
                        <?php foreach ($officers as $o): ?>
                            <div class="officer-item">
                                <div class="officer-main-info">
                                    <div class="officer-avatar" style="background: #ecfdf5; color: #059669;"><?= strtoupper(substr($o['name'], 0, 1)) ?></div>
                                    <div class="officer-details">
                                        <span class="officer-name"><?= htmlspecialchars($o['name']) ?></span>
                                        <span class="officer-meta"><?= htmlspecialchars($o['student_id']) ?> | <?= htmlspecialchars($o['email']) ?></span>
                                    </div>
                                </div>
                                <div class="officer-actions">
                                    <button title="Edit" onclick='editOfficer(<?= json_encode($o) ?>)'><i data-lucide="edit-3" style="width: 16px;"></i></button>
                                    <button title="Delete" style="color: #ef4444;" onclick="deleteOfficer('<?= $o['id'] ?>', '<?= htmlspecialchars($o['name']) ?>')"><i data-lucide="trash-2" style="width: 16px;"></i></button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <?php if (empty($officers)): ?>
                            <div class="empty-state">No officers assigned.</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- Edit Officer Modal -->
    <div id="editOfficerModal" class="modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1000; align-items:center; justify-content:center;">
        <div class="modal-content" style="background:white; padding:32px; border-radius:16px; width:100%; max-width:500px; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1);">
            <div class="modal-header" style="display:flex; justify-content:space-between; align-items:center; margin-bottom:24px;">
                <h2 style="margin:0; font-size:1.25rem; color:#1e293b;">Edit Officer</h2>
                <button onclick="closeModal('editOfficerModal')" style="border:none; background:none; cursor:pointer;"><i data-lucide="x"></i></button>
            </div>
            <form action="api/update_officer.php" method="POST">
                <input type="hidden" name="id" id="edit_officer_id">
                <div class="form-group" style="margin-bottom:16px;">
                    <label style="display:block; font-size:12px; font-weight:600; color:#64748b; margin-bottom:6px;">FULL NAME</label>
                    <input type="text" name="name" id="edit_officer_name" required style="width:100%; padding:10px; border-radius:8px; border:1px solid #e2e8f0;">
                </div>
                <div class="form-group" style="margin-bottom:16px;">
                    <label style="display:block; font-size:12px; font-weight:600; color:#64748b; margin-bottom:6px;">EMAIL ADDRESS</label>
                    <input type="email" name="email" id="edit_officer_email" required style="width:100%; padding:10px; border-radius:8px; border:1px solid #e2e8f0;">
                </div>
                <div class="form-group" style="margin-bottom:16px;">
                    <label style="display:block; font-size:12px; font-weight:600; color:#64748b; margin-bottom:6px;">ROLE</label>
                    <select name="role" id="edit_officer_role" required style="width:100%; padding:10px; border-radius:8px; border:1px solid #e2e8f0;">
                        <option value="Admin">Admin</option>
                        <option value="Adviser">Adviser</option>
                        <option value="Officer">Officer</option>
                    </select>
                </div>
                <div class="form-group" style="margin-bottom:24px;">
                    <label style="display:block; font-size:12px; font-weight:600; color:#64748b; margin-bottom:6px;">NEW PASSWORD (OPTIONAL)</label>
                    <input type="password" name="password" placeholder="Leave blank to keep current" style="width:100%; padding:10px; border-radius:8px; border:1px solid #e2e8f0;">
                </div>
                <div style="display:flex; justify-content:flex-end; gap:12px;">
                    <button type="button" onclick="closeModal('editOfficerModal')" style="padding:10px 20px; border-radius:8px; border:1px solid #e2e8f0; background:white; cursor:pointer;">Cancel</button>
                    <button type="submit" style="padding:10px 24px; border-radius:8px; border:none; background:#4f46e5; color:white; cursor:pointer; font-weight:600;">Update Officer</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        lucide.createIcons();

        function openModal(id) {
            document.getElementById(id).style.display = 'flex';
        }

        function closeModal(id) {
            document.getElementById(id).style.display = 'none';
        }

        function editOfficer(officer) {
            document.getElementById('edit_officer_id').value = officer.id;
            document.getElementById('edit_officer_name').value = officer.name;
            document.getElementById('edit_officer_email').value = officer.email;
            document.getElementById('edit_officer_role').value = officer.role;
            openModal('editOfficerModal');
        }

        function deleteOfficer(id, name) {
            if (confirm(`Are you sure you want to remove ${name} from this election?`)) {
                window.location.href = `api/delete_officer.php?id=${id}&election_id=<?= $electionId ?>`;
            }
        }

        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }
    </script>
</body>
</html>
