<?php
// edit_batch.php
// Handles the editing of a batch.

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Ensure user is logged in and is an admin or 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';

$batch_id = isset($_GET['batch_id']) ? (int)$_GET['batch_id'] : 0;
$batch = null;
$courses = [];
$instructors = [];
$message = '';
$is_error = false;

// Fetch all courses and instructors for the dropdowns
try {
    $stmt_courses = $pdo->query("SELECT id, course_name FROM courses ORDER BY course_name");
    $courses = $stmt_courses->fetchAll(PDO::FETCH_ASSOC);

    $stmt_instructors = $pdo->query("SELECT id, full_name FROM users WHERE role = 'instructor' ORDER BY full_name");
    $instructors = $stmt_instructors->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $message = "Error fetching courses or instructors: " . $e->getMessage();
    $is_error = true;
}

// Handle form submission for editing the batch
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_batch'])) {
    $batch_id = filter_input(INPUT_POST, 'batch_id', FILTER_VALIDATE_INT);
    $batch_name = filter_input(INPUT_POST, 'batch_name', FILTER_SANITIZE_STRING);
    $course_id = filter_input(INPUT_POST, 'course_id', FILTER_VALIDATE_INT);
    $instructor_id = filter_input(INPUT_POST, 'instructor_id', FILTER_VALIDATE_INT);
    $start_date = filter_input(INPUT_POST, 'start_date', FILTER_SANITIZE_STRING);
    $end_date = filter_input(INPUT_POST, 'end_date', FILTER_SANITIZE_STRING);
    $modality = filter_input(INPUT_POST, 'modality', FILTER_SANITIZE_STRING);
    $fees = filter_input(INPUT_POST, 'fees', FILTER_VALIDATE_FLOAT);
    $duration = filter_input(INPUT_POST, 'duration', FILTER_SANITIZE_STRING);
    $description = filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING);
    
    // Basic validation
    if (!$batch_id || !$batch_name || !$course_id || !$instructor_id || !$start_date || !$end_date || !$fees) {
        $message = "All required fields must be filled.";
        $is_error = true;
    } else {
        try {
            $sql = "UPDATE batches SET batch_name = ?, course_id = ?, instructor_id = ?, start_date = ?, end_date = ?, modality = ?, fees = ?, duration = ?, description = ? WHERE id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$batch_name, $course_id, $instructor_id, $start_date, $end_date, $modality, $fees, $duration, $description, $batch_id]);
            
            $_SESSION['message'] = "Batch updated successfully!";
            $_SESSION['is_error'] = false;
            header("Location: index.php?page=manage_batches");
            exit();

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

// Fetch existing batch data to pre-fill the form
if ($batch_id > 0) {
    try {
        $sql = "SELECT * FROM batches WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$batch_id]);
        $batch = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$batch) {
            $message = "Batch not found.";
            $is_error = true;
        }
    } catch (PDOException $e) {
        $message = "Database error: " . $e->getMessage();
        $is_error = true;
    }
} else {
    $message = "Invalid batch ID.";
    $is_error = true;
}

?>

<div class="w-full max-w-4xl mx-auto p-6 bg-white rounded-lg shadow-xl">
    <h1 class="text-3xl font-bold text-gray-900 mb-6">Edit Batch</h1>

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

    <?php if ($batch): ?>
    <form action="index.php?page=edit_batch" method="POST" class="space-y-6">
        <input type="hidden" name="batch_id" value="<?php echo htmlspecialchars($batch['id']); ?>">
        
        <div>
            <label for="batch_name" class="block text-sm font-medium text-gray-700">Batch Name</label>
            <input type="text" name="batch_name" id="batch_name" required value="<?php echo htmlspecialchars($batch['batch_name']); ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm">
        </div>

        <div>
            <label for="course_id" class="block text-sm font-medium text-gray-700">Course</label>
            <select id="course_id" name="course_id" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm">
                <?php foreach ($courses as $course): ?>
                    <option value="<?php echo htmlspecialchars($course['id']); ?>" <?php echo ($batch['course_id'] == $course['id']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($course['course_name']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div>
            <label for="instructor_id" class="block text-sm font-medium text-gray-700">Instructor</label>
            <select id="instructor_id" name="instructor_id" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm">
                <?php foreach ($instructors as $instructor): ?>
                    <option value="<?php echo htmlspecialchars($instructor['id']); ?>" <?php echo ($batch['instructor_id'] == $instructor['id']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($instructor['full_name']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
                <label for="start_date" class="block text-sm font-medium text-gray-700">Start Date</label>
                <input type="date" name="start_date" id="start_date" required value="<?php echo htmlspecialchars($batch['start_date']); ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm">
            </div>
            <div>
                <label for="end_date" class="block text-sm font-medium text-gray-700">End Date</label>
                <input type="date" name="end_date" id="end_date" required value="<?php echo htmlspecialchars($batch['end_date']); ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm">
            </div>
        </div>

        <div>
            <label for="modality" class="block text-sm font-medium text-gray-700">Modality</label>
            <select id="modality" name="modality" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm">
                <option value="online" <?php echo ($batch['modality'] == 'online') ? 'selected' : ''; ?>>Online</option>
                <option value="physical" <?php echo ($batch['modality'] == 'physical') ? 'selected' : ''; ?>>Physical</option>
            </select>
        </div>

        <div>
            <label for="fees" class="block text-sm font-medium text-gray-700">Fees</label>
            <input type="number" name="fees" id="fees" step="0.01" required value="<?php echo htmlspecialchars($batch['fees']); ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm">
        </div>
        
        <div>
            <label for="duration" class="block text-sm font-medium text-gray-700">Duration</label>
            <input type="text" name="duration" id="duration" value="<?php echo htmlspecialchars($batch['duration']); ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm">
        </div>

        <div>
            <label for="description" class="block text-sm font-medium text-gray-700">Description</label>
            <textarea id="description" name="description" rows="3" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"><?php echo htmlspecialchars($batch['description']); ?></textarea>
        </div>

        <div class="flex justify-end space-x-3">
            <a href="index.php?page=manage_batches" class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                Cancel
            </a>
            <button type="submit" name="update_batch" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                Save Changes
            </button>
        </div>
    </form>
    <?php endif; ?>
</div>