<?php
require_once __DIR__ . '/../config/db.php';

header('Content-Type: application/json');

$action = $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'tipos_ensenanza':
            $sql = "SELECT id, nombre FROM tipos_ensenanza ORDER BY id";
            $result = $conn->query($sql);
            $tipos = [];
            while ($row = $result->fetch_assoc()) {
                $tipos[] = $row;
            }
            echo json_encode($tipos);
            break;

        case 'grados':
            $sql = "SELECT id, nombre, tipo_ensenanza_id FROM grados ORDER BY tipo_ensenanza_id, id";
            $result = $conn->query($sql);
            $grados = [];
            while ($row = $result->fetch_assoc()) {
                $grados[] = $row;
            }
            echo json_encode($grados);
            break;

        case 'alumnos_count':
            $sql = "SELECT COUNT(*) as total FROM alumnos";
            $result = $conn->query($sql);
            $count = $result->fetch_assoc();
            echo json_encode($count);
            break;

        case 'alumnos_por_grado':
            $sql = "SELECT g.nombre as grado, COUNT(a.id) as cantidad 
                    FROM grados g 
                    LEFT JOIN alumnos a ON g.id = a.grado_id 
                    GROUP BY g.id, g.nombre 
                    ORDER BY g.tipo_ensenanza_id, g.id";
            $result = $conn->query($sql);
            $stats = [];
            while ($row = $result->fetch_assoc()) {
                $stats[] = $row;
            }
            echo json_encode($stats);
            break;

        default:
            echo json_encode(['error' => 'Acción no válida']);
    }
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
