<?php
/**
 * SisPen Snesaka - Fungsi Umum
 */

// Mulai session jika belum
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/database.php';

// ===================== BASE URL =====================
// Auto-detect subfolder, works for localhost/SISPENRA or localhost/
function getBaseUrl() {
    if (isset($_SESSION['base_url'])) return $_SESSION['base_url'];

    $scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
    // Find the SISPENRA root: walk up from current script to find index.php location
    $docRoot = str_replace('\\', '/', realpath(__DIR__ . '/..'));
    $serverRoot = str_replace('\\', '/', realpath($_SERVER['DOCUMENT_ROOT'] ?? ''));

    if ($serverRoot && strpos($docRoot, $serverRoot) === 0) {
        $base = substr($docRoot, strlen($serverRoot));
        $base = rtrim($base, '/');
    } else {
        // Fallback: detect from SCRIPT_NAME
        $base = dirname(dirname(str_replace('\\', '/', $scriptName)));
        $base = rtrim($base === '.' ? '' : $base, '/');
        // If we're in modules/xxx/, go up 2 levels
        if (strpos($scriptName, '/modules/') !== false) {
            $base = dirname(dirname(dirname(str_replace('\\', '/', $scriptName))));
            $base = rtrim($base === '.' ? '' : $base, '/');
        } elseif (strpos($scriptName, '/api/') !== false || strpos($scriptName, '/templates/') !== false || strpos($scriptName, '/includes/') !== false) {
            $base = dirname(dirname(str_replace('\\', '/', $scriptName)));
            $base = rtrim($base === '.' ? '' : $base, '/');
        }
    }

    $_SESSION['base_url'] = $base;
    return $base;
}

function url($path = '') {
    $base = getBaseUrl();
    $path = ltrim($path, '/');
    return $base . ($path ? '/' . $path : '');
}

define('BASE_URL', getBaseUrl());

// ===================== AUTH =====================

function isLoggedIn() {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: ' . url('index.php'));
        exit;
    }
}

function requireAdmin() {
    requireLogin();
    if ($_SESSION['role'] !== 'admin') {
        header('Location: ' . url('guru.php'));
        exit;
    }
}

function getCurrentUser() {
    if (!isLoggedIn()) return null;
    return db_fetch("SELECT u.*, g.id as guru_id, g.nip FROM users u LEFT JOIN guru g ON g.user_id = u.id WHERE u.id = ?", [$_SESSION['user_id']]);
}

function login($username, $password) {
    $user = db_fetch("SELECT * FROM users WHERE username = ? AND status = 'aktif'", [$username]);
    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['nama'] = $user['nama_lengkap'];
        $_SESSION['role'] = $user['role'];

        // Simpan guru_id / is_bk (guru) atau nis (siswa) ke session
        if ($user['role'] === 'guru') {
            $guru = db_fetch("SELECT id, is_bk FROM guru WHERE user_id = ?", [$user['id']]);
            $_SESSION['guru_id'] = $guru['id']    ?? null;
            $_SESSION['is_bk']   = $guru['is_bk'] ?? 0;
        } elseif ($user['role'] === 'siswa') {
            // username siswa = NIS
            $_SESSION['nis'] = $user['username'];
        }

        return $user;
    }
    return false;
}

function requireSiswa() {
    if (!isLoggedIn() || $_SESSION['role'] !== 'siswa') {
        header('Location: ' . BASE_URL . '/index.php');
        exit;
    }
}

function logout() {
    $base = BASE_URL;
    session_destroy();
    header('Location: ' . $base . '/index.php');
    exit;
}

// ===================== NILAI =====================

function hitungNilaiAkhir($tugas, $harian, $uts, $uas, $praktik = null) {
    // Legacy – tidak dipakai di Kurikulum Merdeka
    return round(($tugas * 0.20) + ($harian * 0.20) + ($uts * 0.30) + ($uas * 0.30), 2);
}

/**
 * Ambil formula dari pengaturan.
 * Return array: ['rata_sumatif'=>50, 'sts'=>25, 'sas'=>25, 'jumlah_sumatif'=>5]
 */
function getFormula() {
    $p = getPengaturan();
    return array(
        'rata_sumatif'   => isset($p['formula_rata_sumatif'])  && $p['formula_rata_sumatif']  > 0 ? floatval($p['formula_rata_sumatif'])  : 50.0,
        'sts'            => isset($p['formula_sts'])           && $p['formula_sts']           >= 0 ? floatval($p['formula_sts'])           : 25.0,
        'sas'            => isset($p['formula_sas'])           && $p['formula_sas']           >= 0 ? floatval($p['formula_sas'])           : 25.0,
        'jumlah_sumatif' => isset($p['formula_jumlah_sumatif']) && $p['formula_jumlah_sumatif'] > 0 ? intval($p['formula_jumlah_sumatif'])   : 5,
    );
}

