<?php
/**
 * Create / Edit Election Form
 */

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/voting.php';
requireAuth();

if (!isVoting() && !isAdmin()) {
    header('Location: ' . BASE_PATH . '/voting?toast_error=' . urlencode('Only voting administrators or the assigned manager can manage elections.'));
    exit;
}

if (!isVotingEnabled()) {
    header('Location: ' . BASE_PATH . '/voting?toast_error=' . urlencode('Voting system is currently disabled.'));
    exit;
}

// Create: only admin, and redirect to Settings to create (so assignment is set)
if ($action === 'create') {
    if (!isAdmin()) {
        header('Location: ' . BASE_PATH . '/voting?toast_error=' . urlencode('Only an administrator can create elections. Use Settings → Voting.'));
        exit;
    }
    header('Location: ' . BASE_PATH . '/settings/voting?add=1');
    exit;
}

// Get action and id from route variables (set by router)
$action = $route_action ?? '';
$id = isset($route_id) ? (int)$route_id : null;

$isEdit = ($action === 'edit' && $id);
$election = null;
$errors = [];

if ($isEdit) {
    $election = getElection($id);
    if (!$election) {
        header('Location: ' . BASE_PATH . '/voting?toast_error=' . urlencode('Election not found.'));
        exit;
    }
    if (!canManageElection($id)) {
        header('Location: ' . BASE_PATH . '/voting?toast_error=' . urlencode('You do not have permission to edit this election.'));
        exit;
    }
}

// Lock all fields except status when the election is active
$isLocked = $isEdit && ($election['status'] === 'active');
// Election over: closed or end date passed — no edits at all
$endTs = !empty($election['end_date']) ? strtotime($election['end_date']) : false;
$electionOver = $isEdit && (($election['status'] ?? '') === 'closed' || ($endTs !== false && time() >= $endTs));
$readOnly = $isLocked || $electionOver;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($electionOver) {
        header('Location: ' . BASE_PATH . '/voting/edit/' . $id . '?toast_error=' . urlencode('This election has ended. No changes can be made.'));
        exit;
    }
    $status = in_array($_POST['status'] ?? '', ['draft', 'active', 'closed']) ? $_POST['status'] : 'draft';

    if ($isLocked) {
        // Only update status — all other fields are frozen
        $stmt = $pdo->prepare('UPDATE elections SET status = ? WHERE id = ?');
        $stmt->execute([$status, $id]);
        header('Location: ' . BASE_PATH . '/voting?toast=' . urlencode('Election status updated.'));
        exit;
    }

    $title = trim($_POST['title'] ?? '');
    $type = in_array($_POST['type'] ?? '', ['fellowship', 'presbyters']) ? $_POST['type'] : 'fellowship';
    $startDate = !empty($_POST['start_date']) ? $_POST['start_date'] : null;
    $endDate = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
    $numberOfFemales = $type === 'presbyters' && !empty($_POST['number_of_females']) ? (int)$_POST['number_of_females'] : null;
    $numberOfMales = $type === 'presbyters' && !empty($_POST['number_of_males']) ? (int)$_POST['number_of_males'] : null;
    $groupType = in_array($_POST['group_type'] ?? '', ['gen_grp', 'service_grp']) ? $_POST['group_type'] : null;
    $groupId = $groupType === 'service_grp' && !empty($_POST['group_id']) ? (int)$_POST['group_id'] : null;
    $groupName = $groupType === 'gen_grp' && trim($_POST['group_name'] ?? '') !== '' ? trim($_POST['group_name']) : null;
    if ($type === 'presbyters') {
        $groupType = null;
        $groupId = null;
        $groupName = null;
    }
    $managerUserId = !empty($_POST['manager_user_id']) ? (int)$_POST['manager_user_id'] : null;
    $enabled = !empty($_POST['enabled']) ? 1 : 0;

    if (empty($title)) {
        $errors[] = 'Title is required.';
    }

    if (empty($errors)) {
        if ($isEdit) {
            $stmt = $pdo->prepare('UPDATE elections SET title = ?, type = ?, status = ?, start_date = ?, end_date = ?, number_of_females = ?, number_of_males = ?, group_type = ?, group_id = ?, group_name = ?, manager_user_id = ?, enabled = ? WHERE id = ?');
            $stmt->execute([$title, $type, $status, $startDate ?: null, $endDate ?: null, $numberOfFemales, $numberOfMales, $groupType, $groupId, $groupName, $managerUserId, $enabled, $id]);
            header('Location: ' . BASE_PATH . '/voting?toast=' . urlencode('Election updated.'));
        } else {
            $stmt = $pdo->prepare('INSERT INTO elections (title, type, status, start_date, end_date, number_of_females, number_of_males) VALUES (?, ?, ?, ?, ?, ?, ?)');
            $stmt->execute([$title, $type, $status, $startDate ?: null, $endDate ?: null, $numberOfFemales, $numberOfMales]);
            $newId = $pdo->lastInsertId();
            header('Location: ' . BASE_PATH . '/voting/manage/' . $newId . '?toast=' . urlencode('Election created. Now add positions and candidates.'));
        }
        exit;
    }

    $election = ['title' => $title, 'type' => $type, 'status' => $status, 'start_date' => $startDate, 'end_date' => $endDate, 'number_of_females' => $numberOfFemales, 'number_of_males' => $numberOfMales, 'group_type' => $groupType, 'group_id' => $groupId, 'group_name' => $groupName, 'manager_user_id' => $managerUserId, 'enabled' => $enabled];
}

