<?php
// pages/services.php
requireRole('any'); // Coordinators/Admins

$error = null;
$success = null;

// Handle success message from auto-close
if (isset($_GET['msg'])) {
    $success = htmlspecialchars($_GET['msg']);
}

// Handle Delete
if (isset($_GET['delete'])) {
    if (hasRole('admin')) {
        $id = (int)$_GET['delete'];
        $pdo->prepare("DELETE FROM services WHERE id = ?")->execute([$id]);
        $success = "Service deleted";
    }
}

// Handle Close Service
if (isset($_GET['close'])) {
    $id = (int)$_GET['close'];
    $pdo->prepare("UPDATE services SET status = 'Closed' WHERE id = ?")->execute([$id]);
    $success = "Service marked as Closed";
}

// Handle Manual Add
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_service') {
    $type = clean_input($_POST['type']);
    $date = $_POST['date'];
    $time = $_POST['time'];
    $name = clean_input($_POST['name']);
    
    $stmt = $pdo->prepare("INSERT INTO services (type, name, service_date, service_time) VALUES (?, ?, ?, ?)");
    if ($stmt->execute([$type, $name, $date, $time])) {
        $success = "Service added successfully";
    } else {
        $error = "Failed to add service";
    }
}
// Handle Edit Service
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit_service') {
    $id = (int)$_POST['id'];
    $type = clean_input($_POST['type']);
    $name = clean_input($_POST['name']);
    $date = $_POST['date']; // Validate if needed
    $time = $_POST['time'];
    
    $stmt = $pdo->prepare("UPDATE services SET type = ?, name = ?, service_date = ?, service_time = ? WHERE id = ?");
    if ($stmt->execute([$type, $name, $date, $time, $id])) {
        $success = "Service updated successfully";
        // Refresh page to show changes cleanly
        // header("Location: index.php?page=services&msg=Service updated"); exit; // Optional, but $success works 
    } else {
        $error = "Failed to update service";
    }
}

// Fetch Services
$filter_status = isset($_GET['status']) ? $_GET['status'] : 'Open';
$sql = "SELECT * FROM services WHERE 1=1";
if ($filter_status != 'All') {
    $sql .= " AND status = '$filter_status'";
}
$sql .= " ORDER BY service_date DESC, service_time DESC LIMIT 50";
$services = $pdo->query($sql)->fetchAll();
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
    <h1>Service & Event Management</h1>
    <!-- Auto-Close Removed -->
</div>

<?php if ($error): ?>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>
<?php if ($success): ?>
<div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>

<div class="dashboard-grid">
    <!-- Manual Add -->
    <div class="card" style="grid-column: span 2;">
        <h3>Add Special / Custom Service</h3>
        <form method="POST" style="display: flex; gap: 10px; align-items: flex-end; flex-wrap: wrap;">
            <input type="hidden" name="action" value="add_service">
            <div class="form-group" style="margin-bottom: 0;">
                <label>Type</label>
                <select name="type" class="form-control" required>
                    <option value="Special">Special Event</option>
                    <option value="Sunday Morning">Sunday Morning</option>
                    <option value="Bible Study">Bible Study</option>
                </select>
            </div>
             <div class="form-group" style="margin-bottom: 0;">
                <label>Name (Optional)</label>
                <input type="text" name="name" class="form-control" placeholder="e.g. Revival">
            </div>
            <div class="form-group" style="margin-bottom: 0;">
                <label>Date</label>
                <input type="date" name="date" class="form-control" required>
            </div>
            <div class="form-group" style="margin-bottom: 0;">
                <label>Time</label>
                <input type="time" name="time" class="form-control" required>
            </div>
            <button type="submit" class="btn">Add Service</button>
        </form>
    </div>
</div>

