<?php
// Set PHP timezone to Europe/London (handles BST automatically)
date_default_timezone_set('Europe/London');

// Default user_id for testing
$user_id = 1;

// Initialize Google Calendar API
require 'vendor/autoload.php';
session_start();

$client = new Google_Client();
$client->setAuthConfig('/home/dave/secure/client_credentials.json');

$calendar_events = [];
$calendar_error = null;
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
    $client->setAccessToken($_SESSION['access_token']);
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        $_SESSION['access_token'] = $client->getAccessToken();
    }
    $service = new Google_Service_Calendar($client);

    // Fetch calendar colors
    $colors = $service->colors->get();
    $eventColors = $colors->getEvent();

    // Determine the selected date (default to current date)
    $selected_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

    // Fetch events from RMGT calendar for the selected date
    $calendarId = 'd5284d59cf8afa5a911d14a4b670f0f63a0b031de0003b9807aafea0d90bd1bf@group.calendar.google.com';
    $timeMin = $selected_date . 'T00:00:00Z';
    $timeMax = $selected_date . 'T23:59:59Z';
    $optParams = [
        'maxResults' => 100,
        'orderBy' => 'startTime',
        'singleEvents' => true,
        'timeMin' => $timeMin,
        'timeMax' => $timeMax,
    ];
    try {
        $results = $service->events->listEvents($calendarId, $optParams);
        foreach ($results->getItems() as $event) {
            $calendar_events[] = [
                'id' => $event->getId(),
                'summary' => $event->getSummary(),
                'start' => $event->start->dateTime ?: $event->start->date,
                'colorId' => $event->getColorId(),
                'backgroundColor' => $event->getColorId() && isset($eventColors[$event->getColorId()]) ? $eventColors[$event->getColorId()]->getBackground() : '#787878',
            ];
        }
        // Sort events by start time
        usort($calendar_events, function($a, $b) {
            return strtotime($a['start']) <=> strtotime($b['start']);
        });
    } catch (Exception $e) {
        $calendar_error = "Calendar Error: " . $e->getMessage();
    }
} else {
    $calendar_error = "Not authenticated with Google Calendar. <a href='auth.php'>Connect to Google Calendar</a>";
}

// 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');
$students = [];
$students_error = null;
if ($rmgt_conn->connect_error) {
    $students_error = 'Database connection failed: ' . $rmgt_conn->connect_error;
} elseif (empty($calendar_events)) {
    $students_error = 'No events found in RMGT calendar for this day.';
} else {
    // Fetch students matching calendar event summaries, including rate
    $event_summaries = array_map(function($event) {
        // Remove "(paid)" from summary for matching
        return preg_replace('/\s*\(paid\)$/i', '', trim($event['summary']));
    }, $calendar_events);
    $placeholders = implode(',', array_fill(0, count($event_summaries), '?'));
    $query = "
        SELECT s.student_id, s.forename, s.surname, s.calendar_name, s.rate, 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.calendar_name IN ($placeholders)
    ";
    $stmt = $rmgt_conn->prepare($query);
    $types = str_repeat('s', count($event_summaries));
    $stmt->bind_param($types, ...$event_summaries);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result === false) {
        $students_error = 'Error fetching students: ' . $rmgt_conn->error;
    } else {
        $students = $result->fetch_all(MYSQLI_ASSOC);
        $students_error = empty($students) ? 'No matching students found for calendar events.' : null;
    }
    $stmt->close();
    $rmgt_conn->close();
}

