<?php
// Default user_id for testing
$user_id = 1;

// Connect to the rmgt database
require_once 'config.php';
$rmgt_conn = new mysqli('database-1.cpxjovqfaduk.eu-west-2.rds.amazonaws.com', 'admin', 'efoih24524aedfawtga!SFD', 'rmgt');
if ($rmgt_conn->connect_error) {
    $students_error = 'Database connection failed: ' . $rmgt_conn->connect_error;
    $students = [];
} else {
    // Determine the selected date (default to current date)
    $selected_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
    $selected_day = date('l', strtotime($selected_date)); // e.g., "Thursday"

    // Fetch students scheduled for the selected day, along with their latest progress
    $query = "
        SELECT s.student_id, s.forename, s.surname, s.time_slot, p.progress, p.datetimestamp
        FROM students s
        LEFT JOIN (
            SELECT student_id, progress, datetimestamp
            FROM student_progress
            WHERE (student_id, datetimestamp) IN (
                SELECT student_id, MAX(datetimestamp)
                FROM student_progress
                GROUP BY student_id
            )
        ) p ON s.student_id = p.student_id
        WHERE s.active = 1
        AND s.day_of_week = ?
        ORDER BY s.time_slot ASC
    ";
    $stmt = $rmgt_conn->prepare($query);
    $stmt->bind_param('s', $selected_day);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result === false) {
        $students_error = 'Error fetching students: ' . $rmgt_conn->error;
        $students = [];
    } else {
        $students = $result->fetch_all(MYSQLI_ASSOC);
        $students_error = empty($students) ? 'No students scheduled for this day.' : null;
    }
    $stmt->close();
    $rmgt_conn->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="theme-color" content="#1E40AF">
    <title>Student Schedule</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        body {
            background: linear-gradient(to bottom, #050244 0px, #050244 270px, #E6F0FA 320px, #E6F0FA 100%);
            color: #1F2937;
            min-height: 100vh;
            overflow-x: hidden;
            display: flex;
            flex-direction: column;
        }
        header {
            background-color: #1E40AF;
            color: white;
            padding: 1rem;
            position: sticky;
            top: 0;
            z-index: 50;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        header h1 {
            font-size: 1.25rem;
            font-weight: 600;
        }
        #menu-toggle {
            background: none;
            border: none;
            cursor: pointer;
            padding: 0.5rem;
        }
        #menu-toggle svg {
            width: 1.5rem;
            height: 1.5rem;
        }
        #sidebar {
            position: fixed;
            top: 0;
            left: 0;
            width: 75%;
            max-width: 280px;
            height: 100%;
            background: white;
            z-index: 60;
            transform: translateX(-100%);
            transition: transform 0.3s ease;
            box-shadow: 2px 0 8px rgba(0, 0, 0, 0.2);
        }
        #sidebar.open {
            transform: translateX(0);
        }
        #sidebar .p-4 {
            padding: 1rem;
        }
        #sidebar h2 {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1F2937;
            margin-bottom: 1rem;
        }
        #sidebar ul li a {
            display: flex;
            align-items: center;
            padding: 0.75rem 1rem;
            color: #1F2937;
            text-decoration: none;
            border-radius: 0.375rem;
            margin-bottom: 0.25rem;
        }
        #sidebar ul li a:hover {
            background-color: #F3F4F6;
        }
        #sidebar ul li a svg {
            width: 1rem;
            height: 1rem;
            margin-right: 0.5rem;
        }
        #sidebar-overlay {
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 55;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s ease;
        }
        #sidebar-overlay.active {
            opacity: 1;
            pointer-events: auto;
        }
        main {
            flex: 1;
            padding: 1rem;
            padding-bottom: 4rem;
        }
        section {
            background: white;
            border-radius: 0.5rem;
            margin-bottom: 1rem;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            overflow: hidden;
        }
        .content {
            padding: 1rem;
            padding-top: 0;
        }
        ul li {
            padding: 0.5rem 0;
            font-size: 0.95rem;
        }
        .student-item {
            border-bottom: 1px solid #E5E7EB;
            padding-bottom: 0.5rem;
            margin-bottom: 0.5rem;
            cursor: pointer;
        }
        .student-item:hover {
            background-color: #F9FAFB;
        }
        .student-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }
        .student-name {
            font-weight: 600;
            color: #1F2937;
        }
        .student-time {
            color: #4B5563;
            font-size: 0.9rem;
        }
        .student-progress {
            color: #6B7280;
            font-size: 0.9rem;
            margin-top: 0.25rem;
        }
        .student-timestamp {
            color: #9CA3AF;
            font-size: 0.85rem;
        }
        .progress-form {
            display: none;
            margin-top: 0.5rem;
            padding: 0.5rem;
            background: #F9FAFB;
            border-radius: 0.375rem;
        }
        .progress-form textarea {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid #D1D5DB;
            border-radius: 0.375rem;
            font-size: 0.9rem;
            resize: vertical;
        }
        .progress-form textarea:focus {
            outline: none;
            border-color: #1E40AF;
            box-shadow: 0 0 0 2px rgba(30, 64, 175, 0.2);
        }
        .progress-form button {
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 0.375rem;
            font-weight: 500;
            cursor: pointer;
            margin-right: 0.5rem;
            margin-top: 0.5rem;
        }
        .progress-form button.primary {
            background: #1E40AF;
            color: white;
        }
        .progress-form button.primary:hover {
            background: #1E3A8A;
        }
        .progress-form button.secondary {
            background: #6B7280;
            color: white;
        }
        .progress-form button.secondary:hover {
            background: #4B5563;
        }
        .progress-form-message {
            margin-top: 0.5rem;
            font-size: 0.85rem;
        }
        .date-nav {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 1rem;
            gap: 0.5rem;
        }
        .date-nav button {
            background: #1E40AF;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 0.375rem;
            cursor: pointer;
            transition: background 0.2s ease;
        }
        .date-nav button:hover {
            background: #1E3A8A;
        }
        .date-nav input[type="date"] {
            padding: 0.5rem;
            border: 1px solid #D1D5DB;
            border-radius: 0.375rem;
            font-size: 0.95rem;
        }
        .bottom-toolbar {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-around;
            align-items: center;
            padding: 0.5rem 0;
            z-index: 50;
        }
        .toolbar-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            text-decoration: none;
            color: #1F2937;
            padding: 0.25rem;
        }
        .toolbar-item svg {
            width: 1.5rem;
            height: 1.5rem;
            margin-bottom: 0.25rem;
        }
        .toolbar-item span {
            font-size: 0.75rem;
            font-weight: 500;
        }
        .section-title {
            display: flex;
            align-items: center;
            font-size: 1.125rem;
            font-weight: 600;
            color: #1F2937;
            padding: 1rem;
        }
        .text-red-500 {
            color: #EF4444;
        }
        .text-green-500 {
            color: #10B981;
        }
        @media (min-width: 640px) {
            main {
                max-width: 24rem;
                margin-left: auto;
                margin-right: auto;
            }
        }
    </style>
