<?php
// pages/calendar_manager.php
requireRole('roster_manager'); // Allows admins, coordinators, roster_managers

// Fetch Events for simple list
$events = $pdo->query("SELECT * FROM calendar_events ORDER BY event_date DESC, event_time ASC LIMIT 50")->fetchAll();

$msg = isset($_GET['msg']) ? htmlspecialchars($_GET['msg']) : '';
$error = isset($_GET['error']) ? htmlspecialchars($_GET['error']) : '';
?>

<div style="display: flex; justify-content: space-between; align-items: center;">
    <h1>Calendar Manager</h1>
    <a href="index.php?page=public_calendar" target="_blank" class="btn" style="background-color: var(--accent-color);">View Public Calendar</a>
</div>

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

<div class="dashboard-grid">
    <!-- Manual Add -->
    <div class="card">
        <h3>Add Single Event</h3>
        <form action="api/calendar_action.php" method="POST">
            <input type="hidden" name="action" value="manual_add">
            
            <div class="form-group">
                <label>Event Title</label>
                <input type="text" name="title" class="form-control" required placeholder="e.g. Workers Meeting">
            </div>
            
            <div class="form-group">
                <label>Date</label>
                <input type="date" name="event_date" id="event_date_input" class="form-control" required onchange="checkDate(this)">
            </div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                <div class="form-group">
                    <label>Start Time <small>(Optional)</small></label>
                    <input type="time" name="event_time" class="form-control">
                </div>
                <div class="form-group">
                    <label>Prayer Room Time <small>(Optional)</small></label>
                    <input type="time" name="prayer_time" id="prayer_time_input" class="form-control">
                </div>
            </div>
            
            <div class="form-group">
                <label>Description</label>
                <textarea name="description" class="form-control" rows="3"></textarea>
            </div>

            <!-- Recurrence Options -->
            <div style="background: rgba(255,255,255,0.05); padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                <h4 style="margin-top: 0; font-size: 1rem; color: var(--accent-color);">Recurrence Rules (Optional)</h4>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                    <div class="form-group">
                        <label>Frequency</label>
                        <select name="recurrence_freq" class="form-control">
                            <option value="none">None (One-time)</option>
                            <option value="daily">Daily</option>
                            <option value="weekly">Weekly</option>
                            <option value="monthly">Monthly</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Ends After</label>
                        <input type="date" name="recurrence_end" class="form-control" placeholder="Select End Date">
                    </div>
                </div>
            </div>
            
            <button type="submit" class="btn btn-block">Add Event(s)</button>
        </form>
    </div>
    
    <script>
    function checkDate(input) {
        // Logic: Sundays is fixed 7:30am, others blank
        const dateVal = input.value;
        if (!dateVal) return;
        
        const d = new Date(dateVal);
        // getDay(): 0 is Sunday
        if (d.getDay() === 0) {
            document.getElementById('prayer_time_input').value = '07:30';
        } else {
            // "leave prayer room blank untill entered manually"
            // We clear it only if it was auto-set? Or always?
            // Safer to clear it so user knows they have to enter it if they want.
            document.getElementById('prayer_time_input').value = '';
        }
    }
    </script>
    
    <!-- CSV Import -->
    <div class="card">
        <h3>Bulk Import (CSV)</h3>
        <p style="font-size: 0.9rem; color: #aaa;">Upload a CSV file with the following columns:</p>
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
            <code style="background: #333; padding: 5px; font-size: 0.8rem;">Date, Title, Time, Prayer Time, Description</code>
            <a href="api/download_sample_csv.php" class="btn" style="padding: 2px 8px; font-size: 0.8rem; background-color: #444;">Download Sample</a>
        </div>
        
        <form action="api/calendar_action.php" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="csv_import">
            <div class="form-group">
                <input type="file" name="csv_file" class="form-control" accept=".csv" required>
            </div>
            <button type="submit" class="btn btn-block" style="background-color: var(--secondary-color); color: #000;">Import CSV</button>
        </form>
        
        <div style="margin-top: 20px;">
            <h4>Sample CSV Content:</h4>
            <pre style="background: #222; padding: 10px; font-size: 0.75rem; color: #ccc;">
2023-12-25, Christmas Service, 09:00, 08:30, Special service
2023-12-31, Crossover Night, 21:00, , Watch night service
            </pre>
        </div>
    </div>
</div>

