<?php
/**
 * S.P.M Dashboard - Global Functions & Helpers
 */

session_start();

require_once __DIR__ . '/database.php';

// ============================================================
// SECURITY HELPERS
// ============================================================
function generateCsrfToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function verifyCsrfToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

function sanitize($input) {
    return strip_tags(trim($input));
}

function sanitizeHtml($input) {
    return strip_tags($input, '<p><br><b><i><u><strong><em><ul><ol><li><h1><h2><h3><a><img>');
}

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

function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: ' . BASE_URL . 'modules/auth/login.php');
        exit;
    }
}

function hasRole($role) {
    if (!isLoggedIn()) return false;
    if (is_array($role)) {
        return in_array($_SESSION['user_role'], $role);
    }
    return $_SESSION['user_role'] === $role;
}

function isSuperAdmin() {
    return hasRole('superadmin');
}

function isAdmin() {
    return hasRole(['superadmin', 'admin_unit']);
}

function currentUserId() {
    return $_SESSION['user_id'] ?? null;
}

function currentUserName() {
    return $_SESSION['user_nama'] ?? 'Pengguna';
}

function currentUserRole() {
    return $_SESSION['user_role'] ?? null;
}

function currentUnitId() {
    return $_SESSION['unit_id'] ?? null;
}

// ============================================================
// FILE UPLOAD HELPERS
// ============================================================
function uploadImage($file, $folder = 'pegawai', $maxSize = 31457280) {
    $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    $allowedExt   = ['jpg','jpeg','png','gif','webp'];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errMsg = [
            UPLOAD_ERR_INI_SIZE   => 'Fail terlalu besar (php.ini limit).',
            UPLOAD_ERR_FORM_SIZE  => 'Fail terlalu besar (form limit).',
            UPLOAD_ERR_PARTIAL    => 'Fail tidak lengkap semasa upload.',
            UPLOAD_ERR_NO_FILE    => 'Tiada fail dipilih.',
            UPLOAD_ERR_NO_TMP_DIR => 'Tiada direktori sementara.',
            UPLOAD_ERR_CANT_WRITE => 'Gagal menulis ke cakera.',
        ];
        return ['success' => false, 'message' => $errMsg[$file['error']] ?? 'Ralat semasa upload fail (kod: '.$file['error'].').'];
    }

    if ($file['size'] > $maxSize) {
        return ['success' => false, 'message' => 'Saiz fail melebihi had (30MB).'];
    }

    // Guna finfo untuk semak MIME sebenar — lebih selamat dari $file['type']
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $realMime = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    if (!in_array($realMime, $allowedTypes)) {
        return ['success' => false, 'message' => 'Jenis fail tidak dibenarkan ('.$realMime.'). Hanya JPG, PNG, GIF, WEBP.'];
    }

    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedExt)) $ext = 'jpg';
    $filename = uniqid('img_', true) . '.' . $ext;
    $targetDir = UPLOAD_PATH . $folder . '/';

    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0777, true);
        chmod($targetDir, 0777);
    }

    if (!is_writable($targetDir)) {
        return ['success' => false, 'message' => 'Direktori upload tidak boleh ditulis: '.$targetDir];
    }

    $targetPath = $targetDir . $filename;

    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        chmod($targetPath, 0644);
        return ['success' => true, 'filename' => $filename, 'path' => $folder . '/' . $filename];
    }

    return ['success' => false, 'message' => 'Gagal memindahkan fail ke: '.$targetPath];
}

function uploadDocument($file, $folder = 'documents') {
    $allowedTypes = ['application/pdf', 'application/msword', 
                     'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                     'application/vnd.ms-excel',
                     'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                     'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errMsg = [
            UPLOAD_ERR_INI_SIZE   => 'Fail terlalu besar (php.ini limit).',
            UPLOAD_ERR_FORM_SIZE  => 'Fail terlalu besar (form limit).',
            UPLOAD_ERR_PARTIAL    => 'Fail tidak lengkap semasa upload.',
            UPLOAD_ERR_NO_FILE    => 'Tiada fail dipilih.',
            UPLOAD_ERR_NO_TMP_DIR => 'Tiada direktori sementara.',
            UPLOAD_ERR_CANT_WRITE => 'Gagal menulis ke cakera.',
        ];
        return ['success' => false, 'message' => $errMsg[$file['error']] ?? 'Ralat semasa upload fail (kod: '.$file['error'].').'];
    }
    
    if ($file['size'] > 31457280) { // 30MB
        return ['success' => false, 'message' => 'Saiz fail melebihi had (30MB).'];
    }
    
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $filename = uniqid('doc_', true) . '.' . $ext;
    $targetDir = UPLOAD_PATH . $folder . '/';
    
    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0755, true);
    }
    
    if (move_uploaded_file($file['tmp_name'], $targetDir . $filename)) {
        return ['success' => true, 'filename' => $filename, 'path' => $folder . '/' . $filename];
    }
    
    return ['success' => false, 'message' => 'Gagal memindahkan fail.'];
}