</head>
<body>
    <header>
        <h1>Student Schedule</h1>
        <button id="menu-toggle">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16m-7 6h7"></path>
            </svg>
        </button>
    </header>

    <div id="sidebar">
        <div class="p-4">
            <h2>Menu</h2>
            <ul>
                <li>
                    <a href="dashboard.php" class="flex items-center">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"></path>
                        </svg>
                        Accounts Dashboard
                    </a>
                </li>
                <li>
                    <a href="personal.php" class="flex items-center">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19l-7 1 1-7 5-5 5 5 1 7-7-1zm0 0l7-1m-7 1V9m7 1l-1 7m-5-5l-1 1m1-1l1-1"></path>
                        </svg>
                        Financial Details
                    </a>
                </li>
                <li>
                    <a href="rm_guitar.php" class="flex items-center">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0zm-3 8a8 8 0 100-16 8 8 0 000 16z"></path>
                        </svg>
                        RM Guitar
                    </a>
                </li>
                <li>
                    <a href="update_financials.php" class="flex items-center">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15.828a2 2 0 01-2.828 0l-1.414-1.414a2 2 0 010-2.828L15.172 4z"></path>
                        </svg>
                        Update Financials
                    </a>
                </li>
                <li>
                    <a href="student_schedule.php" class="flex items-center">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                        </svg>
                        Student Schedule
                    </a>
                </li>
                <li>
                    <a href="logout.php" class="flex items-center text-red-500">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path>
                        </svg>
                        Logout
                    </a>
                </li>
            </ul>
        </div>
    </div>

    <div id="sidebar-overlay"></div>

    <main>
        <section>
            <h2 class="section-title">Student Schedule for <?php echo htmlspecialchars(date('l, jS F Y', strtotime($selected_date))); ?></h2>
            <div class="content">
                <ul>
                    <?php if (isset($students_error)): ?>
                        <li><span class="text-red-500"><?php echo htmlspecialchars($students_error); ?></span></li>
                    <?php else: ?>
                        <?php foreach ($students as $student): ?>
                            <li class="student-item" onclick="toggleProgressForm(<?php echo $student['student_id']; ?>)">
                                <div>
                                    <div class="student-name">
                                        <?php echo htmlspecialchars($student['forename'] . ' ' . ($student['surname'] ?? '')); ?>
                                        <span class="student-time"> - <?php echo htmlspecialchars($student['time_slot']); ?></span>
                                    </div>
                                    <?php if (!empty($student['progress'])): ?>
                                        <div class="student-progress">
                                            Last worked on: <?php echo htmlspecialchars($student['progress']); ?>
                                        </div>
                                        <div class="student-timestamp">
                                            Updated: <?php echo date('Y-m-d H:i', strtotime($student['datetimestamp'])); ?>
                                        </div>
                                    <?php else: ?>
                                        <div class="student-progress">No progress recorded.</div>
                                    <?php endif; ?>
                                </div>
                                <form id="progress-form-<?php echo $student['student_id']; ?>" class="progress-form" method="POST" onsubmit="updateProgress(event, <?php echo $student['student_id']; ?>)">
                                    <input type="hidden" name="student_id" value="<?php echo $student['student_id']; ?>">
                                    <div>
                                        <label for="progress-<?php echo $student['student_id']; ?>">Update Progress:</label>
                                        <textarea id="progress-<?php echo $student['student_id']; ?>" name="progress" rows="3"><?php echo htmlspecialchars($student['progress'] ?? ''); ?></textarea>
                                    </div>
                                    <div>
                                        <button type="submit" class="primary">Save</button>
                                        <button type="button" class="secondary" onclick="toggleProgressForm(<?php echo $student['student_id']; ?>)">Cancel</button>
                                    </div>
                                    <div id="progress-message-<?php echo $student['student_id']; ?>" class="progress-form-message"></div>
                                </form>
                            </li>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </ul>
                <div class="date-nav">
                    <button onclick="navigateDay(-1)">Previous Day</button>
                    <input type="date" id="date-picker" value="<?php echo htmlspecialchars($selected_date); ?>" onchange="selectDate()">
                    <button onclick="navigateDay(1)">Next Day</button>
                </div>
            </div>
        </section>
    </main>

    <div class="bottom-toolbar">
        <a href="dashboard.php" class="toolbar-item">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"></path>
            </svg>
            <span>Accounts</span>
        </a>
        <a href="personal.php" class="toolbar-item">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.1 0-2 .9-2 2v4c0 1.1.9 2 2 2s2-.9 2-2v-4c0-1.1-.9-2-2-2zm0 6c-.55 0-1-.45-1-1v-2c0-.55.45-1 1-1s1 .45 1 1v2c0 .55-.45 1-1 1zm8-2h-1v-1c0-2.76-2.24-5-5-5h-4c-2.76 0-5 2.24-5 5v1H4c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h16c.55 0 1-.45 1-1v-4c0-.55-.45-1-1-1zm-1 4H5v-3h14v3z"></path>
            </svg>
            <span>Financials</span>
        </a>
        <a href="rm_guitar.php" class="toolbar-item">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.75 10.5l-3.25-3.25m0 0l-3.25 3.25M12 7.25v10.5m7.5-10.5h-3m-9 0H3.75m12 7.5h-3m-9 0H3.75"></path>
            </svg>
            <span>RM Guitar</span>
        </a>
        <a href="update_financials.php" class="toolbar-item">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15.828a2 2 0 01-2.828 0l-1.414-1.414a2 2 0 010-2.828L15.172 4z"></path>
            </svg>
            <span>Update</span>
        </a>
        <a href="student_schedule.php" class="toolbar-item">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
            </svg>
            <span>Schedule</span>
        </a>
    </div>

    <script>
        // Sidebar toggle
        const menuToggle = document.getElementById('menu-toggle');
        const sidebar = document.getElementById('sidebar');
        const sidebarOverlay = document.getElementById('sidebar-overlay');

        menuToggle.addEventListener('click', () => {
            sidebar.classList.toggle('open');
            sidebarOverlay.classList.toggle('active');
        });

        sidebarOverlay.addEventListener('click', () => {
            sidebar.classList.remove('open');
            sidebarOverlay.classList.remove('active');
        });

        // Date navigation functions
        function navigateDay(offset) {
            const datePicker = document.getElementById('date-picker');
            let currentDate = new Date(datePicker.value);
            currentDate.setDate(currentDate.getDate() + offset);
            datePicker.value = currentDate.toISOString().split('T')[0];
            selectDate();
        }

        function selectDate() {
            const datePicker = document.getElementById('date-picker');
            window.location.href = 'student_schedule.php?date=' + datePicker.value;
        }

        // Toggle progress form visibility
        function toggleProgressForm(studentId) {
            const form = document.getElementById('progress-form-' + studentId);
            form.style.display = form.style.display === 'block' ? 'none' : 'block';
        }

        // Update progress
        async function updateProgress(event, studentId) {
            event.preventDefault();
            const form = document.getElementById('progress-form-' + studentId);
            const formMessage = document.getElementById('progress-message-' + studentId);
            const formData = new FormData(form);

            try {
                const response = await fetch('update_progress.php', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();
                formMessage.textContent = result.success || result.error;
                formMessage.className = result.success ? 'progress-form-message text-green-500' : 'progress-form-message text-red-500';
                if (result.success) {
                    // Refresh the page to show updated progress
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                }
            } catch (error) {
                formMessage.textContent = 'Network error: ' + error.message;
                formMessage.className = 'progress-form-message text-red-500';
            }
        }
    </script>
</body>
</html>