<?php
// manage_batch_schedule.php
// This page allows administrators and instructors to view, edit, and delete
// class schedules for a specific batch, with pagination.

// Ensure session is started.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Redirect if not logged in OR not an admin/instructor.
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'instructor')) {
    header("Location: index.php?page=login");
    exit();
}

require_once 'config/database.php';

$message = '';
$is_error = false;
$batch_id = $_GET['batch_id'] ?? null; // Get batch_id from URL
$batch_name = '';
$course_name = '';
$schedules = [];

$current_user_id = $_SESSION['user_id'];
$current_user_role = $_SESSION['user_role'];

// --- Pagination Setup ---
$items_per_page = 10;
$current_page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
if ($current_page < 1) $current_page = 1;
$offset = ($current_page - 1) * $items_per_page;
$total_schedules = 0;
$total_pages = 1;

if (!$batch_id || !is_numeric($batch_id)) {
    $message = "Invalid batch ID provided.";
    $is_error = true;
} else {
    try {
        // Fetch batch and course info
        $stmt_batch = $pdo->prepare("
            SELECT b.id, b.batch_name, b.instructor_id, c.course_name
            FROM batches b
            JOIN courses c ON b.course_id = c.id
            WHERE b.id = ? LIMIT 1
        ");
        $stmt_batch->execute([$batch_id]);
        $batch_info = $stmt_batch->fetch(PDO::FETCH_ASSOC);

        if (!$batch_info) {
            $message = "Batch not found.";
            $is_error = true;
        } else {
            $batch_name = $batch_info['batch_name'];
            $course_name = $batch_info['course_name'];

            // Authorization check: Instructor can only manage their own batches.
            if ($current_user_role === 'instructor' && $batch_info['instructor_id'] != $current_user_id) {
                $message = "You are not authorized to manage schedules for this batch.";
                $is_error = true;
            } else {
                // Count total schedules for pagination
                $stmt_count = $pdo->prepare("SELECT COUNT(*) FROM batch_schedules WHERE batch_id = ?");
                $stmt_count->execute([$batch_id]);
                $total_schedules = $stmt_count->fetchColumn();
                $total_pages = ceil($total_schedules / $items_per_page);

                // Fetch schedules for the batch with pagination, including recording_link
                $stmt_schedules = $pdo->prepare("
                    SELECT
                        id,
                        schedule_date,
                        start_time,
                        end_time,
                        topic,
                        location_or_link,
                        recording_link
                    FROM batch_schedules
                    WHERE batch_id = ?
                    ORDER BY schedule_date ASC, start_time ASC
                    LIMIT ? OFFSET ?
                ");
                $stmt_schedules->bindValue(1, $batch_id, PDO::PARAM_INT);
                $stmt_schedules->bindValue(2, $items_per_page, PDO::PARAM_INT);
                $stmt_schedules->bindValue(3, $offset, PDO::PARAM_INT);
                $stmt_schedules->execute();
                $schedules = $stmt_schedules->fetchAll(PDO::FETCH_ASSOC);

                if (empty($schedules) && $total_schedules > 0) {
                     $message = "No schedules found for this page. Adjust page number.";
                     $is_error = true;
                } elseif (empty($schedules)) {
                    $message = "No schedules have been created for this batch yet.";
                }
            }
        }
    } catch (PDOException $e) {
        $message = "Database error fetching schedules: " . $e->getMessage();
        $is_error = true;
        error_log("Manage Batch Schedule Fetch Error: " . $e->getMessage());
    }
}
?>

<div class="w-full max-w-6xl mx-auto p-6 bg-white rounded-lg shadow-xl">
    <h2 class="text-3xl font-bold mb-2 text-center text-gray-800">
        Manage Batch Schedules
    </h2>
    <h3 class="text-xl font-semibold mb-6 text-center text-blue-700">
        <span class="text-gray-600">Batch:</span> <?php echo htmlspecialchars($batch_name); ?>
        <span class="text-gray-600">| Course:</span> <?php echo htmlspecialchars($course_name); ?>
    </h3>

    <div id="scheduleOverallMessage" class="mb-4 mt-2 text-center text-sm font-semibold"></div>

    <?php if (!empty($message)): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg
            <?php echo $is_error ? 'bg-red-100 text-red-700 border border-red-200' : 'bg-blue-50 text-blue-700 border border-blue-200'; ?>">
            <?php echo $message; ?>
            <p class="mt-4"><a href="index.php?page=admin_dashboard" class="text-blue-600 hover:underline">Back to Admin Dashboard</a></p>
        </div>
    <?php endif; ?>

    <?php if (!$is_error && (!empty($schedules) || $total_schedules > 0)): ?>
        <div class="mb-6 text-right">
            <a href="index.php?page=create_batch_schedule&batch_id=<?php echo htmlspecialchars($batch_id); ?>" class="inline-block px-4 py-2 bg-green-600 text-white font-semibold rounded-md hover:bg-green-700 transition duration-300">
                + Add New Schedule Entry
            </a>
        </div>

        <div class="overflow-x-auto">
            <table class="min-w-full bg-white border-collapse border border-gray-200 rounded-lg overflow-hidden">
                <thead class="bg-gray-100">
                    <tr>
                        <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Date</th>
                        <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Time</th>
                        <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Topic</th>
                        <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Location/Link</th>
                        <th class="py-3 px-4 text-center text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($schedules)): ?>
                        <?php foreach ($schedules as $schedule): ?>
                            <tr class="hover:bg-gray-50 border-b border-gray-200 last:border-b-0" data-schedule-id="<?php echo htmlspecialchars($schedule['id']); ?>">
                                <td class="py-3 px-4 text-sm text-gray-800"><?php echo date('M d, Y', strtotime($schedule['schedule_date'])); ?></td>
                                <td class="py-3 px-4 text-sm text-gray-800"><?php echo date('h:i A', strtotime($schedule['start_time'])) . ' - ' . date('h:i A', strtotime($schedule['end_time'])); ?></td>
                                <td class="py-3 px-4 text-sm text-gray-800"><?php echo htmlspecialchars($schedule['topic'] ?: 'N/A'); ?></td>
                                <td class="py-3 px-4 text-sm text-blue-600 hover:underline">
                                    <a href="<?php echo htmlspecialchars($schedule['location_or_link']); ?>" target="_blank" class="truncate block max-w-[200px]">
                                        <?php echo htmlspecialchars($schedule['location_or_link']); ?>
                                    </a>
                                </td>
                                <td class="py-3 px-4 text-center text-sm">
                                    <button type="button" class="edit-schedule-btn bg-blue-500 text-white px-3 py-1 rounded-md text-xs hover:bg-blue-600 mr-2 transition duration-300"
                                            data-id="<?php echo htmlspecialchars($schedule['id']); ?>"
                                            data-date="<?php echo htmlspecialchars($schedule['schedule_date']); ?>"
                                            data-start-time="<?php echo htmlspecialchars($schedule['start_time']); ?>"
                                            data-end-time="<?php echo htmlspecialchars($schedule['end_time']); ?>"
                                            data-topic="<?php echo htmlspecialchars($schedule['topic']); ?>"
                                            data-location-or-link="<?php echo htmlspecialchars($schedule['location_or_link']); ?>"
                                            data-recording-link="<?php echo htmlspecialchars($schedule['recording_link']); ?>">
                                        Edit
                                    </button>
                                    <button type="button" class="delete-schedule-btn bg-red-500 text-white px-3 py-1 rounded-md text-xs hover:bg-red-600 transition duration-300"
                                            data-id="<?php echo htmlspecialchars($schedule['id']); ?>">
                                        Delete
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="5" class="py-6 px-4 text-center text-gray-500 text-lg">No schedule entries found for this page.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if ($total_pages > 1): ?>
            <div class="mt-8 flex justify-center items-center space-x-2">
                <?php if ($current_page > 1): ?>
                    <a href="index.php?page=manage_batch_schedule&batch_id=<?php echo htmlspecialchars($batch_id); ?>&p=<?php echo $current_page - 1; ?>" class="px-3 py-1 border border-gray-300 rounded-md hover:bg-gray-200">Previous</a>
                <?php else: ?>
                    <span class="px-3 py-1 border border-gray-300 rounded-md text-gray-400 cursor-not-allowed">Previous</span>
                <?php endif; ?>

                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <a href="index.php?page=manage_batch_schedule&batch_id=<?php echo htmlspecialchars($batch_id); ?>&p=<?php echo $i; ?>" class="px-3 py-1 border border-gray-300 rounded-md <?php echo ($i === $current_page) ? 'bg-blue-600 text-white' : 'hover:bg-gray-200'; ?>">
                        <?php echo $i; ?>
                    </a>
                <?php endfor; ?>

                <?php if ($current_page < $total_pages): ?>
                    <a href="index.php?page=manage_batch_schedule&batch_id=<?php echo htmlspecialchars($batch_id); ?>&p=<?php echo $current_page + 1; ?>" class="px-3 py-1 border border-gray-300 rounded-md hover:bg-gray-200">Next</a>
                <?php else: ?>
                    <span class="px-3 py-1 border border-gray-300 rounded-md text-gray-400 cursor-not-allowed">Next</span>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    <?php elseif (!$is_error): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg bg-blue-50 text-blue-700 border border-blue-200">
            No schedules have been created for this batch yet.
            <p class="mt-4">
                <a href="index.php?page=create_batch_schedule&batch_id=<?php echo htmlspecialchars($batch_id); ?>" class="inline-block px-4 py-2 bg-green-600 text-white font-semibold rounded-md hover:bg-green-700 transition duration-300">
                    Add First Schedule Entry
                </a>
            </p>
        </div>
    <?php endif; ?>

    <div class="mt-8 text-center">
        <a href="index.php?page=admin_dashboard" class="px-6 py-3 bg-gray-200 text-gray-700 font-semibold rounded-md hover:bg-gray-300 transition duration-300">
            Back to Admin Dashboard
        </a>
    </div>
</div>

<div id="editScheduleModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center hidden">
    <div class="bg-white p-6 rounded-lg shadow-xl w-full max-w-md">
        <h3 class="text-xl font-bold mb-4">Edit Schedule Entry</h3>
        <form id="editScheduleForm" class="space-y-4">
            <input type="hidden" id="edit_schedule_id" name="id">
            <input type="hidden" name="batch_id" value="<?php echo htmlspecialchars($batch_id); ?>">

            <div>
                <label for="edit_schedule_date" class="block text-gray-700 text-sm font-semibold mb-2">Class Date:</label>
                <input type="date" id="edit_schedule_date" name="schedule_date" required
                        class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label for="edit_start_time" class="block text-gray-700 text-sm font-semibold mb-2">Start Time:</label>
                    <input type="time" id="edit_start_time" name="start_time" required
                            class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                <div>
                    <label for="edit_end_time" class="block text-gray-700 text-sm font-semibold mb-2">End Time:</label>
                    <input type="time" id="edit_end_time" name="end_time" required
                            class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
            </div>

            <div>
                <label for="edit_topic" class="block text-gray-700 text-sm font-semibold mb-2">Topic:</label>
                <input type="text" id="edit_topic" name="topic" required
                        class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label for="edit_location_or_link" class="block text-gray-700 text-sm font-semibold mb-2">Live Class Link:</label>
                <input type="url" id="edit_location_or_link" name="location_or_link" required
                        class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label for="edit_recording_link" class="block text-gray-700 text-sm font-semibold mb-2">Recording Link:</label>
                <input type="url" id="edit_recording_link" name="recording_link"
                        class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                        placeholder="Optional">
            </div>

            <div class="flex justify-end space-x-3">
                <button type="button" id="cancelEdit" class="px-4 py-2 bg-gray-300 text-gray-800 rounded-md hover:bg-gray-400">Cancel</button>
                <button type="submit" id="saveEdit" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">Save Changes</button>
            </div>
        </form>
        <div id="editScheduleMessage" class="mt-4 text-center text-sm font-semibold"></div>
    </div>
</div>


<script>
    document.addEventListener('DOMContentLoaded', function() {
        const editScheduleModal = document.getElementById('editScheduleModal');
        const editScheduleForm = document.getElementById('editScheduleForm');
        const editScheduleMessageDiv = document.getElementById('editScheduleMessage');
        const cancelEditButton = document.getElementById('cancelEdit');
        const saveEditButton = document.getElementById('saveEdit');
        const scheduleOverallMessageDiv = document.getElementById('scheduleOverallMessage');

        // Select the parent div of each field
        const editDateDiv = document.querySelector('label[for="edit_schedule_date"]').parentElement;
        const editTimeDiv = document.querySelector('.grid.grid-cols-2.gap-4');
        const editTopicDiv = document.querySelector('label[for="edit_topic"]').parentElement;
        const editLiveLinkDiv = document.querySelector('label[for="edit_location_or_link"]').parentElement;
        const editRecordingLinkDiv = document.querySelector('label[for="edit_recording_link"]').parentElement;

        // Function to display overall messages
        function displayOverallMessage(message, isError = false) {
            scheduleOverallMessageDiv.textContent = message;
            scheduleOverallMessageDiv.className = 'mb-4 mt-2 p-2 rounded-md text-center text-sm font-semibold';
            if (isError) {
                scheduleOverallMessageDiv.classList.add('bg-red-100', 'text-red-700', 'border', 'border-red-200');
            } else {
                scheduleOverallMessageDiv.classList.add('bg-green-100', 'text-green-700', 'border', 'border-green-200');
            }
        }
        
        // Clear overall message when any modal opens
        function clearOverallMessage() {
            scheduleOverallMessageDiv.textContent = '';
            scheduleOverallMessageDiv.className = 'mb-4 mt-2 text-center text-sm font-semibold';
        }

        // Show Edit Modal
        document.querySelectorAll('.edit-schedule-btn').forEach(button => {
            button.addEventListener('click', function() {
                clearOverallMessage();
                
                const scheduleDateStr = this.dataset.date;
                const scheduleDate = new Date(scheduleDateStr);
                const today = new Date();
                // Set today's date to midnight for accurate date-only comparison
                today.setHours(0, 0, 0, 0); 
                
                document.getElementById('edit_schedule_id').value = this.dataset.id;
                document.getElementById('edit_schedule_date').value = scheduleDateStr;
                document.getElementById('edit_start_time').value = this.dataset.startTime;
                document.getElementById('edit_end_time').value = this.dataset.endTime;
                document.getElementById('edit_topic').value = this.dataset.topic;
                document.getElementById('edit_location_or_link').value = this.dataset.locationOrLink;
                document.getElementById('edit_recording_link').value = this.dataset.recordingLink;
                
                // New conditional logic
                if (scheduleDate < today) {
                    // Date has passed, show only the recording link field and add a user message
                    editDateDiv.classList.add('hidden');
                    editTimeDiv.classList.add('hidden');
                    editTopicDiv.classList.add('hidden');
                    editLiveLinkDiv.classList.add('hidden'); // Hide live link for past classes
                    editRecordingLinkDiv.classList.remove('hidden'); // Ensure recording link is shown
                    
                    editScheduleMessageDiv.innerHTML = '<span class="text-blue-600">This class has already occurred. You can only update the recording link.</span>';

                    // Set the recording link field to not be required
                    document.getElementById('edit_recording_link').required = false;
                } else {
                    // Date is today or in the future, show all fields
                    editDateDiv.classList.remove('hidden');
                    editTimeDiv.classList.remove('hidden');
                    editTopicDiv.classList.remove('hidden');
                    editLiveLinkDiv.classList.remove('hidden'); // Show live link for future classes
                    editRecordingLinkDiv.classList.remove('hidden'); // Also show recording link
                    
                    editScheduleMessageDiv.textContent = ''; // Clear message
                    
                    // Set the live link field to be required again
                    document.getElementById('edit_location_or_link').required = true;
                }

                editScheduleModal.classList.remove('hidden');
            });
        });

        // Close Edit Modal
        if (cancelEditButton) {
            cancelEditButton.addEventListener('click', function() {
                editScheduleModal.classList.add('hidden');
            });
        }

        // Handle Edit Form Submission
        if (editScheduleForm) {
            editScheduleForm.addEventListener('submit', async function(event) {
                event.preventDefault();
                saveEditButton.disabled = true;
                editScheduleMessageDiv.innerHTML = '<span class="text-blue-600">Saving changes...</span>';

                const formData = new FormData(this);
                const scheduleData = {};
                
                // Loop through all form elements to get their values
                for (let [key, value] of formData.entries()) {
                    // Only include non-empty values in the data sent to the API
                    if (value !== '') {
                        scheduleData[key] = value;
                    }
                }
                
                // Ensure required fields for the API are always sent, even if empty, to be safe.
                scheduleData['id'] = document.getElementById('edit_schedule_id').value;
                scheduleData['batch_id'] = this.querySelector('input[name="batch_id"]').value;

                try {
                    const response = await fetch('api/update_batch_schedule.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(scheduleData)
                    });

                    const data = await response.json();

                    if (data.success) {
                        editScheduleMessageDiv.innerHTML = '<span class="text-green-600">' + data.message + ' Reloading...</span>';
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    } else {
                        editScheduleMessageDiv.innerHTML = '<span class="text-red-600">' + (data.message || 'Failed to update schedule.') + '</span>';
                    }
                } catch (error) {
                    console.error('Error updating schedule:', error);
                    editScheduleMessageDiv.innerHTML = '<span class="text-red-600">Network error or server issue.</span>';
                } finally {
                    saveEditButton.disabled = false;
                }
            });
        }

        // Handle Delete Button Click
        document.querySelectorAll('.delete-schedule-btn').forEach(button => {
            button.addEventListener('click', function() {
                const scheduleId = this.dataset.id;
                if (confirm('Are you sure you want to delete this schedule entry? This action cannot be undone.')) {
                    deleteSchedule(scheduleId);
                }
            });
        });

        async function deleteSchedule(scheduleId) {
            const row = document.querySelector(`tr[data-schedule-id="${scheduleId}"]`);
            if (row) {
                row.style.opacity = '0.5';
            }
            displayOverallMessage('Deleting schedule...', false);

            try {
                const response = await fetch('api/delete_batch_schedule.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ id: scheduleId })
                });

                const data = await response.json();

                if (data.success) {
                    displayOverallMessage(data.message + ' Reloading...', false);
                    if (row) {
                        row.remove();
                    }
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    displayOverallMessage((data.message || 'Failed to delete schedule.'), true);
                    if (row) {
                        row.style.opacity = '1';
                    }
                }
            } catch (error) {
                console.error('Error deleting schedule:', error);
                displayOverallMessage('Network error or server issue during deletion.', true);
                if (row) {
                    row.style.opacity = '1';
                }
            }
        }
    });
</script>