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

try {
    $pdo = new PDO("mysql:host=localhost;dbname=kaltekgo_avila", "kaltekgo_admin", "kaltek@2024");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Dados do formulário
    $alunos = $_POST['aluno_id'] ?? [];
    $nomes = $_POST['nome'] ?? [];
    $turmas = $_POST['id_turma'] ?? [];
    $points = $_POST['point'] ?? [];
    $disciplinas = $_POST['disciplina'] ?? [];
    //$mts = $_POST['mt'] ?? [];

    // Notas de t1 a t30
    $notas = [];
    for ($i = 1; $i <= 30; $i++) {
        $notas["t{$i}"] = $_POST["t{$i}"] ?? [];
    }
    
    $check = $pdo->prepare("SELECT COUNT(*) FROM nota_tarefas_entregues WHERE matricula = ? AND id_turma = ? AND id_disciplina = ?");

    // Construir parte dinâmica do UPDATE
    $camposUpdate = [];
    for ($i = 1; $i <= 30; $i++) {
        $camposUpdate[] = "t{$i} = ?";
    }
    $updateSQL = "
        UPDATE nota_tarefas_entregues SET 
            " . implode(', ', $camposUpdate) . ",
            point = ?, nome = ?, id_turma = ?, id_disciplina = ?, mt = ?
        WHERE matricula = ? AND id_turma = ? AND id_disciplina = ?
    ";
    $update = $pdo->prepare($updateSQL);

    // Construir parte dinâmica do INSERT
    $camposInsert = implode(', ', array_map(fn($i) => "t{$i}", range(1, 30)));
    $placeholders = rtrim(str_repeat('?, ', 30), ', ');
    $insertSQL = "
        INSERT INTO nota_tarefas_entregues (
            matricula, $camposInsert, point, nome, id_turma, id_disciplina, mt
        ) VALUES (?, $placeholders, ?, ?, ?, ?, ?)
    ";
    $insert = $pdo->prepare($insertSQL);

    for ($i = 0; $i < count($alunos); $i++) {
        $alunoId = $alunos[$i];
        $nome = $nomes[$i] ?? '';
        $turma = $turmas[$i] ?? '';
        $disciplina = $disciplinas[$i] ?? '';
        $mt = floatval(str_replace(',', '.', $mts[$i] ?? 0));
        $point = floatval(str_replace(',', '.', $points[$i] ?? 0));

        // Coletar notas t1 a t30
        $valoresNotas = [];
        for ($j = 1; $j <= 30; $j++) {
            $campo = "t{$j}";
            $valoresNotas[] = floatval(str_replace(',', '.', $notas[$campo][$i] ?? 0));
        }

        $temNota = array_reduce($valoresNotas, fn($carry, $v) => $carry || $v > 0, false) || $point > 0;

        if ($temNota) {
            $check->execute([$alunoId, $turma, $disciplina]);
            $existe = $check->fetchColumn();

            if ($existe) {
                $update->execute([
                    ...$valoresNotas, $point, $nome, $turma, $disciplina, $mt,
                    $alunoId, $turma, $disciplina
                ]);
            } else {
                $insert->execute([
                    $alunoId, ...$valoresNotas, $point, $nome, $turma, $disciplina, $mt
                ]);
            }
        }
    }

    echo json_encode(['sucesso' => true, 'mensagem' => 'Dados salvos com sucesso! Aguarde um momento']);
} catch (Exception $e) {
    echo json_encode(['sucesso' => false, 'mensagem' => 'Erro: ' . $e->getMessage()]);
} 