<?php
/**
 * Record / edit a single attendance entry (aggregate counts)
 */

require_once __DIR__ . '/../../includes/audit.php';

$isEdit = ($action === 'edit' && $id);
$record = null;

$currentServiceTypeName = '';
if ($isEdit) {
    $stmt = $pdo->prepare("SELECT r.*, t.name AS service_type_name FROM attendance_records r JOIN service_types t ON t.id = r.service_type_id WHERE r.id = ?");
    $stmt->execute([$id]);
    $record = $stmt->fetch();
    if (!$record) {
        header('Location: ' . BASE_PATH . '/attendance');
        exit;
    }
    $currentServiceTypeName = $record['service_type_name'] ?? '';
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $serviceTypeId   = (int)($_POST['service_type_id'] ?? 0);
    $serviceTypeName = trim($_POST['service_type_new_name'] ?? '');
    $date            = trim($_POST['date'] ?? '');
    $maleCount       = max(0, (int)($_POST['male_count'] ?? 0));
    $femaleCount     = max(0, (int)($_POST['female_count'] ?? 0));
    $childrenCount   = max(0, (int)($_POST['children_count'] ?? 0));
    $visitorsCount   = max(0, (int)($_POST['visitors_count'] ?? 0));
    $notes           = trim($_POST['notes'] ?? '');

    if ($serviceTypeId === -1 && $serviceTypeName === '') $errors[] = 'Please enter a new service type name.';
    if ($serviceTypeId === 0) $errors[] = 'Please select a service type.';
    if (!$date || !strtotime($date)) $errors[] = 'Please enter a valid date.';
    if ($maleCount + $femaleCount + $childrenCount + $visitorsCount === 0)
        $errors[] = 'Please enter at least one count.';

    if (empty($errors)) {
        if ($serviceTypeId === -1) {
            // Resolve service type by name: find existing (any status) or create
            $stmt = $pdo->prepare("SELECT id FROM service_types WHERE LOWER(TRIM(name)) = LOWER(?)");
            $stmt->execute([$serviceTypeName]);
            $row = $stmt->fetch();
            if ($row) {
                $serviceTypeId = (int)$row['id'];
            } else {
                $pdo->prepare("INSERT INTO service_types (name) VALUES (?)")->execute([$serviceTypeName]);
                $serviceTypeId = (int)$pdo->lastInsertId();
            }
        }

        if ($isEdit) {
            $pdo->prepare(
                "UPDATE attendance_records
                 SET service_type_id=?, date=?, male_count=?, female_count=?,
                     children_count=?, visitors_count=?, notes=?
                 WHERE id=?"
            )->execute([$serviceTypeId, $date, $maleCount, $femaleCount, $childrenCount, $visitorsCount, $notes ?: null, $id]);
            $msg = 'Attendance updated.';
            $eventAction = 'attendance_updated';
        } else {
            try {
                $pdo->prepare(
                    "INSERT INTO attendance_records
                     (service_type_id, date, male_count, female_count, children_count, visitors_count, notes)
                     VALUES (?,?,?,?,?,?,?)"
                )->execute([$serviceTypeId, $date, $maleCount, $femaleCount, $childrenCount, $visitorsCount, $notes ?: null]);
                $msg = 'Attendance recorded.';
                $eventAction = 'attendance_recorded';
            } catch (PDOException $e) {
                if ($e->getCode() === '23000') {
                    $errors[] = 'An attendance record for this service type and date already exists. Please edit it instead.';
                } else {
                    throw $e;
                }
            }
        }
        if (empty($errors)) {
            try {
                $stmt = $pdo->prepare('SELECT name FROM service_types WHERE id = ?');
                $stmt->execute([$serviceTypeId]);
                $serviceTypeLabel = $stmt->fetchColumn() ?: 'Service';
                logActivity(
                    $eventAction ?? 'attendance_saved',
                    ($eventAction === 'attendance_updated' ? 'Updated' : 'Recorded') . " attendance for {$serviceTypeLabel} on {$date}",
                    [
                        'service_type_id' => $serviceTypeId,
                        'service_type' => $serviceTypeLabel,
                        'date' => $date,
                        'male' => $maleCount,
                        'female' => $femaleCount,
                        'children' => $childrenCount,
                        'visitors' => $visitorsCount,
                        'total' => ($maleCount + $femaleCount + $childrenCount + $visitorsCount),
                        'notes' => $notes ?: null,
                        'attendance_record_id' => $isEdit ? $id : (int)$pdo->lastInsertId(),
                    ]
                );
            } catch (Throwable $e) {
                // Never block save on audit failure
            }
            header('Location: ' . BASE_PATH . '/attendance?toast=' . urlencode($msg));
            exit;
        }
    }
}