<!-- Event List -->
<div class="card" style="margin-top: 30px;">
    <h3>Upcoming / Recent Events</h3>
    <table class="table" style="width: 100%; border-collapse: collapse; margin-top: 15px;">
        <thead>
            <tr style="border-bottom: 2px solid #333; text-align: left;">
                <th style="padding: 10px;">Date & Time</th>
                <th style="padding: 10px;">Title</th>
                <th style="padding: 10px;">Prayer Room</th>
                <th style="padding: 10px; text-align: right;">Action</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($events as $e): ?>
            <tr style="border-bottom: 1px solid #333;">
                <td style="padding: 10px;">
                    <div style="font-weight: bold;"><?php echo date('M j, Y', strtotime($e['event_date'])); ?></div>
                    <small style="color: #aaa;"><?php echo $e['event_time'] ? date('h:i A', strtotime($e['event_time'])) : 'All Day'; ?></small>
                </td>
                <td style="padding: 10px;">
                    <?php echo htmlspecialchars($e['title']); ?>
                    <?php if ($e['description']): ?>
                        <div style="font-size: 0.8rem; color: #888;"><?php echo htmlspecialchars(substr($e['description'], 0, 50)) . (strlen($e['description']) > 50 ? '...' : ''); ?></div>
                    <?php endif; ?>
                </td>
                <td style="padding: 10px; color: var(--accent-color);">
                    <?php echo $e['prayer_time'] ? date('h:i A', strtotime($e['prayer_time'])) : '-'; ?>
                </td>
                <td style="padding: 10px; text-align: right;">
                    <div style="display: flex; gap: 5px; justify-content: flex-end;">
                        <button class="btn" style="background-color: var(--primary-color); padding: 5px 10px; font-size: 0.8rem;" 
                                onclick="openEditEventModal(<?php echo $e['id']; ?>, '<?php echo addslashes($e['title']); ?>', '<?php echo $e['event_date']; ?>', '<?php echo $e['event_time']??''; ?>', '<?php echo $e['prayer_time']??''; ?>', '<?php echo addslashes(str_replace("\n", "\\n", $e['description']??'')); ?>')">
                            Edit
                        </button>
                        <form action="api/calendar_action.php" method="POST" onsubmit="return confirm('Delete event?');" style="margin:0;">
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?php echo $e['id']; ?>">
                            <button type="submit" class="btn" style="background-color: var(--danger-color); padding: 5px 10px; font-size: 0.8rem;">Delete</button>
                        </form>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($events)): ?>
            <tr><td colspan="4" style="padding: 20px; text-align: center; color: #666;">No events found.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<!-- Edit Event Modal -->
<div id="editEventModal" 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 Event</h3>
        <button onclick="closeEditEventModal()" style="position: absolute; top: 15px; right: 15px; background: none; border: none; color: #fff; font-size: 1.5rem; cursor: pointer;">&times;</button>
        
        <form action="api/calendar_action.php" method="POST">
            <input type="hidden" name="action" value="update_event">
            <input type="hidden" name="id" id="edit_event_id">
            
            <div class="form-group">
                <label>Event Title</label>
                <input type="text" name="title" id="edit_event_title" class="form-control" required>
            </div>
            
            <div class="form-group">
                <label>Date</label>
                <input type="date" name="event_date" id="edit_event_date" class="form-control" required onchange="checkDateEdit(this)">
            </div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                <div class="form-group">
                    <label>Start Time</label>
                    <input type="time" name="event_time" id="edit_event_time" class="form-control">
                </div>
                <div class="form-group">
                    <label>Prayer Room Time</label>
                    <input type="time" name="prayer_time" id="edit_prayer_time" class="form-control">
                </div>
            </div>
            
            <div class="form-group">
                <label>Description</label>
                <textarea name="description" id="edit_event_desc" class="form-control" rows="3"></textarea>
            </div>
            
            <button type="submit" class="btn btn-block">Save Changes</button>
        </form>
    </div>
</div>

<script>
function openEditEventModal(id, title, date, time, prayer, desc) {
    document.getElementById('edit_event_id').value = id;
    document.getElementById('edit_event_title').value = title;
    document.getElementById('edit_event_date').value = date;
    document.getElementById('edit_event_time').value = time;
    document.getElementById('edit_prayer_time').value = prayer;
    document.getElementById('edit_event_desc').value = desc;
    
    document.getElementById('editEventModal').style.display = 'flex';
}
function closeEditEventModal() {
    document.getElementById('editEventModal').style.display = 'none';
}
function checkDateEdit(input) {
    const dateVal = input.value;
    if (!dateVal) return;
    const d = new Date(dateVal);
    if (d.getDay() === 0) {
        document.getElementById('edit_prayer_time').value = '07:30';
    } else {
        // Typically don't clear on edit unless user explicitly clears, 
        // effectively guiding them is enough.
        // But for consistency:
        // document.getElementById('edit_prayer_time').value = ''; 
    }
}
window.onclick = function(event) {
    if (event.target == document.getElementById('editEventModal')) {
        closeEditEventModal();
    }
}
</script>
