<?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'] ?? [];
    $disciplinas = $_POST['disciplina'] ?? [];
    $points1 = $_POST['point1'] ?? [];
    $points2 = $_POST['point2'] ?? [];
    $points3 = $_POST['point3'] ?? [];
    $points4 = $_POST['point4'] ?? [];

    // Verificação de existência
    $check = $pdo->prepare("SELECT COUNT(*) FROM nota_tarefas_entregues WHERE matricula = ? AND id_turma = ? AND id_disciplina = ?");

    // Update
    $update = $pdo->prepare("
        UPDATE nota_tarefas_entregues SET 
            point1 = ?, point2 = ?, point3 = ?, point4 = ?, nome = ?
        WHERE matricula = ? AND id_turma = ? AND id_disciplina = ?
    ");

    // Insert
    $insert = $pdo->prepare("
        INSERT INTO nota_tarefas_entregues (
            matricula, point1, point2, point3, point4, nome, id_turma, id_disciplina
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");

    for ($i = 0; $i < count($alunos); $i++) {
        $alunoId = $alunos[$i];
        $nome = $nomes[$i] ?? '';
        $turma = $turmas[$i] ?? '';
        $disciplina = $disciplinas[$i] ?? '';
        $point1 = floatval(str_replace(',', '.', $points1[$i] ?? 0));
        $point2 = floatval(str_replace(',', '.', $points2[$i] ?? 0));
        $point3 = floatval(str_replace(',', '.', $points3[$i] ?? 0));
        $point4 = floatval(str_replace(',', '.', $points4[$i] ?? 0));

        $temNota = $point1 > 0 || $point2 > 0 || $point3 > 0 || $point4 > 0;

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

            if ($existe) {
                $update->execute([
                    $point1, $point2, $point3, $point4, $nome,
                    $alunoId, $turma, $disciplina
                ]);
            } else {
                $insert->execute([
                    $alunoId, $point1, $point2, $point3, $point4, $nome, $turma, $disciplina
                ]);
            }
        }
    }

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