<?php
/**
 * Manage service types (admin only)
 */
if (!isAdmin()) {
    header('Location: ' . BASE_PATH . '/attendance');
    exit;
}

// Handle add
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_service'])) {
    $name = trim($_POST['name'] ?? '');
    if ($name === '') {
        $svcError = 'Name is required.';
    } else {
        try {
            $pdo->prepare("INSERT INTO service_types (name) VALUES (?)")->execute([$name]);
            header('Location: ' . BASE_PATH . '/attendance/services?toast=' . urlencode('Service type added.'));
            exit;
        } catch (PDOException $e) {
            $svcError = 'That name already exists.';
        }
    }
}

// Handle rename
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['rename_service'])) {
    $sid  = (int)$_POST['service_id'];
    $name = trim($_POST['name'] ?? '');
    if ($name !== '' && $sid) {
        try {
            $pdo->prepare("UPDATE service_types SET name=? WHERE id=?")->execute([$name, $sid]);
        } catch (PDOException $e) {}
    }
    header('Location: ' . BASE_PATH . '/attendance/services?toast=' . urlencode('Service type updated.'));
    exit;
}

// Handle toggle active
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_active'])) {
    $sid = (int)$_POST['service_id'];
    $pdo->prepare("UPDATE service_types SET is_active = 1 - is_active WHERE id=?")->execute([$sid]);
    header('Location: ' . BASE_PATH . '/attendance/services');
    exit;
}

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_service'])) {
    $sid = (int)$_POST['service_id'];
    if ($sid) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM attendance_records WHERE service_type_id=?");
        $stmt->execute([$sid]);
        $count = (int)$stmt->fetchColumn();
        if ($count === 0) {
            $pdo->prepare("DELETE FROM service_types WHERE id=?")->execute([$sid]);
            header('Location: ' . BASE_PATH . '/attendance/services?toast=' . urlencode('Service type deleted.'));
        } else {
            header('Location: ' . BASE_PATH . '/attendance/services?toast_error=' . urlencode("Cannot delete: $count attendance record(s) use this service type."));
        }
    }
    exit;
}

$serviceTypes = $pdo->query(
    "SELECT t.id, t.name, t.is_active,
            COUNT(r.id) AS record_count
     FROM service_types t
     LEFT JOIN attendance_records r ON r.service_type_id = t.id
     GROUP BY t.id ORDER BY t.name"
)->fetchAll();

$pageTitle = 'Manage Service Types';
require_once __DIR__ . '/../../includes/header.php';
?>

