<?php
// create_batch.php
// This page allows administrators or instructors to create new batches for existing courses.

// Ensure session is started for user authentication and messages.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Redirect if not logged in (basic access control)
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header("Location: index.php?page=login");
    exit();
}

// Optional: Further restrict access to only 'admin' or 'instructor' roles
// if ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'instructor') {
//     header("Location: index.php?page=dashboard"); // Redirect unauthorized users
//     exit();
// }

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

$message = ''; // Message for success or error feedback.
$is_error = false; // Flag for message styling.

// Initialize form fields for sticky form behavior.
$selected_course_id = '';
$batch_name = '';
$start_date = '';
$end_date = '';
$selected_instructor_id = '';
$modality = '';
$fees = ''; // New field
$duration = ''; // New field
$description = ''; // New field

$instructors = [];
$courses = [];

try {
    // Fetch all courses to populate the dropdown.
    $stmt = $pdo->prepare("SELECT id, course_name FROM courses ORDER BY course_name ASC");
    $stmt->execute();
    $courses = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Fetch users with the 'instructor' role to populate the dropdown.
    $stmt = $pdo->prepare("SELECT id, full_name, username FROM users WHERE role = 'instructor' ORDER BY full_name ASC");
    $stmt->execute();
    $instructors = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

// Handle form submission.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $selected_course_id = trim($_POST['course_id'] ?? '');
    $batch_name = trim($_POST['batch_name'] ?? '');
    $start_date = trim($_POST['start_date'] ?? '');
    $end_date = trim($_POST['end_date'] ?? '');
    $selected_instructor_id = trim($_POST['instructor_id'] ?? '');
    $modality = trim($_POST['modality'] ?? '');
    $fees = trim($_POST['fees'] ?? ''); // Fetch new field
    $duration = trim($_POST['duration'] ?? ''); // Fetch new field
    $description = trim($_POST['description'] ?? ''); // Fetch new field

    // --- Input Validation ---
    if (empty($selected_course_id) || empty($batch_name) || empty($start_date) || empty($selected_instructor_id) || empty($modality) || empty($fees) || empty($duration)) {
        $message = "Please fill in all required fields.";
        $is_error = true;
    } elseif (!is_numeric($selected_course_id) || $selected_course_id <= 0) {
        $message = "Invalid course selected.";
        $is_error = true;
    } elseif (!is_numeric($selected_instructor_id) || $selected_instructor_id <= 0) {
        $message = "Invalid instructor selected.";
        $is_error = true;
    } elseif (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $start_date) || !strtotime($start_date)) {
        $message = "Start Date must be in YYYY-MM-DD format and a valid date.";
        $is_error = true;
    } elseif (!empty($end_date) && (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $end_date) || !strtotime($end_date))) {
        $message = "End Date must be in YYYY-MM-DD format or be empty.";
        $is_error = true;
    } elseif (!empty($end_date) && strtotime($end_date) < strtotime($start_date)) {
        $message = "End Date cannot be before Start Date.";
        $is_error = true;
    } elseif (!is_numeric($fees) || $fees < 0) { // New validation for fees
        $message = "Fees must be a positive number.";
        $is_error = true;
    } else {
        // --- Insert Batch into Database ---
        try {
            // Updated SQL query to include the new columns
            $stmt = $pdo->prepare("INSERT INTO batches (course_id, batch_name, instructor_id, start_date, end_date, modality, fees, duration, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
            
            // Updated execute array to include the new values
            if ($stmt->execute([$selected_course_id, $batch_name, $selected_instructor_id, $start_date, $end_date, $modality, $fees, $duration, $description])) {
                $message = "Batch '<strong>" . htmlspecialchars($batch_name) . "</strong>' created successfully!";
                $is_error = false;
                // Clear form fields on success.
                $selected_course_id = '';
                $batch_name = '';
                $start_date = '';
                $end_date = '';
                $selected_instructor_id = '';
                $modality = '';
                $fees = ''; 
                $duration = '';
                $description = '';
            } else {
                $message = "Error creating batch. Please try again.";
                $is_error = true;
            }
        } catch (PDOException $e) {
            $message = "Database error during batch creation: " . $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-6 text-center text-gray-800">Create New Course Batch</h2>

    <?php if (!empty($message)): ?>
        <div class="mb-4 p-3 rounded-md text-center
            <?php echo $is_error ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'; ?>">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <form action="index.php?page=create_batch" method="POST" class="space-y-4">
        <div>
            <label for="course_id" class="block text-gray-700 text-sm font-semibold mb-2">Select Course:</label>
            <select id="course_id" name="course_id" required
                    class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option value="">-- Select a Course --</option>
                <?php foreach ($courses as $course): ?>
                    <option value="<?php echo htmlspecialchars($course['id']); ?>"
                        <?php echo ($selected_course_id == $course['id']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($course['course_name']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <?php if (empty($courses) && !$is_error): ?>
                <p class="text-sm text-red-500 mt-1">No courses available. Please create a course first.</p>
            <?php endif; ?>
        </div>

        <div>
            <label for="batch_name" class="block text-gray-700 text-sm font-semibold mb-2">Batch Name (e.g., "Spring 2025 Online"):</label>
            <input type="text" id="batch_name" name="batch_name" value="<?php echo htmlspecialchars($batch_name); ?>" 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_date" class="block text-gray-700 text-sm font-semibold mb-2">Start Date:</label>
            <input type="date" id="start_date" name="start_date" value="<?php echo htmlspecialchars($start_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="end_date" class="block text-gray-700 text-sm font-semibold mb-2">End Date (Optional):</label>
            <input type="date" id="end_date" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>"
                   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="fees" class="block text-gray-700 text-sm font-semibold mb-2">Course Fees (e.g., 500.00):</label>
            <input type="number" step="0.01" id="fees" name="fees" value="<?php echo htmlspecialchars($fees); ?>" 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="duration" class="block text-gray-700 text-sm font-semibold mb-2">Course Duration (e.g., "3 months"):</label>
            <input type="text" id="duration" name="duration" value="<?php echo htmlspecialchars($duration); ?>" 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="description" class="block text-gray-700 text-sm font-semibold mb-2">Description (Optional):</label>
            <textarea id="description" name="description" rows="4"
                      class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"><?php echo htmlspecialchars($description); ?></textarea>
        </div>

        <div>
            <label for="instructor_id" class="block text-gray-700 text-sm font-semibold mb-2">Assign Instructor:</label>
            <select id="instructor_id" name="instructor_id" required
                    class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option value="">-- Select an Instructor --</option>
                <?php foreach ($instructors as $instructor): ?>
                    <option value="<?php echo htmlspecialchars($instructor['id']); ?>"
                        <?php echo ($selected_instructor_id == $instructor['id']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($instructor['full_name'] ?: $instructor['username']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <?php if (empty($instructors) && !$is_error): ?>
                <p class="text-sm text-red-500 mt-1">No instructors available. Please register one first.</p>
            <?php endif; ?>
        </div>

        <div>
            <label for="modality" class="block text-gray-700 text-sm font-semibold mb-2">Modality:</label>
            <div class="flex items-center space-x-4">
                <label class="inline-flex items-center">
                    <input type="radio" name="modality" value="online" class="form-radio text-blue-600" <?php echo ($modality == 'online' || $modality == '') ? 'checked' : ''; ?>>
                    <span class="ml-2 text-gray-700">Online</span>
                </label>
                <label class="inline-flex items-center">
                    <input type="radio" name="modality" value="physical" class="form-radio text-blue-600" <?php echo ($modality == 'physical') ? 'checked' : ''; ?>>
                    <span class="ml-2 text-gray-700">Physical</span>
                </label>
            </div>
        </div>

        <button type="submit"
                class="w-full py-2 px-4 bg-blue-600 text-white font-semibold rounded-md hover:bg-blue-700 transition duration-300">Create Batch</button>
    </form>

    <p class="mt-6 text-center text-gray-600">
        <a href="index.php?page=dashboard" class="text-blue-600 hover:underline">Back to Dashboard</a>
    </p>
</div>