<?php
/**
 * SISPENRA - API: Save Nilai (AJAX)
 */
require_once '../includes/functions.php';
requireLogin();
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) $input = $_POST;

$pengaturan = getPengaturan();
$required = ['siswa_id', 'mapel_id', 'kelas_id'];
foreach ($required as $r) {
    if (empty($input[$r])) {
        echo json_encode(['error' => "$r is required"]);
        exit;
    }
}

$siswaId = intval($input['siswa_id']);
$mapelId = intval($input['mapel_id']);
$kelasId = intval($input['kelas_id']);
$tugas   = floatval($input['nilai_tugas'] ?? 0);
$harian  = floatval($input['nilai_harian'] ?? 0);
$uts     = floatval($input['nilai_uts'] ?? 0);
$uas     = floatval($input['nilai_uas'] ?? 0);
$akhir   = round(($tugas * 0.20) + ($harian * 0.20) + ($uts * 0.30) + ($uas * 0.30), 2);
$predikat = getPredikat($akhir);

$currentUser = getCurrentUser();
$guruId = $currentUser['guru_id'] ?? null;

$existing = db_fetch("SELECT id FROM nilai WHERE siswa_id = ? AND mapel_id = ? AND kelas_id = ? AND tahun_ajaran = ? AND semester = ?",
    [$siswaId, $mapelId, $kelasId, $pengaturan['tahun_ajaran_aktif'], $pengaturan['semester_aktif']]);

$row = [
    'nilai_tugas' => $tugas, 'nilai_harian' => $harian,
    'nilai_uts' => $uts, 'nilai_uas' => $uas,
    'nilai_akhir' => $akhir, 'predikat' => $predikat,
    'catatan' => sanitize($input['catatan'] ?? ''),
    'guru_id' => $guruId ?? 1,
];

if ($existing) {
    db_update('nilai', $row, 'id = :id', ['id' => $existing['id']]);
} else {
    db_insert('nilai', array_merge($row, [
        'siswa_id' => $siswaId, 'mapel_id' => $mapelId, 'kelas_id' => $kelasId,
        'tahun_ajaran' => $pengaturan['tahun_ajaran_aktif'],
        'semester' => $pengaturan['semester_aktif'],
    ]));
}

echo json_encode(['success' => true, 'nilai_akhir' => $akhir, 'predikat' => $predikat]);