$pageTitle = $isEdit ? 'Edit Election' : 'Create Election';
$editFellowshipNames = [];
$editMinistriesList = [];
$editUsersList = [];
if ($isEdit) {
    require_once __DIR__ . '/../../includes/fellowships.php';
    $editFellowshipNames = array_filter(getFellowshipOrder(), function($v) { return $v !== null; });
    $editMinistriesList = $pdo->query("SELECT id, name FROM ministries ORDER BY name")->fetchAll();
    $editUsersList = $pdo->query("SELECT id, username, full_name, role FROM users WHERE active = 1 AND role IN ('voting', 'admin') ORDER BY role, username")->fetchAll();
}
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="header">
    <h1><?= $isEdit ? 'Edit Election' : 'Create Election' ?></h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/voting" class="link-muted">← Elections</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<?php if (!empty($errors)): ?>
    <div data-toast="error" data-toast-msg="<?= htmlspecialchars(implode(' ', $errors)) ?>" style="display:none"></div>
<?php endif; ?>

<?php if ($electionOver): ?>
<div style="display:flex; align-items:center; gap:0.6rem; background:#fef2f2; border-left:4px solid #dc2626; border-radius:0 8px 8px 0; padding:0.75rem 1rem; margin-bottom:1.25rem; max-width:680px;">
    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#b91c1c" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><path d="M15 9l-6 6M9 9l6 6"/></svg>
    <span style="font-size:0.875rem; color:#991b1b;">This election has ended. No changes can be made.</span>
</div>
<?php elseif ($isLocked): ?>
<div style="display:flex; align-items:center; gap:0.6rem; background:#fffbeb; border-left:4px solid #f59e0b; border-radius:0 8px 8px 0; padding:0.75rem 1rem; margin-bottom:1.25rem; max-width:680px;">
    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#d97706" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M12 2a5 5 0 0 1 5 5v3H7V7a5 5 0 0 1 5-5z"/><rect x="3" y="10" width="18" height="12" rx="2"/></svg>
    <span style="font-size:0.875rem; color:#92400e;">Voting is in progress — all fields are locked. Only <strong>Status</strong> can be changed.</span>
</div>
<?php endif; ?>

<?php $d = $readOnly ? 'disabled' : ''; $dStatus = $electionOver ? 'disabled' : ''; ?>