<div class="card" style="margin-top: 20px;">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
        <h3>Service List</h3>
        <div>
            <a href="index.php?page=services&status=Open" class="btn" style="<?php echo $filter_status=='Open'?'background-color:#444;':'background-color:transparent; border:1px solid #444;'; ?>">Open</a>
             <a href="index.php?page=services&status=Closed" class="btn" style="<?php echo $filter_status=='Closed'?'background-color:#444;':'background-color:transparent; border:1px solid #444;'; ?>">Closed</a>
            <a href="index.php?page=services&status=All" class="btn" style="<?php echo $filter_status=='All'?'background-color:#444;':'background-color:transparent; border:1px solid #444;'; ?>">All</a>
        </div>
    </div>

    <div class="table-responsive">
        <table>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Type / Name</th>
                    <th>Time</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($services as $s): ?>
                <tr>
                    <td><?php echo date('D, M j, Y', strtotime($s['service_date'])); ?></td>
                    <td>
                        <strong><?php echo htmlspecialchars($s['type']); ?></strong>
                        <?php if(!empty($s['name'])): ?>
                            <br><small><?php echo htmlspecialchars($s['name']); ?></small>
                        <?php endif; ?>
                    </td>
                    <td><?php echo date('g:i A', strtotime($s['service_time'])); ?></td>
                    <td>
                        <?php if($s['status'] == 'Open'): ?>
                            <span class="badge" style="background: var(--success-color); padding: 2px 6px; border-radius: 4px;">Open</span>
                        <?php else: ?>
                            <span class="badge" style="background: #555; padding: 2px 6px; border-radius: 4px;">Closed</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <button class="btn" style="padding: 5px 10px; font-size: 0.8rem; background: var(--primary-color);"
                              onclick="openEditModal(<?php echo $s['id']; ?>, '<?php echo $s['type']; ?>', '<?php echo addslashes($s['name']); ?>', '<?php echo $s['service_date']; ?>', '<?php echo $s['service_time']; ?>')">
                            Edit
                        </button>
                        <a href="index.php?page=roster&service_id=<?php echo $s['id']; ?>" class="btn" style="padding: 5px 10px; font-size: 0.8rem;">Roster</a>
                        <?php if($s['status'] == 'Open'): ?>
                        <a href="index.php?page=services&close=<?php echo $s['id']; ?>" class="btn" style="padding: 5px 10px; font-size: 0.8rem; background: #666;" onclick="return confirm('Close this service? This may affect attendance tracking.')">Close</a>
                        <?php endif; ?>
                        <?php if(hasRole('admin')): ?>
                        <a href="index.php?page=services&delete=<?php echo $s['id']; ?>" class="btn" style="padding: 5px 10px; font-size: 0.8rem; background: var(--danger-color);" onclick="return confirm('Delete this service?')">Delete</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Edit Modal -->
<div id="editServiceModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 1000; justify-content: center; align-items: center;">
    <div class="card" style="width: 100%; max-width: 500px; position: relative;">
        <h3>Edit Service</h3>
        <button onclick="closeEditModal()" style="position: absolute; top: 15px; right: 15px; background: none; border: none; color: #fff; font-size: 1.5rem; cursor: pointer;">&times;</button>
        
        <form method="POST">
            <input type="hidden" name="action" value="edit_service">
            <input type="hidden" name="id" id="edit_id">
            
            <div class="form-group">
                <label>Type</label>
                <select name="type" id="edit_type" class="form-control" required>
                    <option value="Special">Special Event</option>
                    <option value="Sunday Morning">Sunday Morning</option>
                    <option value="Bible Study">Bible Study</option>
                </select>
            </div>
            
            <div class="form-group">
                <label>Name (Optional)</label>
                <input type="text" name="name" id="edit_name" class="form-control">
            </div>
            
            <div class="form-group">
                <label>Date</label>
                <input type="date" name="date" id="edit_date" class="form-control" required>
            </div>
            
            <div class="form-group">
                <label>Time</label>
                <input type="time" name="time" id="edit_time" class="form-control" required>
            </div>
            
            <button type="submit" class="btn btn-block">Save Changes</button>
        </form>
    </div>
</div>

<script>
function openEditModal(id, type, name, date, time) {
    document.getElementById('edit_id').value = id;
    document.getElementById('edit_type').value = type;
    document.getElementById('edit_name').value = name;
    document.getElementById('edit_date').value = date;
    document.getElementById('edit_time').value = time;
    
    document.getElementById('editServiceModal').style.display = 'flex';
}
function closeEditModal() {
    document.getElementById('editServiceModal').style.display = 'none';
}
// Close on outside click
window.onclick = function(event) {
    if (event.target == document.getElementById('editServiceModal')) {
        closeEditModal();
    }
}
</script>