// Check if a form should be reopened after refresh
$reopen_form_id = isset($_GET['reopen_form']) ? (int)$_GET['reopen_form'] : null;
?>
<!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 button.receipt {
            background: #10B981;
            color: white;
        }
        .progress-form button.receipt:hover {
            background: #059669;
        }
        .progress-form button.receipt-ca {
            background: #F59E0B;
            color: white;
        }
        .progress-form button.receipt-ca:hover {
            background: #D97706;
        }
        .progress-form button:disabled {
            background: #A0AEC0;
            cursor: not-allowed;
        }
        .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;
        }
        .event-color {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 8px;
        }
        .student-calendar {
            color: #4B5563;
            font-size: 0.9rem;
            margin-top: 0.25rem;
        }
        @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">
                <?php if (isset($calendar_error)): ?>
                    <p class="text-red-500"><?php echo $calendar_error; ?></p>
                <?php endif; ?>
                <ul>
                    <?php if (isset($students_error)): ?>
                        <li><span class="text-red-500"><?php echo htmlspecialchars($students_error); ?></span></li>
                    <?php else: ?>
                        <?php foreach ($calendar_events as $event): ?>
                            <?php
                            // Find matching student by calendar_name, ignoring "(paid)"
                            $calendar_name = preg_replace('/\s*\(paid\)$/i', '', trim($event['summary']));
                            $student = null;
                            foreach ($students as $s) {
                                if ($s['calendar_name'] === $calendar_name) {
                                    $student = $s;
                                    break;
                                }
                            }
                            if (!$student) continue; // Skip if no matching student
                            // Set dot color to green for "(paid)" events
                            $dot_color = stripos($event['summary'], '(paid)') !== false ? '#00FF00' : $event['backgroundColor'];
                            // Get event date for payment_date
                            $payment_date = date('Y-m-d', strtotime($event['start']));
                            $form_open = $reopen_form_id === $student['student_id'] ? 'block' : 'none';
                            ?>
                            <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 date('H:i', strtotime($event['start'])); ?></span>
                                    </div>
                                    <div class="student-calendar">
                                        <span class="event-color" style="background-color: <?php echo htmlspecialchars($dot_color); ?>;"></span>
                                        Calendar: <?php echo htmlspecialchars($event['summary']); ?>
                                    </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']; ?>)" style="display: <?php echo $form_open; ?>;">
                                    <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>
                                        <button type="button" class="receipt" id="receipt-button-<?php echo $student['student_id']; ?>" onclick="addReceipt(<?php echo $student['student_id']; ?>, '<?php echo $payment_date; ?>', <?php echo $student['rate'] ?: '0'; ?>, '<?php echo $event['id']; ?>', <?php echo $student['student_id']; ?>, '<?php echo addslashes($calendar_name); ?>')">Receipt</button>
                                        <button type="button" class="receipt-ca" id="receipt-ca-button-<?php echo $student['student_id']; ?>" onclick="addReceiptCA(<?php echo $student['student_id']; ?>, '<?php echo $payment_date; ?>', <?php echo $student['rate'] ?: '0'; ?>, '<?php echo $event['id']; ?>', <?php echo $student['student_id']; ?>, '<?php echo addslashes($calendar_name); ?>')">Receipt CA</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) {
                    setTimeout(() => {
                        window.location.href = window.location.pathname + '?date=' + document.getElementById('date-picker').value + '&reopen_form=' + studentId;
                    }, 1000);
                }
            } catch (error) {
                formMessage.textContent = 'Network error: ' + error.message;
                formMessage.className = 'progress-form-message text-red-500';
            }
        }

        // Add receipt and update calendar event
        async function addReceipt(studentId, paymentDate, amount, eventId, messageId, calendarName) {
            const formMessage = document.getElementById('progress-message-' + messageId);
            const receiptButton = document.getElementById('receipt-button-' + studentId);

            // Show loading state
            receiptButton.disabled = true;
            formMessage.textContent = 'Processing...';
            formMessage.className = 'progress-form-message';

            // Step 1: Add receipt
            const receiptData = new FormData();
            receiptData.append('student_id', studentId);
            receiptData.append('payment_date', paymentDate);
            receiptData.append('amount', amount);
            receiptData.append('action', 'receipt');

            try {
                console.log('Adding receipt for student:', studentId, 'on date:', paymentDate);
                const receiptResponse = await fetch('insert_payment.php', {
                    method: 'POST',
                    body: receiptData
                });
                const receiptResult = await receiptResponse.json();
                if (!receiptResult.success) {
                    formMessage.textContent = receiptResult.error || 'Failed to add receipt';
                    formMessage.className = 'progress-form-message text-red-500';
                    receiptButton.disabled = false;
                    return;
                }

                // Step 2: Update calendar event to append "(paid)"
                const updateData = new FormData();
                updateData.append('event_id', eventId);
                updateData.append('calendar_id', 'd5284d59cf8afa5a911d14a4b670f0f63a0b031de0003b9807aafea0d90bd1bf@group.calendar.google.com');
                updateData.append('summary', calendarName + ' (paid)');

                console.log('Updating calendar event:', eventId, 'with summary:', calendarName + ' (paid)');
                const updateResponse = await fetch('update_calendar_event.php', {
                    method: 'POST',
                    body: updateData
                });
                const updateResult = await updateResponse.json();
                if (updateResult.success) {
                    formMessage.textContent = 'Receipt added and calendar updated successfully';
                    formMessage.className = 'progress-form-message text-green-500';
                    setTimeout(() => {
                        window.location.href = window.location.pathname + '?date=' + document.getElementById('date-picker').value + '&reopen_form=' + studentId;
                    }, 1000);
                } else {
                    formMessage.textContent = updateResult.error || 'Failed to update calendar event';
                    formMessage.className = 'progress-form-message text-red-500';
                    receiptButton.disabled = false;
                }
            } catch (error) {
                formMessage.textContent = 'Network error: ' + error.message;
                formMessage.className = 'progress-form-message text-red-500';
                receiptButton.disabled = false;
                console.error('Error in addReceipt:', error);
            }
        }

        // Add receipt (current account) and update calendar event
        async function addReceiptCA(studentId, paymentDate, amount, eventId, messageId, calendarName) {
            const formMessage = document.getElementById('progress-message-' + messageId);
            const receiptCAButton = document.getElementById('receipt-ca-button-' + studentId);

            // Show loading state
            receiptCAButton.disabled = true;
            formMessage.textContent = 'Processing...';
            formMessage.className = 'progress-form-message';

            // Step 1: Add receipt (current account)
            const receiptData = new FormData();
            receiptData.append('student_id', studentId);
            receiptData.append('payment_date', paymentDate);
            receiptData.append('amount', amount);
            receiptData.append('action', 'receipt_ca');

            try {
                console.log('Adding receipt CA for student:', studentId, 'on date:', paymentDate);
                const receiptResponse = await fetch('insert_payment_ca.php', {
                    method: 'POST',
                    body: receiptData
                });
                const receiptResult = await receiptResponse.json();
                if (!receiptResult.success) {
                    formMessage.textContent = receiptResult.error || 'Failed to add receipt CA';
                    formMessage.className = 'progress-form-message text-red-500';
                    receiptCAButton.disabled = false;
                    return;
                }

                // Step 2: Update calendar event to append "(paid)"
                const updateData = new FormData();
                updateData.append('event_id', eventId);
                updateData.append('calendar_id', 'd5284d59cf8afa5a911d14a4b670f0f63a0b031de0003b9807aafea0d90bd1bf@group.calendar.google.com');
                updateData.append('summary', calendarName + ' (paid)');

                console.log('Updating calendar event:', eventId, 'with summary:', calendarName + ' (paid)');
                const updateResponse = await fetch('update_calendar_event.php', {
                    method: 'POST',
                    body: updateData
                });
                const updateResult = await updateResponse.json();
                if (updateResult.success) {
                    formMessage.textContent = 'Receipt CA added and calendar updated successfully';
                    formMessage.className = 'progress-form-message text-green-500';
                    setTimeout(() => {
                        window.location.href = window.location.pathname + '?date=' + document.getElementById('date-picker').value + '&reopen_form=' + studentId;
                    }, 1000);
                } else {
                    formMessage.textContent = updateResult.error || 'Failed to update calendar event';
                    formMessage.className = 'progress-form-message text-red-500';
                    receiptCAButton.disabled = false;
                }
            } catch (error) {
                formMessage.textContent = 'Network error: ' + error.message;
                formMessage.className = 'progress-form-message text-red-500';
                receiptCAButton.disabled = false;
                console.error('Error in addReceiptCA:', error);
            }
        }

        // Reopen form if specified in URL
        window.onload = function() {
            const reopenFormId = <?php echo json_encode($reopen_form_id); ?>;
            if (reopenFormId) {
                toggleProgressForm(reopenFormId);
            }
        };
    </script>
</body>
</html>