function deleteFile($path) {
    $fullPath = UPLOAD_PATH . $path;
    if (file_exists($fullPath) && $path !== 'pegawai/default.png') {
        return unlink($fullPath);
    }
    return false;
}

// ============================================================
// ACTIVITY LOG
// ============================================================
function logActivity($aksi, $modul, $rekod_id = null, $deskripsi = null) {
    global $pdo;
    try {
        $stmt = $pdo->prepare("INSERT INTO activity_log (user_id, aksi, modul, rekod_id, deskripsi, ip_address, user_agent) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            currentUserId(),
            $aksi,
            $modul,
            $rekod_id,
            $deskripsi,
            $_SERVER['REMOTE_ADDR'] ?? null,
            $_SERVER['HTTP_USER_AGENT'] ?? null
        ]);
    } catch (Exception $e) {
        // Silent fail for logging
    }
}

// ============================================================
// RESPONSE HELPERS
// ============================================================
function jsonResponse($success, $message = '', $data = []) {
    header('Content-Type: application/json');
    echo json_encode(['success' => $success, 'message' => $message, 'data' => $data]);
    exit;
}

function redirect($url) {
    header('Location: ' . $url);
    exit;
}

// ============================================================
// DATA HELPERS
// ============================================================
function getUnitColor($unitId) {
    $colors = [1 => '#0d6efd', 2 => '#dc3545', 3 => '#198754'];
    return $colors[$unitId] ?? '#6c757d';
}

function getStatusBadge($status) {
    return $status ? '<span class="badge bg-success">Aktif</span>' : '<span class="badge bg-secondary">Tidak Aktif</span>';
}

function timeAgo($datetime) {
    $time = time() - strtotime($datetime);
    if ($time < 60) return 'Baru sahaja';
    if ($time < 3600) return floor($time/60) . ' minit lalu';
    if ($time < 86400) return floor($time/3600) . ' jam lalu';
    if ($time < 2592000) return floor($time/86400) . ' hari lalu';
    return date('d M Y', strtotime($datetime));
}

function formatDate($date, $format = 'd M Y') {
    if (!$date) return '-';
    return date($format, strtotime($date));
}

function getPegawaiImage($gambar) {
    if ($gambar && file_exists(UPLOAD_PATH . 'pegawai/' . $gambar)) {
        return UPLOAD_URL . 'pegawai/' . $gambar;
    }
    return BASE_URL . 'assets/images/default-avatar.png';
}

// ============================================================
// SEKTOR LOGO HELPERS
// ============================================================
function getSektorData() {
    global $pdo;
    static $sektor = null;
    if ($sektor === null) {
        try {
            $sektor = $pdo->query("SELECT * FROM sektor WHERE status=1 ORDER BY id LIMIT 1")->fetch();
        } catch (Exception $e) {
            $sektor = ['nama_sektor'=>'Sektor Pembangunan Murid','kod'=>'SPM','logo'=>null];
        }
    }
    return $sektor;
}

function getSektorLogo($size='normal') {
    $s = getSektorData();
    
    // Prioritize logo_3 for loading size
    if ($size === 'loading' && !empty($s['logo_3']) && file_exists(UPLOAD_PATH . 'logo/' . $s['logo_3'])) {
        return '<img src="'.UPLOAD_URL.'logo/'.$s['logo_3'].'" style="height:100px;width:auto;object-fit:contain" alt="Logo Loading">';
    }
    
    if ($s && !empty($s['logo']) && file_exists(UPLOAD_PATH . 'logo/' . $s['logo'])) {
        $h = $size === 'small' ? '36px' : ($size === 'large' ? '80px' : ($size === 'loading' ? '100px' : '48px'));
        return '<img src="'.UPLOAD_URL.'logo/'.$s['logo'].'" style="height:'.$h.';width:auto;object-fit:contain" alt="Logo Sektor">';
    }
    // Fallback teks SPM
    if ($size === 'small') {
        return '<span style="font-size:1.1rem;font-weight:900;color:#fff;letter-spacing:1px">S.<span style="color:#cc0001">P</span>.M</span>';
    } elseif ($size === 'large' || $size === 'loading') {
        return '<span style="font-size:2.5rem;font-weight:900;color:#fff;letter-spacing:1px">S.<span style="color:#cc0001">P</span>.M</span>';
    }
    return '<span style="font-size:1.4rem;font-weight:900;color:#fff;letter-spacing:1px">S.<span style="color:#cc0001">P</span>.M</span>';
}
