<?php
include('db_connection.php');

$user_level = isset($_GET['user_level']) ? (int)$_GET['user_level'] : 0;
$user_id = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
$class_id = isset($_GET['class_id']) ? (int)$_GET['class_id'] : null;
$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d'); // Default to today's date

if ($user_level <= 0 || $user_id <= 0 || empty($date)) {
    echo json_encode(['success' => false, 'message' => 'Invalid request parameters']);
    exit();
}

if ($user_level === 3 && empty($class_id)) {
    echo json_encode(['success' => true, 'schedule' => []]);
    exit();
}

$query = "SELECT cs.id, cs.date, cs.position, s.name AS subject_name, r.room_number, 
                 e.username AS teacher_name, 
                 c.class_name
          FROM class_schedule cs
          JOIN subjects s ON cs.subject_id = s.id
          JOIN rooms r ON cs.room_id = r.id
          LEFT JOIN emails_v e ON cs.teacher_id = e.id
          LEFT JOIN classes c ON cs.class_id = c.id
          WHERE cs.date = :date";

if ($user_level === 1) {
    $query .= " AND cs.class_id = :class_id";
} elseif ($user_level === 2) {
    $query .= " AND cs.teacher_id = :user_id";
} elseif ($user_level === 3) {
    if ($class_id) {
        $query .= " AND cs.class_id = :class_id";
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid user level']);
    exit();
}

try {
    $stmt = $pdo->prepare($query);
    
    $stmt->bindParam(':date', $date);

    if ($user_level === 1) {
        $stmt->bindParam(':class_id', $class_id);
    } elseif ($user_level === 2) {
        $stmt->bindParam(':user_id', $user_id);
    } elseif ($user_level === 3) {
        if ($class_id) {
            $stmt->bindParam(':class_id', $class_id);
        }
    }

    $stmt->execute();
    
    $schedule = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (count($schedule) > 0) {
        echo json_encode(['success' => true, 'schedule' => $schedule]);
    } else {
        echo json_encode(['success' => true, 'schedule' => []]);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Error executing query: ' . $e->getMessage()]);
}
?>
