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

// === Conexão com o banco ===
$host = "localhost";
$user = "kaltekgo_admin";
$pass = "kaltek@2024";
$db   = "kaltekgo_avila";

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(["erro" => "Falha na conexão: " . $e->getMessage()]);
    exit;
}

// === Parâmetros ===
$nome      = isset($_GET['nome']) ? trim($_GET['nome']) : '';
$detalhes  = isset($_GET['detalhes']) ? intval($_GET['detalhes']) : 0;
$matricula = isset($_GET['matricula']) ? trim($_GET['matricula']) : '';

/**
 * 1) Quando buscar apenas pelo nome → retorna lista de alunos (matrícula + nome + turma/turno).
 */
if ($nome != '' && $detalhes == 0) {
    $sql = "SELECT DISTINCT 
                n.matricula, 
                n.nome,
                n.id_turma,
                t.identificador_serie AS turma,
                t.identificador_turma AS nturma,
                t.identificador_turno AS turno
            FROM nota_tarefas_entregues n
            LEFT JOIN serie_turma_turno t 
                   ON n.id_turma = t.id_serie_turma
            WHERE n.nome LIKE ?
            ORDER BY n.nome ASC";
    
    $stmt = $pdo->prepare($sql);
    $param = "%$nome%";
    $stmt->execute([$param]);
    $alunos = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($alunos, JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * 2) Quando clicar em um aluno → retorna todos os detalhes (turma, disciplinas, notas).
 */
if ($detalhes == 1 && $matricula != '') {
    $sql = "SELECT 
    n.id_turma, 
    n.id_disciplina,
    t.identificador_serie AS turma,
    t.identificador_turma AS nturma,
    t.identificador_turno AS turno,
    d.nomeDisciplina AS nome_disciplina,
    n.nome, 
    n.matricula,
    n.idTrimestre,
    n.t1, n.t2, n.t3, n.t4, n.t5, n.t6, n.t7, n.t8, n.t9, n.t10,
    n.t11, n.t12, n.t13, n.t14, n.t15, n.t16, n.t17, n.t18, n.t19, n.t20,
    n.t21, n.t22, n.t23, n.t24, n.t25, n.t26, n.t27, n.t28, n.t29, n.t30
FROM nota_tarefas_entregues n
LEFT JOIN serie_turma_turno t 
       ON n.id_turma = t.id_serie_turma
LEFT JOIN disciplinas d 
       ON n.id_disciplina = d.id_disciplina
WHERE n.matricula = ? 
  AND n.idTrimestre = '0';
";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$matricula]);
    $resultado = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$resultado) { 
        echo json_encode(["erro" => "Aluno não encontrado"]);
        exit;
    }

    $aluno = [
        "nome"      => $resultado[0]["nome"],
        "matricula" => $resultado[0]["matricula"],
        "id_turma"  => $resultado[0]["id_turma"],
        "turma"     => $resultado[0]["turma"],
        "nturma"    => $resultado[0]["nturma"],
        "turno"     => $resultado[0]["turno"],
        "disciplinas" => []
    ];

    foreach ($resultado as $row) {
        $notas = [];
        for ($i = 1; $i <= 30; $i++) {
            $coluna = "t$i";
            if (!is_null($row[$coluna])) {
                $notas[$coluna] = $row[$coluna];
            }
        }

// 🔎 Buscar nota do simulado_geral
$stmtSimulado = $pdo->prepare("SELECT nota, nota2 FROM simulado_geral WHERE matricula = ? LIMIT 1");
$stmtSimulado->execute([$row["matricula"]]);
$simuladoRow = $stmtSimulado->fetch(PDO::FETCH_ASSOC);

$simulado = 0;
if ($simuladoRow) {
    $nota  = (float)($simuladoRow['nota'] ?? 0);
    $nota2 = (float)($simuladoRow['nota2'] ?? 0);
    $simulado = $nota + $nota2;
}

$aluno["disciplinas"][] = [
    "disciplina" => $row["nome_disciplina"] ?? $row["id_disciplina"],
    "notas"      => $notas,
    "simulado"   => $simulado
];

    }

    echo json_encode($aluno, JSON_UNESCAPED_UNICODE);
    exit;
}

// === Caso nada válido ===
echo json_encode(["erro" => "Parâmetros inválidos"]);
