<?php
session_start();
include 'conexao.php';

if (!isset($_SESSION['usuario'])) {
    header("Location: login.php");
    exit;
}

$usuario = $_SESSION['usuario'];
$perfil_logado = strtoupper($usuario['perfil']);
$nome_usuario_logado = htmlspecialchars($usuario['nome'] ?? 'Usuário');

$professor_id_a_consultar = null;
$nome_professor_a_consultar = '';
$titulo_pagina = 'Seu Histórico de Lançamentos';
$eh_gestor_visualizando = false;

if (in_array($perfil_logado, ['SUBDIRECÇÃO PEDAGÓGICA', 'ADMINISTRADOR'])) {
    $professor_id_url = filter_input(INPUT_GET, 'professor_id', FILTER_VALIDATE_INT);
    $nome_professor_url = filter_input(INPUT_GET, 'nome_professor', FILTER_SANITIZE_STRING);
    if ($professor_id_url) {
        $professor_id_a_consultar = $professor_id_url;
        $nome_professor_a_consultar = htmlspecialchars($nome_professor_url) ?: "Professor ID: {$professor_id_url}";
        $titulo_pagina = "Histórico de Lançamentos de: {$nome_professor_a_consultar}";
        $eh_gestor_visualizando = true;
    }
}

if (!$professor_id_a_consultar) {
    if ($perfil_logado !== 'PROFESSOR' && !$eh_gestor_visualizando) {
        header("Location: login.php");
        exit;
    }
    $professor_id_a_consultar = intval($usuario['id']);
    $nome_professor_a_consultar = $nome_usuario_logado;
}

$historico = [];

$query_historico = "
(
    SELECT t.nome AS nome_turma, d.nome AS nome_disciplina, a.nome AS nome_aluno,
           n.trimestre, 'NPP' AS tipo_nota, n.npp AS valor_nota, n.data_lancamento
    FROM notas n
    JOIN alunos a ON n.aluno_id = a.id
    JOIN turmas t ON n.turma_id = t.id
    JOIN disciplinas d ON n.disciplina_id = d.id
    JOIN atribuicoes atr ON d.id = atr.disciplina_id AND t.id = atr.turma_id
    WHERE atr.professor_id = ? AND n.npp IS NOT NULL AND n.npp > 0
    UNION ALL
    SELECT t.nome, d.nome, a.nome, n.trimestre, 'NPT', n.npt, n.data_lancamento
    FROM notas n
    JOIN alunos a ON n.aluno_id = a.id
    JOIN turmas t ON n.turma_id = t.id
    JOIN disciplinas d ON n.disciplina_id = d.id
    JOIN atribuicoes atr ON d.id = atr.disciplina_id AND t.id = atr.turma_id
    WHERE atr.professor_id = ? AND n.npt IS NOT NULL AND n.npt > 0
    UNION ALL
    SELECT t.nome, d.nome, a.nome, n.trimestre, 'MAC', n.mac, n.data_lancamento
    FROM notas n
    JOIN alunos a ON n.aluno_id = a.id
    JOIN turmas t ON n.turma_id = t.id
    JOIN disciplinas d ON n.disciplina_id = d.id
    JOIN atribuicoes atr ON d.id = atr.disciplina_id AND t.id = atr.turma_id
    WHERE atr.professor_id = ? AND n.mac IS NOT NULL AND n.mac > 0
)
ORDER BY data_lancamento DESC LIMIT 100
";

$stmt = $conn->prepare($query_historico);
$stmt->bind_param("iii", $professor_id_a_consultar, $professor_id_a_consultar, $professor_id_a_consultar);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) $historico[] = $row;
$stmt->close();
$conn->close();
?>
<!DOCTYPE html>
<html lang="pt">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Histórico de Lançamentos - SISMAG</title>
<link rel="stylesheet" href="https://rsms.me/inter/inter.css">
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="css/all.min.css">
<style>body{font-family:'Inter',sans-serif}</style>
</head>
<body class="bg-gray-100 flex min-h-screen">

<!-- BARRA LATERAL -->
<aside class="w-64 bg-[#0d1b2a] text-white flex flex-col">
    <div class="p-4 border-b border-gray-700">
        <h1 class="text-xl font-bold text-blue-400">SISMAG</h1>
        <p class="text-xs text-gray-400 mt-1"><?= $perfil_logado ?></p>
    </div>
    <nav class="flex-1 mt-3">
        <?php if ($eh_gestor_visualizando): ?>
            <a href="historico_controlo.php" class="block px-5 py-3 hover:bg-[#1b263b] transition">
                <i class="fas fa-arrow-left text-blue-400 mr-2"></i> Voltar à Lista
            </a>
        <?php else: ?>
            <a href="painel_professor1.php" class="block px-5 py-3 hover:bg-[#1b263b] transition">
                <i class="fas fa-home text-blue-400 mr-2"></i> Painel
            </a>
        <?php endif; ?>
        <a href="logout.php" class="block px-5 py-3 hover:bg-red-700 transition">
            <i class="fas fa-sign-out-alt text-red-400 mr-2"></i> Sair
        </a>
    </nav>
</aside>

<!-- CONTEÚDO -->
<main class="flex-1 flex flex-col">
    <header class="bg-blue-700 text-white p-4 shadow flex justify-between items-center">
        <h2 class="text-lg font-semibold flex items-center gap-2">
            <i class="fas fa-history"></i> <?= $titulo_pagina ?>
        </h2>
    </header>

    <section class="flex-1 p-6">
        <div class="bg-white rounded-xl shadow-lg p-6 max-w-6xl mx-auto">
            <p class="text-gray-600 mb-6 border-b pb-3 text-sm">
                <?= $eh_gestor_visualizando 
                    ? "Visualizando o histórico de lançamentos de <b>{$nome_professor_a_consultar}</b>." 
                    : "Olá, professor(a) <b>{$nome_professor_a_consultar}</b>. Visualize o seu histórico recente de notas lançadas." ?>
            </p>

            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Data</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Disciplina (Turma)</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Aluno</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">Trim.</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">Tipo</th>
                            <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">Nota</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php if (empty($historico)): ?>
                            <tr>
                                <td colspan="6" class="px-6 py-4 text-center text-sm text-gray-500">
                                    Nenhum lançamento encontrado.
                                </td>
                            </tr>
                        <?php else: foreach ($historico as $item): ?>
                            <tr class="hover:bg-gray-50 transition">
                                <td class="px-6 py-4 text-sm text-gray-500">
                                    <?= date('d/m/Y H:i', strtotime($item['data_lancamento'])) ?>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-900">
                                    <?= htmlspecialchars($item['nome_disciplina']) ?> (<?= htmlspecialchars($item['nome_turma']) ?>)
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-900">
                                    <?= htmlspecialchars($item['nome_aluno']) ?>
                                </td>
                                <td class="px-6 py-4 text-sm text-center text-gray-900"><?= $item['trimestre'] ?>º</td>
                                <td class="px-6 py-4 text-sm text-center font-semibold text-gray-900"><?= $item['tipo_nota'] ?></td>
                                <td class="px-6 py-4 text-sm text-center font-bold text-gray-900"><?= number_format($item['valor_nota'], 1, ',', '.') ?></td>
                            </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </section>
</main>
</body>
</html>
