<?php
session_start();
require '../conexion.php';

$profesor_id = $_SESSION['profesor']['id'] ?? null;

if (!$profesor_id) {
  http_response_code(401);
  echo json_encode(["error" => "No autenticado"]);
  exit;
}

function getAll($pdo, $sql, $params = []) {
  $stmt = $pdo->prepare($sql);
  $stmt->execute($params);
  return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

$cursos = getAll($pdo, "SELECT * FROM cursos WHERE profesor_id = ?", [$profesor_id]);

$alumnos = getAll($pdo, "
  SELECT DISTINCT a.* FROM alumnos a
  JOIN alumnos_cursos ac ON a.id = ac.alumno_id
  JOIN cursos c ON ac.curso_id = c.id
  WHERE c.profesor_id = ?
", [$profesor_id]);

$diplomas = getAll($pdo, "
  SELECT d.* FROM diplomas d
  JOIN alumnos_cursos ac ON d.alumno_curso_id = ac.id
  JOIN cursos c ON ac.curso_id = c.id
  WHERE c.profesor_id = ?
", [$profesor_id]);

echo json_encode([
  "cursos" => $cursos,
  "alumnos" => $alumnos,
  "diplomas" => $diplomas,
  "lastUpdated" => date("Y-m-d H:i:s")
]);
