<?php
// admin_dashboard.php
// This is the dedicated dashboard view for Administrators and Instructors, now using the simplified course grid.

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

// Ensure the user is logged in AND is either 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'; // Include database connection

$username = $_SESSION['username'] ?? 'Admin/Instructor';
$user_role = $_SESSION['user_role'] ?? 'guest';
$user_id = $_SESSION['user_id'] ?? null;

$total_pending_enrollments = 0;
$total_students = 0;
$total_batches = 0;
$total_courses = 0;
$courses = []; // To store available courses

$message = '';
$is_error = false;

try {
    // --- Optimized: Fetch all dashboard stats in one go ---
    // (Stat fetching logic is kept for the dashboard overview cards)
    $sql_stats = "
        SELECT 
            (SELECT COUNT(ce.id) FROM course_enrollments ce 
             JOIN batches b ON ce.batch_id = b.id 
             WHERE ce.status IN ('pending', 'payment_uploaded') 
             " . ($user_role === 'instructor' ? "AND b.instructor_id = ?" : "") . ") AS total_pending,
            (SELECT COUNT(id) FROM users WHERE role = 'student') AS total_students,
            (SELECT COUNT(id) FROM courses) AS total_courses,
            (SELECT COUNT(id) FROM batches " . ($user_role === 'instructor' ? "WHERE instructor_id = ?" : "") . ") AS total_batches
    ";
    
    $params_stats = [];
    if ($user_role === 'instructor') {
        $params_stats[] = $user_id;
        $params_stats[] = $user_id;
    }

    $stmt_stats = $pdo->prepare($sql_stats);
    $stmt_stats->execute($params_stats);
    $stats = $stmt_stats->fetch(PDO::FETCH_ASSOC);

    $total_pending_enrollments = $stats['total_pending'] ?? 0;
    $total_students = $stats['total_students'] ?? 0;
    $total_batches = $stats['total_batches'] ?? 0;
    $total_courses = $stats['total_courses'] ?? 0;

    // --- Fetch ALL available courses (Admins see all, Instructors see courses they have batches in) ---
    $sql_courses = "
        SELECT DISTINCT
            c.id, c.course_name, c.image_path
        FROM courses c
    ";
    
    $params_courses = [];
    if ($user_role === 'instructor') {
        // Instructors only see courses they have batches assigned to
        $sql_courses .= " JOIN batches b ON c.id = b.course_id WHERE b.instructor_id = ?";
        $params_courses[] = $user_id;
    }

    $sql_courses .= " ORDER BY c.course_name ASC";

    $stmt_courses = $pdo->prepare($sql_courses);
    $stmt_courses->execute($params_courses);
    $courses = $stmt_courses->fetchAll(PDO::FETCH_ASSOC);

    if (empty($courses) && $user_role === 'instructor') {
        $message = "You are not currently assigned to any batches. Courses will appear here once assigned.";
    } elseif (empty($courses)) {
         $message = "No courses are currently available in the system.";
    }

} catch (PDOException $e) {
    $message = "Database error fetching courses: " . $e->getMessage();
    $is_error = true;
    error_log("Admin Dashboard Course Fetch Error: " . $e->getMessage());
}
?>

