<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Manage Timetable';
include 'header.php';

$conn = getConnection();
$days = ['','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
$activities = ['tasks','videos','trivia','ads','memes','spin'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $day = intval($_POST['day']);
    $activity = sanitize($_POST['activity']);
    $conn->query("INSERT INTO timetable (day_of_week, activity_type) VALUES ($day, '$activity') ON DUPLICATE KEY UPDATE status='active'");
    setFlash('success', 'Timetable updated!');
    redirect('timetable.php');
}

$schedule = $conn->query("SELECT * FROM timetable WHERE status='active' ORDER BY day_of_week");
?>
<div class="container">
    <div class="card">
        <h3>📅 Manage Timetable</h3>
        <p>Set which activities are available on which days</p>
        <form method="POST" style="background:#f9f9f9;padding:20px;border-radius:8px;margin:20px 0">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group"><label>Day</label><select name="day" class="form-control"><?php for($i=1;$i<=7;$i++) echo "<option value='$i'>$days[$i]</option>"; ?></select></div>
                </div>
                <div class="col-md-6">
                    <div class="form-group"><label>Activity</label><select name="activity" class="form-control"><?php foreach($activities as $a) echo "<option value='$a'>".ucfirst($a)."</option>"; ?></select></div>
                </div>
            </div>
            <button type="submit" class="btn btn-success">Add Schedule</button>
        </form>
        <table class="table">
            <tr><th>Day</th><th>Activity</th><th>Status</th><th>Actions</th></tr>
            <?php while ($item = $schedule->fetch_assoc()): ?>
            <tr>
                <td><?php echo $days[$item['day_of_week']]; ?></td>
                <td><?php echo ucfirst($item['activity_type']); ?></td>
                <td><?php echo $item['status']; ?></td>
                <td><a href="?delete=<?php echo $item['id']; ?>" class="btn btn-danger" style="padding:5px 10px">Delete</a></td>
            </tr>
            <?php endwhile; ?>
        </table>
    </div>
</div>
<?php include 'footer.php'; ?>