<div class="form-card">
    <form method="post" class="member-form">
        <div class="form-group">
            <label for="title">Title</label>
            <input type="text" id="title" name="title" required <?= $d ?>
                value="<?= htmlspecialchars(($election['title'] ?? '') ?: ($_POST['title'] ?? '')) ?>">
        </div>
        <div class="form-group">
            <label for="type">Type</label>
            <select id="type" name="type" required <?= $d ?>>
                <?php $currentType = ($election['type'] ?? '') ?: ($_POST['type'] ?? 'fellowship'); ?>
                <option value="fellowship" <?= $currentType === 'fellowship' ? 'selected' : '' ?>>Group (positions, individuals contest)</option>
                <option value="presbyters" <?= $currentType === 'presbyters' ? 'selected' : '' ?>>Presbyters' Elections (fixed number of females and males)</option>
            </select>
        </div>
        <div class="form-group">
            <label for="status">Status</label>
            <select id="status" name="status" required <?= $dStatus ?>>
                <?php $currentStatus = ($election['status'] ?? '') ?: ($_POST['status'] ?? 'draft'); ?>
                <option value="draft" <?= $currentStatus === 'draft' ? 'selected' : '' ?>>Draft</option>
                <option value="active" <?= $currentStatus === 'active' ? 'selected' : '' ?>>Active</option>
                <option value="closed" <?= $currentStatus === 'closed' ? 'selected' : '' ?>>Closed</option>
            </select>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label for="start_date">Start Date</label>
                <input type="datetime-local" id="start_date" name="start_date" <?= $d ?>
                    value="<?= !empty($election['start_date']) ? date('Y-m-d\TH:i', strtotime($election['start_date'])) : (!empty($_POST['start_date']) ? $_POST['start_date'] : '') ?>">
            </div>
            <div class="form-group">
                <label for="end_date">End Date</label>
                <input type="datetime-local" id="end_date" name="end_date" <?= $d ?>
                    value="<?= !empty($election['end_date']) ? date('Y-m-d\TH:i', strtotime($election['end_date'])) : (!empty($_POST['end_date']) ? $_POST['end_date'] : '') ?>">
            </div>
        </div>
        <div id="presbyters-fields" style="display: <?= $currentType === 'presbyters' ? 'block' : 'none' ?>;">
            <div class="form-row">
                <div class="form-group">
                    <label for="number_of_females">Number of Females to Elect</label>
                    <input type="number" id="number_of_females" name="number_of_females" min="0" <?= $d ?>
                        value="<?= htmlspecialchars(($election['number_of_females'] ?? '') ?: ($_POST['number_of_females'] ?? '')) ?>">
                </div>
                <div class="form-group">
                    <label for="number_of_males">Number of Males to Elect</label>
                    <input type="number" id="number_of_males" name="number_of_males" min="0" <?= $d ?>
                        value="<?= htmlspecialchars(($election['number_of_males'] ?? '') ?: ($_POST['number_of_males'] ?? '')) ?>">
                </div>
            </div>
        </div>
        <?php if ($isEdit): ?>
        <h4 style="margin-top: 1.5rem; margin-bottom: 0.5rem;">Assignment</h4>
        <p class="text-muted" style="font-size: 0.875rem; margin-bottom: 0.75rem;">Group elections can be assigned to a Gen Grp or Service Grp. Presbyters' elections are whole-church and are not assigned to a group.</p>
        <div id="edit-assignment-wrap" style="display: <?= $currentType === 'fellowship' ? 'block' : 'none' ?>;">
        <div class="form-group">
            <label>Assigned to</label>
            <div style="display: flex; flex-wrap: wrap; gap: 1rem; align-items: flex-start;">
                <label class="checkbox-row">
                    <input type="radio" name="group_type" value="gen_grp" <?= ($election['group_type'] ?? '') === 'gen_grp' ? 'checked' : '' ?> <?= $d ?>>
                    Gen Grp
                </label>
                <label class="checkbox-row">
                    <input type="radio" name="group_type" value="service_grp" <?= ($election['group_type'] ?? 'service_grp') === 'service_grp' ? 'checked' : '' ?> <?= $d ?>>
                    Service Grp
                </label>
            </div>
        </div>
        <div id="edit-gen-grp-wrap" class="form-group" style="display: <?= ($election['group_type'] ?? 'service_grp') === 'gen_grp' ? 'block' : 'none' ?>;">
            <label for="group_name">Gen Grp</label>
            <select id="group_name" name="group_name" <?= $d ?>>
                <option value="">— Select —</option>
                <?php foreach ($editFellowshipNames as $fn): ?>
                <option value="<?= htmlspecialchars($fn) ?>" <?= ($election['group_name'] ?? '') === $fn ? 'selected' : '' ?>><?= htmlspecialchars($fn) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div id="edit-service-grp-wrap" class="form-group" style="display: <?= ($election['group_type'] ?? 'service_grp') === 'service_grp' ? 'block' : 'none' ?>;">
            <label for="group_id">Service Grp</label>
            <select id="group_id" name="group_id" <?= $d ?>>
                <option value="">— Select —</option>
                <?php foreach ($editMinistriesList as $min): ?>
                <option value="<?= (int)$min['id'] ?>" <?= (int)($election['group_id'] ?? 0) === (int)$min['id'] ? 'selected' : '' ?>><?= htmlspecialchars($min['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        </div>
        <div class="form-group">
            <label for="manager_user_id">Manager</label>
            <select id="manager_user_id" name="manager_user_id" <?= $d ?>>
                <option value="">— None —</option>
                <?php foreach ($editUsersList as $u): ?>
                <option value="<?= (int)$u['id'] ?>" <?= (int)($election['manager_user_id'] ?? 0) === (int)$u['id'] ? 'selected' : '' ?>><?= htmlspecialchars($u['username'] . ($u['full_name'] ? ' (' . $u['full_name'] . ')' : '') . ' – ' . $u['role']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group checkbox-row">
            <label>
                <input type="checkbox" name="enabled" value="1" <?= !empty($election['enabled']) ? 'checked' : '' ?> <?= $d ?>>
                Enabled (visible to manager)
            </label>
        </div>
        <?php endif; ?>
        <div class="form-actions">
            <?php if (!$electionOver): ?>
            <button type="submit" class="btn"><?= $isLocked ? 'Update Status' : ($isEdit ? 'Update Election' : 'Create Election') ?></button>
            <?php endif; ?>
            <a href="<?= BASE_PATH ?>/voting" class="btn btn-ghost"><?= $electionOver ? 'Back to Elections' : 'Cancel' ?></a>
        </div>
    </form>
</div>

<script>
(function() {
    var typeSelect = document.getElementById('type');
    var presbytersFields = document.getElementById('presbyters-fields');
    var assignmentWrap = document.getElementById('edit-assignment-wrap');
    if (typeSelect && presbytersFields) {
        function toggle() {
            presbytersFields.style.display = typeSelect.value === 'presbyters' ? 'block' : 'none';
            if (assignmentWrap) assignmentWrap.style.display = typeSelect.value === 'fellowship' ? 'block' : 'none';
        }
        typeSelect.addEventListener('change', toggle);
        toggle();
    }
    var genGrp = document.getElementById('edit-gen-grp-wrap');
    var serviceGrp = document.getElementById('edit-service-grp-wrap');
    var radios = document.querySelectorAll('input[name="group_type"]');
    if (genGrp && serviceGrp && radios.length) {
        function updateGroup() {
            var v = document.querySelector('input[name="group_type"]:checked');
            if (!v) return;
            genGrp.style.display = v.value === 'gen_grp' ? 'block' : 'none';
            serviceGrp.style.display = v.value === 'service_grp' ? 'block' : 'none';
        }
        radios.forEach(function(r) { r.addEventListener('change', updateGroup); });
        updateGroup();
    }
})();
</script>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
