<?php
// create_course.php
// This page allows administrators or instructors to create new courses.
// It now only handles the course name and an image.

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

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header("Location: index.php?page=login");
    exit();
}

require_once 'config/database.php';

$message = '';
$is_error = false;
$course_name = '';

// Handle form submission.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $course_name = trim($_POST['course_name'] ?? '');
    
    // Image Upload Handling
    $image_upload_dir = 'public/uploads/course/';
    $image_file = $_FILES['course_image'] ?? null;
    $image_path = null;

    if (!is_dir($image_upload_dir)) {
        mkdir($image_upload_dir, 0777, true);
    }

    // --- Input Validation ---
    if (empty($course_name)) {
        $message = "Please provide a Course Name.";
        $is_error = true;
    } elseif ($image_file['error'] === UPLOAD_ERR_NO_FILE) {
        $message = "Please select an image for the course.";
        $is_error = true;
    } elseif ($image_file && $image_file['error'] === UPLOAD_ERR_OK) {
        $file_name = uniqid('course_', true) . '.' . pathinfo($image_file['name'], PATHINFO_EXTENSION);
        $destination = $image_upload_dir . $file_name;
        
        if (move_uploaded_file($image_file['tmp_name'], $destination)) {
            $image_path = $destination;
        } else {
            $message = "Error uploading image. Please try again.";
            $is_error = true;
        }
    } else {
        $message = "File upload error: " . $image_file['error'];
        $is_error = true;
    }

    if (!$is_error) {
        try {
            $stmt = $pdo->prepare("INSERT INTO courses (course_name, image_path) VALUES (?, ?)");
            if ($stmt->execute([$course_name, $image_path])) {
                $message = "Course '<strong>" . htmlspecialchars($course_name) . "</strong>' created successfully!";
                $is_error = false;
                // Clear form fields on success.
                $course_name = '';
            } else {
                $message = "Error creating course. Please try again.";
                $is_error = true;
            }
        } catch (PDOException $e) {
            $message = "Database error during course 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</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_course" method="POST" enctype="multipart/form-data" class="space-y-4">
        <div>
            <label for="course_name" class="block text-gray-700 text-sm font-semibold mb-2">Course Name:</label>
            <input type="text" id="course_name" name="course_name" value="<?php echo htmlspecialchars($course_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="course_image" class="block text-gray-700 text-sm font-semibold mb-2">Course Image:</label>
            <input type="file" id="course_image" name="course_image" accept="image/*" required
                   class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
        </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 Course</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>