<style>
.svc-wrap { max-width: 600px; margin: 0 auto; }
.svc-card { background: #fff; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; margin-bottom: 1.5rem; }
.svc-card-head {
    padding: 0.875rem 1.25rem; background: #fafbff;
    border-bottom: 1px solid var(--border);
    font-size: 0.72rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.07em; color: var(--text-muted);
}
.svc-row {
    display: flex; align-items: center; gap: 0.75rem; padding: 0.75rem 1.25rem;
    border-bottom: 1px solid var(--border);
}
.svc-row:last-child { border-bottom: none; }
.svc-name  { flex: 1; font-size: 0.9375rem; color: var(--text); }
.svc-count { font-size: 0.78rem; color: var(--text-muted); min-width: 80px; }
.svc-inactive .svc-name { color: var(--text-muted); text-decoration: line-through; }

.add-form { padding: 1.25rem; }
.add-row  { display: flex; gap: 0.5rem; }
.add-row input {
    flex: 1; padding: 0.5rem 0.75rem;
    border: 1px solid var(--border); border-radius: 6px;
    font-size: 0.9375rem; color: var(--text);
}
.add-row input:focus { outline: none; border-color: var(--primary); }
</style>

<div class="svc-wrap">
    <div class="header">
        <h1>Service Types</h1>
        <div class="header-actions">
            <a href="<?= BASE_PATH ?>/attendance" class="btn btn-secondary">← Attendance</a>
            <a href="<?= BASE_PATH ?>/logout">Logout</a>
        </div>
    </div>

    <?php if (!empty($svcError)): ?>
        <div class="alert alert-error" style="margin-bottom:1rem;"><?= htmlspecialchars($svcError) ?></div>
    <?php endif; ?>

    <!-- Existing service types -->
    <?php if ($serviceTypes): ?>
    <div class="svc-card">
        <div class="svc-card-head">Existing Service Types</div>
        <?php foreach ($serviceTypes as $t): ?>
        <div class="svc-row <?= $t['is_active'] ? '' : 'svc-inactive' ?>">
            <span class="svc-name"><?= htmlspecialchars($t['name']) ?></span>
            <span class="svc-count"><?= (int)$t['record_count'] ?> record<?= $t['record_count'] != 1 ? 's' : '' ?></span>
            <div style="display:flex; gap:0.375rem;">
                <!-- Rename -->
                <button class="btn btn-sm btn-outline"
                        onclick="openRename(<?= $t['id'] ?>, '<?= htmlspecialchars(addslashes($t['name'])) ?>')">
                    Rename
                </button>
                <!-- Toggle active -->
                <form method="post" style="display:inline;">
                    <input type="hidden" name="service_id" value="<?= $t['id'] ?>">
                    <button type="submit" name="toggle_active" class="btn btn-sm btn-outline"
                            title="<?= $t['is_active'] ? 'Disable' : 'Enable' ?>">
                        <?= $t['is_active'] ? 'Disable' : 'Enable' ?>
                    </button>
                </form>
                <!-- Delete (only if no records) -->
                <?php if ((int)$t['record_count'] === 0): ?>
                <form method="post" style="display:inline;">
                    <input type="hidden" name="delete_service" value="1">
                    <input type="hidden" name="service_id" value="<?= $t['id'] ?>">
                    <button type="submit" class="btn btn-sm btn-outline-danger"
                            data-confirm="Delete service type '<?= htmlspecialchars($t['name']) ?>'?">
                        Delete
                    </button>
                </form>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <!-- Add new -->
    <div class="svc-card">
        <div class="svc-card-head">Add New Service Type</div>
        <div class="add-form">
            <form method="post">
                <div class="add-row">
                    <input type="text" name="name" placeholder="Dawn Broadcast, Youth Service…"
                           autofocus required maxlength="100">
                    <button type="submit" name="add_service" class="btn">Add</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Rename modal -->
<div id="rename-modal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.45); z-index:1000; align-items:center; justify-content:center;">
    <div style="background:#fff; border-radius:10px; padding:1.75rem; width:100%; max-width:420px; box-shadow:0 20px 60px rgba(0,0,0,0.2);">
        <h3 style="margin:0 0 1rem; font-size:1.1rem;">Rename Service Type</h3>
        <form method="post">
            <input type="hidden" name="service_id" id="rename-id">
            <input type="text" name="name" id="rename-input"
                   style="width:100%; padding:0.5rem 0.75rem; border:1px solid var(--border); border-radius:6px; font-size:0.9375rem; margin-bottom:1rem; box-sizing:border-box;">
            <div style="display:flex; gap:0.5rem; justify-content:flex-end;">
                <button type="button" class="btn btn-secondary" onclick="closeRename()">Cancel</button>
                <button type="submit" name="rename_service" class="btn">Save</button>
            </div>
        </form>
    </div>
</div>
<script>
function openRename(id, name) {
    document.getElementById('rename-id').value = id;
    document.getElementById('rename-input').value = name;
    var m = document.getElementById('rename-modal');
    m.style.display = 'flex';
    setTimeout(function() { document.getElementById('rename-input').focus(); }, 50);
}
function closeRename() {
    document.getElementById('rename-modal').style.display = 'none';
}
document.getElementById('rename-modal').addEventListener('click', function(e) {
    if (e.target === this) closeRename();
});
</script>

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