/**
 * Hitung nilai rapor dari komponen Merdeka.
 * $sumatifs = array nilai sumatif (boleh ada NULL).
 * $formula  = array dari getFormula() atau custom.
 */
function hitungNilaiRapor($sumatifs, $sts, $sas, $formula = null) {
    if ($formula === null) $formula = getFormula();

    // Rata-rata sumatif dari yang terisi saja
    $isiSumatif = array_filter($sumatifs, function($v){ return $v !== null && $v !== ''; });
    $rataSumatif = count($isiSumatif) > 0 ? array_sum($isiSumatif) / count($isiSumatif) : null;

    // Hitung dengan bobot proporsional jika ada komponen kosong
    $totalBobot = 0;
    $totalNilai = 0;

    if ($rataSumatif !== null && $formula['rata_sumatif'] > 0) {
        $totalNilai += $rataSumatif * $formula['rata_sumatif'];
        $totalBobot += $formula['rata_sumatif'];
    }
    if ($sts !== null && $sts !== '' && $formula['sts'] > 0) {
        $totalNilai += floatval($sts) * $formula['sts'];
        $totalBobot += $formula['sts'];
    }
    if ($sas !== null && $sas !== '' && $formula['sas'] > 0) {
        $totalNilai += floatval($sas) * $formula['sas'];
        $totalBobot += $formula['sas'];
    }

    if ($totalBobot <= 0) return null;
    return round($totalNilai / $totalBobot, 0);
}

function getPredikat($nilai, $kkm = 75) {
    if ($nilai >= 90) return 'A';
    if ($nilai >= 80) return 'B';
    if ($nilai >= $kkm) return 'C';
    return 'D';
}

function getKeteranganPredikat($predikat) {
    $ket = ['A' => 'Sangat Baik', 'B' => 'Baik', 'C' => 'Cukup', 'D' => 'Perlu Bimbingan'];
    return $ket[$predikat] ?? '-';
}

function getLulusStatus($nilai, $kkm) {
    return $nilai >= $kkm ? 'Tuntas' : 'Belum Tuntas';
}

// ===================== FORMAT =====================

function formatTanggal($tanggal) {
    if (!$tanggal) return '-';
    $bulan = ['', 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
              'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
    $t = explode('-', $tanggal);
    return intval($t[2]) . ' ' . $bulan[intval($t[1])] . ' ' . $t[0];
}

function formatNilai($nilai) {
    if ($nilai === null) return '-';
    return number_format($nilai, 2);
}

function sanitize($input) {
    return htmlspecialchars(strip_tags(trim($input)), ENT_QUOTES, 'UTF-8');
}

function generateToken() {
    return bin2hex(random_bytes(32));
}

// ===================== FLASH MESSAGE =====================

function setFlash($type, $message) {
    $_SESSION['flash'] = ['type' => $type, 'message' => $message];
}

function getFlash() {
    if (isset($_SESSION['flash'])) {
        $flash = $_SESSION['flash'];
        unset($_SESSION['flash']);
        return $flash;
    }
    return null;
}

// ===================== PAGINATION =====================

function paginate($total, $perPage, $currentPage, $url) {
    $totalPages = ceil($total / $perPage);
    if ($totalPages <= 1) return '';

    $html = '<nav><ul class="pagination">';
    for ($i = 1; $i <= $totalPages; $i++) {
        $active = $i == $currentPage ? ' active' : '';
        $html .= "<li class='page-item{$active}'><a class='page-link' href='{$url}&page={$i}'>{$i}</a></li>";
    }
    $html .= '</ul></nav>';
    return $html;
}

// ===================== STATISTIK =====================

function getRataKelas($kelas_id, $mapel_id, $tahun_ajaran, $semester) {
    $result = db_fetch(
        "SELECT AVG(nilai_akhir) as rata FROM nilai WHERE kelas_id = ? AND mapel_id = ? AND tahun_ajaran = ? AND semester = ?",
        [$kelas_id, $mapel_id, $tahun_ajaran, $semester]
    );
    return round($result['rata'] ?? 0, 2);
}

function getJumlahSiswaByKelas($kelas_id) {
    $result = db_fetch("SELECT COUNT(*) as total FROM siswa WHERE kelas_id = ? AND status = 'aktif'", [$kelas_id]);
    return $result['total'] ?? 0;
}

function getProgressInputNilai($kelas_id, $mapel_id, $tahun_ajaran, $semester) {
    $total = getJumlahSiswaByKelas($kelas_id);
    if (!$total) return 0;
    $sudah = db_fetch(
        "SELECT COUNT(*) as c FROM nilai WHERE kelas_id = ? AND mapel_id = ? AND tahun_ajaran = ? AND semester = ?",
        [$kelas_id, $mapel_id, $tahun_ajaran, $semester]
    );
    return round(($sudah['c'] / $total) * 100);
}
