<?php
// create_batch_schedule.php
// This page allows an administrator or instructor to add a new schedule entry for a specific batch.

// Ensure session is started for user authentication and messages.
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();
}

// Include database connection.
require_once 'config/database.php';

$message = '';
$is_error = false;
$batch_id = $_GET['batch_id'] ?? null;
$batch = null;

// Ensure a batch ID is provided in the URL.
if (!$batch_id) {
    $message = "Error: No batch selected to create a schedule for.";
    $is_error = true;
} else {
    try {
        // Fetch batch and course details for display and validation.
        $stmt = $pdo->prepare("
            SELECT
                b.id,
                b.batch_name,
                c.course_name,
                b.modality,
                b.instructor_id
            FROM batches b
            JOIN courses c ON b.course_id = c.id
            WHERE b.id = ?
        ");
        $stmt->execute([$batch_id]);
        $batch = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$batch) {
            $message = "Error: The selected batch does not exist.";
            $is_error = true;
        } elseif ($_SESSION['user_role'] === 'instructor' && $batch['instructor_id'] != $_SESSION['user_id']) {
            $message = "You do not have permission to manage this batch.";
            $is_error = true;
        }

    } catch (PDOException $e) {
        $message = "Database error: " . $e->getMessage();
        $is_error = true;
    }
}
?>

<div class="bg-white p-8 rounded-lg shadow-md w-full max-w-2xl">
    <h2 class="text-2xl font-bold mb-2 text-center text-gray-800">Create Schedule for Batch</h2>
    
    <?php if ($batch): ?>
        <h3 class="text-xl font-semibold text-center text-blue-600 mb-6"><?php echo htmlspecialchars($batch['batch_name']); ?> - <?php echo htmlspecialchars($batch['course_name']); ?></h3>
    <?php endif; ?>

    <div id="status-message" class="hidden mb-4 p-3 rounded-md text-center"></div>

    <?php if ($batch && !$is_error): ?>
        <form id="schedule-form" method="POST" class="space-y-4">
            <input type="hidden" name="batch_id" value="<?php echo htmlspecialchars($batch_id); ?>">
            <div>
                <label for="schedule_date" class="block text-gray-700 text-sm font-semibold mb-2">Class Date:</label>
                <input type="date" id="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>
                <label for="start_time" class="block text-gray-700 text-sm font-semibold mb-2">Start Time:</label>
                <input type="time" id="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="end_time" class="block text-gray-700 text-sm font-semibold mb-2">End Time:</label>
                <input type="time" id="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>
                <label for="topic" class="block text-gray-700 text-sm font-semibold mb-2">Topic/Description:</label>
                <input type="text" id="topic" name="topic" placeholder="e.g., Introduction to PHP" 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="location_or_link" class="block text-gray-700 text-sm font-semibold mb-2">Location/Online Link:</label>
                <input type="text" id="location_or_link" name="location_or_link" placeholder="<?php echo $batch['modality'] === 'online' ? 'e.g., Google Meet link' : 'e.g., Room 101, Building B'; ?>" 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>
            
            <button type="submit" id="submit-btn"
                    class="w-full py-2 px-4 bg-blue-600 text-white font-semibold rounded-md hover:bg-blue-700 transition duration-300">
                Add to Schedule
            </button>
        </form>

        <div id="loading-spinner" class="hidden text-center mt-6">
            <div class="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-current border-r-transparent align-[-0.125em] text-blue-500" role="status">
                <span class="!absolute !-m-px !h-px !w-px !overflow-hidden !whitespace-nowrap !border-0 !p-0 ![clip:rect(0,0,0,0)]">Loading...</span>
            </div>
            <p class="mt-2 text-gray-600">Creating schedule and notifying students. This may take a moment...</p>
        </div>

        <p class="mt-6 text-center text-gray-600">
            <a href="index.php?page=admin_dashboard" class="text-blue-600 hover:underline">Back to Dashboard</a>
        </p>
    <?php else: ?>
        <div class="p-4 rounded-md text-center text-lg bg-red-100 text-red-700 border border-red-200">
            Cannot display form due to an error. Please return to the dashboard and try again.
            <p class="mt-4"><a href="index.php?page=admin_dashboard" class="text-blue-600 hover:underline font-semibold">Back to Dashboard</a></p>
        </div>
    <?php endif; ?>
</div>

<script>
document.getElementById('schedule-form').addEventListener('submit', function(event) {
    event.preventDefault(); // Prevent the default form submission

    const form = event.target;
    const formData = new FormData(form);
    const submitBtn = document.getElementById('submit-btn');
    const loadingSpinner = document.getElementById('loading-spinner');
    const statusMessage = document.getElementById('status-message');

    // Show loading spinner and disable button
    submitBtn.disabled = true;
    submitBtn.classList.add('opacity-50', 'cursor-not-allowed');
    loadingSpinner.classList.remove('hidden');
    statusMessage.classList.add('hidden'); // Hide previous messages

    fetch('api/create_schedule_api.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        // Handle the response from the API
        loadingSpinner.classList.add('hidden');
        submitBtn.disabled = false;
        submitBtn.classList.remove('opacity-50', 'cursor-not-allowed');
        
        statusMessage.classList.remove('hidden');
        if (data.success) {
            statusMessage.classList.remove('bg-red-100', 'text-red-700');
            statusMessage.classList.add('bg-green-100', 'text-green-700');
            form.reset(); // Clear the form on success
        } else {
            statusMessage.classList.remove('bg-green-100', 'text-green-700');
            statusMessage.classList.add('bg-red-100', 'text-red-700');
        }
        statusMessage.innerHTML = data.message;
    })
    .catch(error => {
        loadingSpinner.classList.add('hidden');
        submitBtn.disabled = false;
        submitBtn.classList.remove('opacity-50', 'cursor-not-allowed');
        
        statusMessage.classList.remove('hidden');
        statusMessage.classList.remove('bg-green-100', 'text-green-700');
        statusMessage.classList.add('bg-red-100', 'text-red-700');
        statusMessage.innerHTML = 'An unexpected error occurred. Please try again.';
        console.error('Error:', error);
    });
});
</script>