<?php
session_start();
require_once '../config.php'; // adjust path

// Simple admin check (integrate with your existing admin login)
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_chamber'])) {
        $name = $conn->real_escape_string($_POST['name']);
        $address = $conn->real_escape_string($_POST['address']);
        $city = $conn->real_escape_string($_POST['city']);
        $phone = $conn->real_escape_string($_POST['phone']);
        $conn->query("INSERT INTO chambers (name, address, city, phone) VALUES ('$name', '$address', '$city', '$phone')");
        header("Location: chambers.php");
        exit;
    } elseif (isset($_POST['update_chamber'])) {
        $id = intval($_POST['chamber_id']);
        $name = $conn->real_escape_string($_POST['name']);
        $address = $conn->real_escape_string($_POST['address']);
        $city = $conn->real_escape_string($_POST['city']);
        $phone = $conn->real_escape_string($_POST['phone']);
        $status = $conn->real_escape_string($_POST['status']);
        $conn->query("UPDATE chambers SET name='$name', address='$address', city='$city', phone='$phone', status='$status' WHERE id=$id");
        header("Location: chambers.php");
        exit;
    } elseif (isset($_POST['delete_chamber'])) {
        $id = intval($_POST['chamber_id']);
        $conn->query("DELETE FROM chambers WHERE id=$id");
        header("Location: chambers.php");
        exit;
    } elseif (isset($_POST['save_slots'])) {
        $chamber_id = intval($_POST['chamber_id']);
        // Delete all existing slots for this chamber
        $conn->query("DELETE FROM chamber_schedules WHERE chamber_id = $chamber_id");
        // Insert new slots
        if (isset($_POST['slots']) && is_array($_POST['slots'])) {
            foreach ($_POST['slots'] as $slot) {
                $day = intval($slot['day']);
                $start = $conn->real_escape_string($slot['start']);
                $end = $conn->real_escape_string($slot['end']);
                $duration = intval($slot['duration']);
                $free_camp = isset($slot['free_camp']) ? 1 : 0;
                $notes = $conn->real_escape_string($slot['notes'] ?? '');
                $conn->query("INSERT INTO chamber_schedules (chamber_id, day_of_week, start_time, end_time, slot_duration, is_free_camp, notes) 
                              VALUES ($chamber_id, $day, '$start', '$end', $duration, $free_camp, '$notes')");
            }
        }
        header("Location: chambers.php?msg=Slots saved");
        exit;
    }
}