$serviceTypes = $pdo->query("SELECT id, name FROM service_types WHERE is_active=1 ORDER BY name")->fetchAll();

$pageTitle   = $isEdit ? 'Edit Attendance' : 'Record Attendance';
require_once __DIR__ . '/../../includes/header.php';
?>

<style>
.rec-wrap  { max-width: 520px; margin: 0 auto; }
.rec-card  { background: #fff; border: 1px solid var(--border); border-radius: 8px; padding: 1.75rem; }
.rec-field { margin-bottom: 1.125rem; }
.rec-field label { display: block; font-size: 0.8125rem; font-weight: 500; color: var(--text); margin-bottom: 0.35rem; }
.rec-field input, .rec-field select, .rec-field textarea {
    width: 100%; padding: 0.5rem 0.75rem;
    border: 1px solid var(--border); border-radius: 6px;
    font-size: 0.9375rem; color: var(--text); font-family: inherit;
    box-sizing: border-box;
}
.rec-field input:focus, .rec-field select:focus, .rec-field textarea:focus {
    outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(30,58,95,0.08);
}
.rec-counts { display: grid; grid-template-columns: 1fr 1fr; gap: 0.875rem; }
.rec-total-bar {
    display: flex; align-items: center; justify-content: space-between;
    background: #f0f4ff; border: 1px solid #c7d6f5; border-radius: 6px;
    padding: 0.75rem 1rem; margin-bottom: 1.25rem;
    font-size: 0.875rem;
}
.rec-total-bar strong { font-size: 1.5rem; color: var(--primary); }
.rec-field-error { color: #dc2626; font-size: 0.8rem; margin-top: 0.25rem; }
.count-label { display: flex; align-items: center; gap: 0.4rem; }
.count-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
.dot-m { background: #3b82f6; }
.dot-f { background: #ec4899; }
.dot-c { background: #10b981; }
.dot-v { background: #f59e0b; }
</style>

<div class="header">
    <h1><?= $isEdit ? 'Edit Attendance' : 'Record Attendance' ?></h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/attendance" class="btn btn-secondary">← Back</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<div class="rec-wrap">
    <?php if (!empty($errors)): ?>
        <?php foreach ($errors as $e): ?>
            <div class="alert alert-error" style="margin-bottom:0.75rem;"><?= htmlspecialchars($e) ?></div>
        <?php endforeach; ?>
    <?php endif; ?>

    <div class="rec-card">
        <form method="post" id="rec-form">
            <div class="rec-field">
                <label for="service_type_id">Service type *</label>
                <?php
                    $selectedId = (int)($_POST['service_type_id'] ?? 0);
                    if ($isEdit && $selectedId === 0) {
                        // Try to preselect based on current name
                        foreach ($serviceTypes as $t) {
                            if (strcasecmp(trim($t['name']), trim($currentServiceTypeName)) === 0) {
                                $selectedId = (int)$t['id'];
                                break;
                            }
                        }
                    }
                ?>
                <select id="service_type_id" name="service_type_id" required onchange="toggleNewServiceType()">
                    <option value="0">— Select —</option>
                    <?php foreach ($serviceTypes as $t): ?>
                        <option value="<?= (int)$t['id'] ?>" <?= $selectedId === (int)$t['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($t['name']) ?>
                        </option>
                    <?php endforeach; ?>
                    <option value="-1" <?= $selectedId === -1 ? 'selected' : '' ?>>+ Add new service type…</option>
                </select>
                <div id="new-service-type-wrap" style="display:none; margin-top:0.6rem;">
                    <input type="text" id="service_type_new_name" name="service_type_new_name"
                           value="<?= htmlspecialchars($_POST['service_type_new_name'] ?? '') ?>"
                           placeholder="Type a new service name…" maxlength="100" autocomplete="off">
                </div>
            </div>

            <div class="rec-field">
                <label for="att-date">Date *</label>
                <input type="date" id="att-date" name="date" required
                       value="<?= htmlspecialchars($record['date'] ?? ($_POST['date'] ?? date('Y-m-d'))) ?>">
            </div>

            <!-- Total live preview -->
            <div class="rec-total-bar">
                <span>Total attendance</span>
                <strong id="live-total">0</strong>
            </div>

            <div class="rec-counts">
                <div class="rec-field">
                    <label class="count-label">
                        <span class="count-dot dot-m"></span> Male
                    </label>
                    <input type="number" name="male_count" id="male_count" min="0" value="<?= (int)($record['male_count'] ?? ($_POST['male_count'] ?? 0)) ?>"
                           oninput="updateTotal()" placeholder="0">
                </div>
                <div class="rec-field">
                    <label class="count-label">
                        <span class="count-dot dot-f"></span> Female
                    </label>
                    <input type="number" name="female_count" id="female_count" min="0" value="<?= (int)($record['female_count'] ?? ($_POST['female_count'] ?? 0)) ?>"
                           oninput="updateTotal()" placeholder="0">
                </div>
                <div class="rec-field">
                    <label class="count-label">
                        <span class="count-dot dot-c"></span> Children
                    </label>
                    <input type="number" name="children_count" id="children_count" min="0" value="<?= (int)($record['children_count'] ?? ($_POST['children_count'] ?? 0)) ?>"
                           oninput="updateTotal()" placeholder="0">
                </div>
                <div class="rec-field">
                    <label class="count-label">
                        <span class="count-dot dot-v"></span> Visitors
                    </label>
                    <input type="number" name="visitors_count" id="visitors_count" min="0" value="<?= (int)($record['visitors_count'] ?? ($_POST['visitors_count'] ?? 0)) ?>"
                           oninput="updateTotal()" placeholder="0">
                </div>
            </div>

            <div class="rec-field">
                <label for="att-notes">Notes <span style="font-weight:400; color:var(--text-muted);">(optional)</span></label>
                <textarea id="att-notes" name="notes" rows="2"
                          placeholder="Public holiday, guest speaker…"><?= htmlspecialchars($record['notes'] ?? ($_POST['notes'] ?? '')) ?></textarea>
            </div>

            <button type="submit" class="btn" style="width:100%; padding:0.65rem;">
                <?= $isEdit ? 'Save Changes' : 'Save Attendance' ?>
            </button>
        </form>
    </div>
</div>

<script>
function updateTotal() {
    var m = parseInt(document.getElementById('male_count').value)     || 0;
    var f = parseInt(document.getElementById('female_count').value)   || 0;
    var c = parseInt(document.getElementById('children_count').value) || 0;
    var v = parseInt(document.getElementById('visitors_count').value) || 0;
    document.getElementById('live-total').textContent = m + f + c + v;
}
updateTotal();

function toggleNewServiceType() {
    var sel = document.getElementById('service_type_id');
    var wrap = document.getElementById('new-service-type-wrap');
    var isNew = sel && String(sel.value) === '-1';
    if (wrap) wrap.style.display = isNew ? 'block' : 'none';
}
toggleNewServiceType();
</script>

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