<?php
session_start();
include '../includes/db.php';

// Validaciones básicas
if (!isset($_SESSION['username']) || $_SESSION['rol'] != 'coordinador2' || !$conn) {
    header('HTTP/1.1 403 Forbidden');
    exit();
}

if (!isset($_GET['estudiante_id']) || !isset($_GET['postgrado_id'])) {
    echo json_encode([]);
    exit();
}

try {
    $sql = "SELECT d.id, d.nombre, d.codigo, d.tipo 
            FROM denominaciones d
            WHERE d.postgrado_id = ?
            AND NOT EXISTS (
                SELECT 1 FROM inscripciones i 
                WHERE i.denominacion_id = d.id AND i.estudiante_id = ?
                AND (
                    (d.tipo = 'puntaje' AND i.nota_final >= 10) OR
                    (d.tipo = 'aprobado_reprobado' AND i.nota_definitiva = 'aprobado')
                )
            )";

    $stmt = $conn->prepare($sql);
    if (!$stmt) throw new Exception("Error SQL: " . $conn->error);
    
    $stmt->bind_param("ii", $_GET['postgrado_id'], $_GET['estudiante_id']);
    $stmt->execute();
    
    header('Content-Type: application/json');
    echo json_encode($stmt->get_result()->fetch_all(MYSQLI_ASSOC));
    
} catch (Exception $e) {
    header('HTTP/1.1 500 Internal Server Error');
    echo json_encode(['error' => $e->getMessage()]);
}