$chambers = $conn->query("SELECT * FROM chambers ORDER BY id");
$edit_chamber = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $edit_chamber = $conn->query("SELECT * FROM chambers WHERE id=$id")->fetch_assoc();
}
$slot_chamber_id = isset($_GET['slots']) ? intval($_GET['slots']) : null;
$slot_chamber = null;
$existing_slots = [];
if ($slot_chamber_id) {
    $slot_chamber = $conn->query("SELECT * FROM chambers WHERE id=$slot_chamber_id")->fetch_assoc();
    $res = $conn->query("SELECT * FROM chamber_schedules WHERE chamber_id=$slot_chamber_id ORDER BY day_of_week, start_time");
    while ($r = $res->fetch_assoc()) {
        $existing_slots[] = $r;
    }
}
$days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chamber & Time Slot Manager</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background: #f0f2f5; padding: 20px; }
        .container { max-width: 1400px; margin: auto; }
        .card { border-radius: 15px; margin-bottom: 30px; }
        .slot-row { background: #f9f9f9; margin-bottom: 10px; padding: 10px; border-radius: 8px; }
    </style>
</head>
<body>
<div class="container">
    <h2>🏥 Chamber & Time Slot Management</h2>
    <?php if (isset($_GET['msg'])): ?>
        <div class="alert alert-success"><?= htmlspecialchars($_GET['msg']) ?></div>
    <?php endif; ?>

    <!-- Chamber List -->
    <div class="card">
        <div class="card-header bg-primary text-white">Chambers <button class="btn btn-sm btn-light float-end" data-bs-toggle="modal" data-bs-target="#addChamberModal">+ Add New</button></div>
        <div class="card-body">
            <table class="table table-bordered">
                <thead class="table-light"><tr><th>ID</th><th>Name</th><th>Address</th><th>City</th><th>Status</th><th>Actions</th></tr></thead>
                <tbody>
                <?php while($ch = $chambers->fetch_assoc()): ?>
                <tr>
                    <td><?= $ch['id'] ?></td>
                    <td><?= htmlspecialchars($ch['name']) ?></td>
                    <td><?= htmlspecialchars($ch['address']) ?></td>
                    <td><?= htmlspecialchars($ch['city']) ?></td>
                    <td><span class="badge <?= $ch['status']=='active'?'bg-success':'bg-secondary' ?>"><?= $ch['status'] ?></span></td>
                    <td>
                        <a href="?edit=<?= $ch['id'] ?>" class="btn btn-sm btn-warning">Edit</a>
                        <a href="?slots=<?= $ch['id'] ?>" class="btn btn-sm btn-info">Time Slots</a>
                        <form method="post" style="display:inline-block;" onsubmit="return confirm('Delete?')"><input type="hidden" name="chamber_id" value="<?= $ch['id'] ?>"><button type="submit" name="delete_chamber" class="btn btn-sm btn-danger">Delete</button></form>
                    </td>
                </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Edit Chamber Form -->
    <?php if ($edit_chamber): ?>
    <div class="card">
        <div class="card-header bg-warning">Edit Chamber</div>
        <div class="card-body">
            <form method="post">
                <input type="hidden" name="chamber_id" value="<?= $edit_chamber['id'] ?>">
                <div class="row g-3">
                    <div class="col-md-4"><label>Name</label><input type="text" name="name" class="form-control" value="<?= htmlspecialchars($edit_chamber['name']) ?>" required></div>
                    <div class="col-md-4"><label>Address</label><input type="text" name="address" class="form-control" value="<?= htmlspecialchars($edit_chamber['address']) ?>"></div>
                    <div class="col-md-2"><label>City</label><input type="text" name="city" class="form-control" value="<?= htmlspecialchars($edit_chamber['city']) ?>"></div>
                    <div class="col-md-2"><label>Phone</label><input type="text" name="phone" class="form-control" value="<?= htmlspecialchars($edit_chamber['phone']) ?>"></div>
                    <div class="col-md-2"><label>Status</label><select name="status" class="form-control"><option value="active" <?= $edit_chamber['status']=='active'?'selected':'' ?>>Active</option><option value="inactive" <?= $edit_chamber['status']=='inactive'?'selected':'' ?>>Inactive</option></select></div>
                    <div class="col-12"><button type="submit" name="update_chamber" class="btn btn-primary">Update</button></div>
                </div>
            </form>
        </div>
    </div>
    <?php endif; ?>

    <!-- Manage Time Slots for a Chamber -->
    <?php if ($slot_chamber_id && $slot_chamber): ?>
    <div class="card">
        <div class="card-header bg-success text-white">Time Slots for: <?= htmlspecialchars($slot_chamber['name']) ?></div>
        <div class="card-body">
            <form method="post" id="slotForm">
                <input type="hidden" name="chamber_id" value="<?= $slot_chamber_id ?>">
                <div id="slotsContainer">
                    <?php foreach ($existing_slots as $idx => $slot): ?>
                    <div class="slot-row row g-2">
                        <input type="hidden" name="slots[<?= $idx ?>][id]" value="<?= $slot['id'] ?>">
                        <div class="col-md-2"><label>Day</label><select name="slots[<?= $idx ?>][day]" class="form-control"><?php for($i=0;$i<7;$i++): ?><option value="<?= $i ?>" <?= $i==$slot['day_of_week']?'selected':'' ?>><?= $days[$i] ?></option><?php endfor; ?></select></div>
                        <div class="col-md-2"><label>Start</label><input type="time" name="slots[<?= $idx ?>][start]" class="form-control" value="<?= $slot['start_time'] ?>" required></div>
                        <div class="col-md-2"><label>End</label><input type="time" name="slots[<?= $idx ?>][end]" class="form-control" value="<?= $slot['end_time'] ?>" required></div>
                        <div class="col-md-1"><label>Duration(min)</label><input type="number" name="slots[<?= $idx ?>][duration]" class="form-control" value="<?= $slot['slot_duration'] ?>" required></div>
                        <div class="col-md-1"><label>Free Camp</label><input type="checkbox" name="slots[<?= $idx ?>][free_camp]" value="1" <?= $slot['is_free_camp']?'checked':'' ?>></div>
                        <div class="col-md-3"><label>Notes</label><input type="text" name="slots[<?= $idx ?>][notes]" class="form-control" value="<?= htmlspecialchars($slot['notes'] ?? '') ?>"></div>
                        <div class="col-md-1"><label>&nbsp;</label><button type="button" class="btn btn-danger remove-slot">✖</button></div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <div class="mt-3">
                    <button type="button" class="btn btn-secondary" id="addSlotBtn">+ Add Another Time Slot</button>
                    <button type="submit" name="save_slots" class="btn btn-success">Save All Slots</button>
                    <a href="chambers.php" class="btn btn-light">Back</a>
                </div>
            </form>
        </div>
    </div>
    <script>
        let slotIndex = <?= count($existing_slots) ?>;
        document.getElementById('addSlotBtn').addEventListener('click', function() {
            let container = document.getElementById('slotsContainer');
            let newRow = document.createElement('div');
            newRow.className = 'slot-row row g-2';
            newRow.innerHTML = `
                <input type="hidden" name="slots[${slotIndex}][id]" value="">
                <div class="col-md-2"><select name="slots[${slotIndex}][day]" class="form-control"><?php for($i=0;$i<7;$i++): ?><option value="<?= $i ?>"><?= $days[$i] ?></option><?php endfor; ?></select></div>
                <div class="col-md-2"><input type="time" name="slots[${slotIndex}][start]" class="form-control" required></div>
                <div class="col-md-2"><input type="time" name="slots[${slotIndex}][end]" class="form-control" required></div>
                <div class="col-md-1"><input type="number" name="slots[${slotIndex}][duration]" class="form-control" value="30" required></div>
                <div class="col-md-1"><input type="checkbox" name="slots[${slotIndex}][free_camp]" value="1"></div>
                <div class="col-md-3"><input type="text" name="slots[${slotIndex}][notes]" class="form-control" placeholder="e.g., Closed on govt holiday"></div>
                <div class="col-md-1"><button type="button" class="btn btn-danger remove-slot">✖</button></div>
            `;
            container.appendChild(newRow);
            slotIndex++;
            attachRemoveEvents();
        });
        function attachRemoveEvents() {
            document.querySelectorAll('.remove-slot').forEach(btn => {
                btn.removeEventListener('click', removeHandler);
                btn.addEventListener('click', removeHandler);
            });
        }
        function removeHandler(e) {
            e.target.closest('.slot-row').remove();
        }
        attachRemoveEvents();
    </script>
    <?php endif; ?>
</div>

<!-- Add Chamber Modal -->
<div class="modal fade" id="addChamberModal" tabindex="-1">
    <div class="modal-dialog"><div class="modal-content"><form method="post"><div class="modal-header bg-primary text-white"><h5>Add Chamber</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><div class="mb-2"><label>Name*</label><input type="text" name="name" class="form-control" required></div><div class="mb-2"><label>Address</label><input type="text" name="address" class="form-control"></div><div class="mb-2"><label>City</label><input type="text" name="city" class="form-control"></div><div class="mb-2"><label>Phone</label><input type="text" name="phone" class="form-control"></div></div><div class="modal-footer"><button type="submit" name="add_chamber" class="btn btn-primary">Add</button></div></form></div></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>