<div class="w-full max-w-7xl mx-auto px-6 py-8">

    <div class="flex flex-col sm:flex-row justify-between items-center mb-8 pb-4 border-b border-gray-200">
        <h1 class="text-3xl sm:text-4xl font-extrabold text-gray-900 mb-2 sm:mb-0">
            Welcome, <span class="text-blue-600"><?php echo htmlspecialchars($username); ?></span>!
        </h1>
        <div class="text-lg text-gray-700">
            Your Role: <span class="font-semibold capitalize text-blue-600"><?php echo htmlspecialchars($user_role); ?></span>
        </div>
    </div>

    <?php if ($is_error): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg bg-red-100 text-red-700 border border-red-200">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <h2 class="text-2xl font-bold mb-4 text-gray-800">System Overview</h2>
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-10">
        <a href="index.php?page=manage_enrollments" class="block">
            <div class="p-6 rounded-lg shadow-md bg-red-50 border-l-4 border-red-500 hover:bg-red-100 transition duration-300">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-3xl font-extrabold text-red-700"><?php echo htmlspecialchars($total_pending_enrollments); ?></p>
                        <p class="text-md text-red-600 font-semibold mt-1">Pending Req</p>
                    </div>
                    <i class="fas fa-exclamation-triangle text-4xl text-red-400"></i>
                </div>
                <p class="text-xs text-gray-500 mt-2">Click to review enrollments</p>
            </div>
        </a>

        <a href="index.php?page=manage_courses" class="block">
            <div class="p-6 rounded-lg shadow-md bg-green-50 border-l-4 border-green-500 hover:bg-green-100 transition duration-300">
                <div class="flex items-center justify-between">
                    <div>
                       <p class="text-3xl font-extrabold text-green-700"><?php echo htmlspecialchars($total_courses); ?></p>
                        <p class="text-md text-green-600 font-semibold mt-1">Total Courses</p>
                    </div>
                    <i class="fas fa-book-open text-4xl text-green-400"></i>
                </div>
                <p class="text-xs text-gray-500 mt-2">Click to Manage Courses</p>
            </div>
        </a>
        
        <div class="p-6 rounded-lg shadow-md bg-blue-50 border-l-4 border-blue-500">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-3xl font-extrabold text-blue-700"><?php echo htmlspecialchars($total_batches); ?></p>
                    <p class="text-md text-blue-600 font-semibold mt-1">Total Batches</p>
                </div>
                <i class="fas fa-users-class text-4xl text-blue-400"></i>
            </div>
        </div>

        <?php if ($user_role === 'admin'): ?>
        <div class="p-6 rounded-lg shadow-md bg-purple-50 border-l-4 border-purple-500">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-3xl font-extrabold text-purple-700"><?php echo htmlspecialchars($total_students); ?></p>
                    <p class="text-md text-purple-600 font-semibold mt-1">Total Students</p>
                </div>
                <i class="fas fa-user-graduate text-4xl text-purple-400"></i>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <h2 class="text-2xl font-bold mb-6 text-gray-800">Quick Actions</h2>
     <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-10">
        <?php if ($user_role === 'admin'): ?>
        <a href="index.php?page=register_user&role=student" class="flex flex-col items-center justify-center p-6 bg-purple-100 rounded-lg shadow-md hover:bg-purple-200 transition duration-300">
            <i class="fas fa-user-plus w-10 h-10 text-purple-600 mb-2 text-2xl"></i>
            <span class="text-lg font-semibold text-purple-800">Register Student</span>
        </a>
        <a href="index.php?page=register_user&role=instructor" class="flex flex-col items-center justify-center p-6 bg-indigo-100 rounded-lg shadow-md hover:bg-indigo-200 transition duration-300">
            <i class="fas fa-chalkboard-teacher w-10 h-10 text-indigo-600 mb-2 text-2xl"></i>
            <span class="text-lg font-semibold text-indigo-800">Register Instructor</span>
        </a>
        <?php endif; ?>
        <a href="index.php?page=create_course" class="flex flex-col items-center justify-center p-6 bg-green-100 rounded-lg shadow-md hover:bg-green-200 transition duration-300">
            <i class="fas fa-plus-circle w-10 h-10 text-green-600 mb-2 text-2xl"></i>
            <span class="text-lg font-semibold text-green-800">Create New Course</span>
        </a>
        <a href="index.php?page=create_batch" class="flex flex-col items-center justify-center p-6 bg-blue-100 rounded-lg shadow-md hover:bg-blue-200 transition duration-300">
            <i class="fas fa-layer-group w-10 h-10 text-blue-600 mb-2 text-2xl"></i>
            <span class="text-lg font-semibold text-blue-800">Create New Batch</span>
        </a>
        <a href="index.php?page=manage_batches" class="flex flex-col items-center justify-center p-6 bg-yellow-100 rounded-lg shadow-md hover:bg-yellow-200 transition duration-300">
            <i class="fas fa-tasks w-10 h-10 text-yellow-600 mb-2 text-2xl"></i>
            <span class="text-lg font-semibold text-yellow-800">Manage All Batches</span>
        </a>
        <a href="index.php?page=manage_users" class="flex flex-col items-center justify-center p-6 bg-gray-100 rounded-lg shadow-md hover:bg-gray-200 transition duration-300">
            <i class="fas fa-users-cog w-10 h-10 text-gray-600 mb-2 text-2xl"></i>
            <span class="text-lg font-semibold text-gray-800">Manage All Users</span>
        </a>
    </div>
    <hr class="my-10 border-gray-200">

    <h2 class="text-2xl font-bold mb-6 text-gray-800">
        <?php echo ($user_role === 'instructor') ? 'Courses You Manage' : 'Courses for Batch Management'; ?>
    </h2>

    <?php if (!empty($message) && !$is_error): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg bg-blue-50 text-blue-700 border border-blue-200">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        <?php if (!empty($courses)): ?>
            <?php foreach ($courses as $course): ?>
                <div class="bg-white border border-gray-200 rounded-lg shadow-md overflow-hidden flex flex-col hover:shadow-xl transition-shadow duration-300">
                    <img src="<?php echo htmlspecialchars($course['image_path'] ?? 'public/images/default-course.png'); ?>" 
                         alt="Course Image" 
                         class="w-full h-48 object-cover">
                    <div class="p-6 flex-grow">
                        <h3 class="text-xl font-bold mb-2 text-gray-900 leading-tight">
                            <?php echo htmlspecialchars($course['course_name']); ?>
                        </h3>
                         <p class="text-sm text-gray-500 mt-2">ID: #<?php echo htmlspecialchars($course['id']); ?></p>
                    </div>
                    <div class="p-6 bg-gray-50 border-t border-gray-100">
                        <a href="index.php?page=admin_course_batches&course_id=<?php echo htmlspecialchars($course['id']); ?>" 
                           class="block px-4 py-2 bg-blue-600 text-white text-center font-semibold rounded-md hover:bg-blue-700 transition duration-300">
                            View/Manage Batches
                        </a>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<div class="h-12"></div>

</body>
</html>