<?php
// includes/functions.php

if (!function_exists('formatTanggal')) {
    function formatTanggal($date)
    {
        if (!$date) return '-';

        $bulan = [
            1 => 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
            'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
        ];

        $timestamp = strtotime((string)$date);
        if (!$timestamp) return '-';

        $tgl = date('j', $timestamp);
        $bln = $bulan[(int)date('n', $timestamp)] ?? '-';
        $thn = date('Y', $timestamp);

        return $tgl . ' ' . $bln . ' ' . $thn;
    }
}

if (!function_exists('formatRupiah')) {
    function formatRupiah($angka)
    {
        return 'Rp ' . number_format((float)$angka, 0, ',', '.');
    }
}

if (!function_exists('bulanRomawi')) {
    function bulanRomawi($bln)
    {
        $romawi = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII'];
        $index = (int)$bln - 1;

        return $romawi[$index] ?? '-';
    }
}

if (!function_exists('generateNomorSurat')) {
    function generateNomorSurat($jenis = 'KEP')
    {
        $conn = getConnection();
        $bulan = (int)date('n');
        $tahun = (int)date('Y');

        $stmt = $conn->prepare("SELECT nomor_terakhir FROM counter_surat WHERE bulan = ? AND tahun = ? LIMIT 1");
        if (!$stmt) {
            return sprintf("%03d/%s-RSBM/%s/%d", 1, $jenis, bulanRomawi($bulan), $tahun);
        }

        $stmt->bind_param("ii", $bulan, $tahun);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($row = $result->fetch_assoc()) {
            $nomor = (int)$row['nomor_terakhir'] + 1;

            $stmtUpdate = $conn->prepare("UPDATE counter_surat SET nomor_terakhir = ? WHERE bulan = ? AND tahun = ?");
            if ($stmtUpdate) {
                $stmtUpdate->bind_param("iii", $nomor, $bulan, $tahun);
                $stmtUpdate->execute();
                $stmtUpdate->close();
            }
        } else {
            $nomor = 1;

            $stmtInsert = $conn->prepare("INSERT INTO counter_surat (bulan, tahun, nomor_terakhir) VALUES (?, ?, ?)");
            if ($stmtInsert) {
                $stmtInsert->bind_param("iii", $bulan, $tahun, $nomor);
                $stmtInsert->execute();
                $stmtInsert->close();
            }
        }

        $stmt->close();

        return sprintf("%03d/%s-RSBM/%s/%d", $nomor, $jenis, bulanRomawi($bulan), $tahun);
    }
}

if (!function_exists('logActivity')) {
    function logActivity(string $action, string $module, int $record_id = 0, string $description = ''): bool
    {
        if (!function_exists('getConnection')) {
            return false;
        }

        $conn = getConnection();
        if (!$conn instanceof mysqli) {
            return false;
        }

        if (session_status() === PHP_SESSION_NONE) {
            @session_start();
        }

        // Kandidat user ID dari session
        $candidateUserId = 0;
        if (!empty($_SESSION['user_id'])) {
            $candidateUserId = (int)$_SESSION['user_id'];
        } elseif (!empty($_SESSION['user']['id'])) {
            $candidateUserId = (int)$_SESSION['user']['id'];
        } elseif (!empty($_SESSION['id'])) {
            $candidateUserId = (int)$_SESSION['id'];
        }

        // Validasi ke tabel users supaya tidak nabrak FK
        $validUserId = null;
        if ($candidateUserId > 0) {
            $check = $conn->prepare("SELECT id FROM users WHERE id = ? LIMIT 1");
            if ($check) {
                $check->bind_param("i", $candidateUserId);
                $check->execute();
                $res = $check->get_result();
                if ($res && $res->fetch_assoc()) {
                    $validUserId = $candidateUserId;
                }
                $check->close();
            }
        }

        // employee_id opsional, tidak dipaksa dari session
        $employeeId = null;
        if (!empty($_SESSION['employee_id'])) {
            $employeeId = (int)$_SESSION['employee_id'];
        } elseif (!empty($_SESSION['employee']['id'])) {
            $employeeId = (int)$_SESSION['employee']['id'];
        }

        $username = (string)(
            $_SESSION['username']
            ?? $_SESSION['full_name']
            ?? $_SESSION['user']['username']
            ?? $_SESSION['user']['name']
            ?? 'system'
        );

        $ip = $_SERVER['REMOTE_ADDR'] ?? '';
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';

        /*
         * Gunakan nama kolom sesuai struktur tabel lama Anda:
         * activity_logs(user_id, employee_id, action, module_name, record_id, description, ip_address, user_agent)
         */
        $stmt = $conn->prepare("
            INSERT INTO activity_logs
            (user_id, employee_id, action, module_name, record_id, description, ip_address, user_agent)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");

        if (!$stmt) {
            return false;
        }

        $stmt->bind_param(
            "iississs",
            $validUserId,
            $employeeId,
            $action,
            $module,
            $record_id,
            $description,
            $ip,
            $userAgent
        );

        $ok = $stmt->execute();
        $stmt->close();

        return $ok;
    }
}

if (!function_exists('getUserInfo')) {
    function getUserInfo($user_id)
    {
        $conn = getConnection();

        $stmt = $conn->prepare("
            SELECT u.*, e.full_name, e.nik, e.photo_path, u.role
            FROM users u
            JOIN employees e ON u.employee_id = e.id
            WHERE u.id = ?
            LIMIT 1
        ");

        if (!$stmt) {
            return null;
        }

        $user_id = (int)$user_id;
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result ? $result->fetch_assoc() : null;
        $stmt->close();

        return $row ?: null;
    }
}

if (!function_exists('getUnits')) {
    function getUnits()
    {
        $conn = getConnection();
        $result = $conn->query("SELECT * FROM units WHERE is_active = 1 ORDER BY name");

        $data = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
        }

        return $data;
    }
}

if (!function_exists('getEmployeesByUnit')) {
    function getEmployeesByUnit($unit_id = null)
    {
        $conn = getConnection();

        $sql = "
            SELECT e.*, u.name as unit_name
            FROM employees e
            LEFT JOIN units u ON e.unit_id = u.id
            WHERE e.employment_status = 'aktif'
        ";

        if ($unit_id !== null && $unit_id !== '' && (int)$unit_id > 0) {
            $sql .= " AND e.unit_id = " . (int)$unit_id;
        }

        $sql .= " ORDER BY e.full_name";

        $result = $conn->query($sql);
        $data = [];

        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
        }

        return $data;
    }
}