<?php
require_once __DIR__ . '/app/bootstrap.php';
$user = require_system_admin();
$pageTitle = 'Korisnici';
$pageSubtitle = 'Administracija korisničkih naloga i uloga';

$errors = [];

function admin_avatar_upload_extension_from_image_type(int $imageType): ?string
{
    if ($imageType === IMAGETYPE_JPEG) {
        return 'jpg';
    }
    if ($imageType === IMAGETYPE_PNG) {
        return 'png';
    }
    return null;
}

function admin_delete_profile_photo_file(?string $relativePath): void
{
    $path = profile_photo_storage_path($relativePath);
    if ($path !== null) {
        @unlink($path);
    }
}

function admin_save_avatar_bytes(int $targetUserId, string $bytes, string $extension, array $targetUser): array
{
    $uploadDir = __DIR__ . '/uploads/avatars';
    if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true)) {
        return [false, 'Folder za fotografije nije moguće kreirati. Proverite dozvole na hostingu.'];
    }
    if (!is_writable($uploadDir)) {
        return [false, 'Folder za fotografije nije upisiv. Proverite dozvole za uploads/avatars.'];
    }

    $filename = 'user-' . $targetUserId . '-' . date('YmdHis') . '-' . bin2hex(random_bytes(4)) . '.' . $extension;
    $relativePath = 'uploads/avatars/' . $filename;
    $targetPath = $uploadDir . '/' . $filename;

    if (file_put_contents($targetPath, $bytes, LOCK_EX) === false) {
        return [false, 'Fotografija nije mogla biti sačuvana. Proverite upload podešavanja na hostingu.'];
    }
    @chmod($targetPath, 0644);

    $oldPhoto = trim((string)($targetUser['profile_photo'] ?? ''));
    try {
        $stmt = db()->prepare('UPDATE users SET profile_photo = ?, updated_at = ? WHERE id = ?');
        $stmt->execute([$relativePath, now_app_datetime_sql(), $targetUserId]);
    } catch (PDOException $e) {
        if (is_file($targetPath)) {
            @unlink($targetPath);
        }
        return [false, 'Baza nije ažurirana. Importujte poslednju upgrade SQL migraciju, pa pokušajte ponovo.'];
    }

    admin_delete_profile_photo_file($oldPhoto);
    return [true, $relativePath];
}

function admin_find_user(int $targetUserId): ?array
{
    if ($targetUserId <= 0) {
        return null;
    }
    try {
        $stmt = db()->prepare('SELECT id, name, email, is_system_admin, is_active, profile_photo FROM users WHERE id = ? LIMIT 1');
        $stmt->execute([$targetUserId]);
        $row = $stmt->fetch();
        return $row ?: null;
    } catch (PDOException $e) {
        return null;
    }
}

function admin_user_organization_label(array $listedUser): string
{
    $unit = user_organization_unit($listedUser);
    return $unit !== null ? (organization_unit_definitions()[$unit] ?? $unit) : '—';
}

function admin_validate_user_fields(string $name, string $email, array $profileFields): array
{
    $validationErrors = [];
    if (mb_strlen($name) < 2) {
        $validationErrors[] = 'Ime i prezime mora imati najmanje 2 karaktera.';
    } elseif (mb_strlen($name) > 120) {
        $validationErrors[] = 'Ime i prezime može imati najviše 120 karaktera.';
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL) || mb_strlen($email) > 190) {
        $validationErrors[] = 'Unesite validnu email adresu do 190 karaktera.';
    }

    $limits = [
        'job_title' => ['Radno mesto', 120],
        'phone' => ['Telefon', 60],
        'location' => ['Lokacija', 120],
        'manager_name' => ['Nadređeni', 120],
        'department' => ['Sektor', 120],
        'employee_code' => ['Šifra zaposlenog', 80],
    ];
    foreach ($limits as $field => [$label, $limit]) {
        if (mb_strlen((string)($profileFields[$field] ?? '')) > $limit) {
            $validationErrors[] = $label . ' može imati najviše ' . $limit . ' karaktera.';
        }
    }
    return $validationErrors;
}


if (is_post()) {
    validate_csrf();
    $action = (string)($_POST['action'] ?? '');

    if ($action === 'create') {
        $name = trim((string)($_POST['name'] ?? ''));
        $email = strtolower(trim((string)($_POST['email'] ?? '')));
        $password = (string)($_POST['password'] ?? '');
        $jobTitle = trim((string)($_POST['job_title'] ?? ''));
        $phone = trim((string)($_POST['phone'] ?? ''));
        $location = trim((string)($_POST['location'] ?? ''));
        $managerName = trim((string)($_POST['manager_name'] ?? ''));
        $department = trim((string)($_POST['department'] ?? ''));
        $employeeCode = trim((string)($_POST['employee_code'] ?? ''));
        $roleCodes = normalize_role_codes($_POST['roles'] ?? []);
        $isSystemAdmin = !empty($_POST['is_system_admin']) ? 1 : 0;
        $selectedBaseRoles = array_values(array_intersect($roleCodes, base_user_role_codes()));

        if (count($selectedBaseRoles) > 1) {
            $errors[] = 'Izaberite samo jednu osnovnu korisničku ulogu: USERF ili USERDS.';
        }
        $errors = array_merge($errors, validate_warehouse_role_consistency($roleCodes));
        $errors = array_merge($errors, admin_validate_user_fields($name, $email, [
            'job_title' => $jobTitle,
            'phone' => $phone,
            'location' => $location,
            'manager_name' => $managerName,
            'department' => $department,
            'employee_code' => $employeeCode,
        ]));
        if (strlen($password) < 10) {
            $errors[] = 'Lozinka mora imati najmanje 10 karaktera.';
        }
        if (!$errors) {
            try {
                db()->beginTransaction();
                $stmt = db()->prepare('INSERT INTO users (name, email, password_hash, is_system_admin, job_title, phone, location, manager_name, department, employee_code, is_active, must_change_password, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, NOW(), NOW())');
                $stmt->execute([$name, $email, password_hash($password, PASSWORD_DEFAULT), $isSystemAdmin, $jobTitle ?: null, $phone ?: null, $location ?: null, $managerName ?: null, $department ?: null, $employeeCode ?: null]);
                $newUserId = (int)db()->lastInsertId();
                sync_user_roles(db(), $newUserId, $roleCodes, (int)$user['id']);
                db()->commit();
                flash('success', 'Korisnik je kreiran.');
                redirect('users.php');
            } catch (Throwable $e) {
                if (db()->inTransaction()) {
                    db()->rollBack();
                }
                $errors[] = $e instanceof PDOException && (string)$e->getCode() === '23000'
                    ? 'Email adresa je već u upotrebi.'
                    : 'Korisnik nije kreiran. Proverite migraciju upgrade_v3_16.sql.';
            }
        }
    }

    if ($action === 'update') {
        $targetId = (int)($_POST['user_id'] ?? 0);
        $name = trim((string)($_POST['name'] ?? ''));
        $email = strtolower(trim((string)($_POST['email'] ?? '')));
        $roleCodes = normalize_role_codes($_POST['roles'] ?? []);
        $isSystemAdmin = !empty($_POST['is_system_admin']) ? 1 : 0;
        $selectedBaseRoles = array_values(array_intersect($roleCodes, base_user_role_codes()));
        $isActive = !empty($_POST['is_active']) ? 1 : 0;
        $mustChangePassword = !empty($_POST['must_change_password']) ? 1 : 0;
        $password = (string)($_POST['password'] ?? '');
        $jobTitle = trim((string)($_POST['job_title'] ?? ''));
        $phone = trim((string)($_POST['phone'] ?? ''));
        $location = trim((string)($_POST['location'] ?? ''));
        $managerName = trim((string)($_POST['manager_name'] ?? ''));
        $department = trim((string)($_POST['department'] ?? ''));
        $employeeCode = trim((string)($_POST['employee_code'] ?? ''));

        if (count($selectedBaseRoles) > 1) {
            $errors[] = 'Izaberite samo jednu osnovnu korisničku ulogu: USERF ili USERDS.';
        }
        $errors = array_merge($errors, validate_warehouse_role_consistency($roleCodes));
        $errors = array_merge($errors, admin_validate_user_fields($name, $email, [
            'job_title' => $jobTitle,
            'phone' => $phone,
            'location' => $location,
            'manager_name' => $managerName,
            'department' => $department,
            'employee_code' => $employeeCode,
        ]));
        $targetUser = admin_find_user($targetId);
        if (!$targetUser) {
            $errors[] = 'Korisnik nije pronađen.';
        }
        if ($targetId === (int)$user['id'] && $isActive === 0) {
            $errors[] = 'Ne možete deaktivirati sopstveni nalog.';
        }
        if ($targetUser && (int)$targetUser['is_system_admin'] === 1 && (int)$targetUser['is_active'] === 1 && ($isSystemAdmin !== 1 || $isActive === 0)) {
            $adminCountStmt = db()->prepare('SELECT COUNT(*) FROM users WHERE is_system_admin = 1 AND is_active = 1 AND id <> ?');
            $adminCountStmt->execute([$targetId]);
            if ((int)$adminCountStmt->fetchColumn() < 1) {
                $errors[] = 'Poslednji aktivni sistemski administrator ne može biti deaktiviran niti mu se može ukinuti administratorsko pravo.';
            }
        }

        if (!$errors) {
            if ($password !== '' && strlen($password) < 10) {
                $errors[] = 'Nova lozinka mora imati najmanje 10 karaktera.';
            }

            if (!$errors) {
                try {
                    db()->beginTransaction();
                    if ($password !== '') {
                        $stmt = db()->prepare('UPDATE users SET name = ?, email = ?, is_system_admin = ?, is_active = ?, must_change_password = ?, password_hash = ?, job_title = ?, phone = ?, location = ?, manager_name = ?, department = ?, employee_code = ?, updated_at = ? WHERE id = ?');
                        $stmt->execute([$name, $email, $isSystemAdmin, $isActive, $mustChangePassword, password_hash($password, PASSWORD_DEFAULT), $jobTitle ?: null, $phone ?: null, $location ?: null, $managerName ?: null, $department ?: null, $employeeCode ?: null, now_app_datetime_sql(), $targetId]);
                    } else {
                        $stmt = db()->prepare('UPDATE users SET name = ?, email = ?, is_system_admin = ?, is_active = ?, must_change_password = ?, job_title = ?, phone = ?, location = ?, manager_name = ?, department = ?, employee_code = ?, updated_at = ? WHERE id = ?');
                        $stmt->execute([$name, $email, $isSystemAdmin, $isActive, $mustChangePassword, $jobTitle ?: null, $phone ?: null, $location ?: null, $managerName ?: null, $department ?: null, $employeeCode ?: null, now_app_datetime_sql(), $targetId]);
                    }
                    if ($isActive === 0) {
                        $assignmentEvent = db()->prepare("INSERT INTO ticket_events (ticket_id, user_id, event_type, old_value, new_value, created_at)
                            SELECT id, ?, 'assigned_changed', CAST(assigned_to AS CHAR), NULL, NOW()
                            FROM tickets
                            WHERE assigned_to = ?");
                        $assignmentEvent->execute([(int)$user['id'], $targetId]);
                        $clearAssignment = db()->prepare('UPDATE tickets SET assigned_to = NULL, updated_at = NOW() WHERE assigned_to = ?');
                        $clearAssignment->execute([$targetId]);
                    }
                    sync_user_roles(db(), $targetId, $roleCodes, (int)$user['id']);
                    db()->commit();

                    flash('success', 'Korisnik je ažuriran.');
                    $returnSearch = mb_substr(trim((string)($_POST['return_q'] ?? '')), 0, 160);
                    $returnPage = max(1, (int)($_POST['return_page'] ?? 1));
                    redirect(page_url('users.php', ['q' => $returnSearch, 'page' => $returnPage]));
                } catch (Throwable $e) {
                    if (db()->inTransaction()) {
                        db()->rollBack();
                    }
                    $errors[] = $e instanceof PDOException && (string)$e->getCode() === '23000'
                        ? 'Korisnik nije ažuriran. Email adresa je možda već u upotrebi.'
                        : 'Korisnik nije ažuriran. Proverite migraciju i integritet uloga.';
                }
            }
        }
    }

    if ($action === 'admin_upload_photo') {
        $targetId = (int)($_POST['user_id'] ?? 0);
        $targetUser = admin_find_user($targetId);

        if (!$targetUser) {
            $errors[] = 'Korisnik nije pronađen.';
        } elseif (!isset($_FILES['profile_photo']) || !is_array($_FILES['profile_photo'])) {
            $errors[] = 'Niste izabrali fotografiju za upload.';
        } else {
            $file = $_FILES['profile_photo'];
            if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
                $errors[] = 'Upload fotografije nije uspeo. Proverite fajl i pokušajte ponovo.';
            } elseif ((int)($file['size'] ?? 0) <= 0) {
                $errors[] = 'Izabrani fajl je prazan.';
            } elseif ((int)$file['size'] > profile_photo_max_size_bytes()) {
                $errors[] = 'Fotografija može imati maksimalno 2 MB.';
            } else {
                $tmpPath = (string)($file['tmp_name'] ?? '');
                $originalInfo = @getimagesize($tmpPath);
                $originalExtension = is_array($originalInfo) ? admin_avatar_upload_extension_from_image_type((int)($originalInfo[2] ?? 0)) : null;

                if ($originalExtension === null) {
                    $errors[] = 'Dozvoljeni formati su JPG i PNG.';
                } else {
                    $croppedData = trim((string)($_POST['cropped_photo_data'] ?? ''));
                    $bytes = '';
                    $extension = $originalExtension;

                    if ($croppedData !== '') {
                        if (!preg_match('#^data:image/(jpeg|png);base64,([a-zA-Z0-9+/=\r\n]+)$#', $croppedData, $matches)) {
                            $errors[] = 'Preview fotografije nije validan. Izaberite sliku ponovo i pokušajte opet.';
                        } else {
                            $decoded = base64_decode(preg_replace('/\s+/', '', $matches[2]), true);
                            if ($decoded === false || $decoded === '') {
                                $errors[] = 'Preview fotografije nije moguće obraditi. Izaberite sliku ponovo i pokušajte opet.';
                            } elseif (strlen($decoded) > profile_photo_max_size_bytes()) {
                                $errors[] = 'Obrađena fotografija može imati maksimalno 2 MB.';
                            } else {
                                $croppedInfo = @getimagesizefromstring($decoded);
                                $croppedExtension = is_array($croppedInfo) ? admin_avatar_upload_extension_from_image_type((int)($croppedInfo[2] ?? 0)) : null;
                                if ($croppedExtension === null) {
                                    $errors[] = 'Obrađena fotografija nije validna. Dozvoljeni formati su JPG i PNG.';
                                } else {
                                    $bytes = $decoded;
                                    $extension = $croppedExtension;
                                }
                            }
                        }
                    } else {
                        $bytes = @file_get_contents($tmpPath);
                        if ($bytes === false || $bytes === '') {
                            $errors[] = 'Fotografiju nije moguće pročitati. Izaberite sliku ponovo i pokušajte opet.';
                        }
                    }

                    if (!$errors && $bytes !== '') {
                        [$saved, $result] = admin_save_avatar_bytes($targetId, $bytes, $extension, $targetUser);
                        if (!$saved) {
                            $errors[] = $result;
                        } else {
                            if ($targetId !== (int)$user['id']) {
                                notify_user($targetId, 'Profilna fotografija je ažurirana', 'Administrator je ažurirao profilnu fotografiju na vašem nalogu.', 'account.php#photo');
                            }
                            flash('success', 'Profilna fotografija zaposlenog je uspešno promenjena.');
                            redirect('users.php?profile=' . $targetId . '#profil-zaposlenog');
                        }
                    }
                }
            }
        }
    }

    if ($action === 'admin_delete_photo') {
        $targetId = (int)($_POST['user_id'] ?? 0);
        $targetUser = admin_find_user($targetId);
        if (!$targetUser) {
            $errors[] = 'Korisnik nije pronađen.';
        } else {
            $oldPhoto = trim((string)($targetUser['profile_photo'] ?? ''));
            try {
                $stmt = db()->prepare('UPDATE users SET profile_photo = NULL, updated_at = ? WHERE id = ?');
                $stmt->execute([now_app_datetime_sql(), $targetId]);
                admin_delete_profile_photo_file($oldPhoto);
                if ($targetId !== (int)$user['id']) {
                    notify_user($targetId, 'Profilna fotografija je uklonjena', 'Administrator je uklonio profilnu fotografiju sa vašeg naloga.', 'account.php#photo');
                }
                flash('success', 'Profilna fotografija zaposlenog je uklonjena.');
                redirect('users.php?profile=' . $targetId . '#profil-zaposlenog');
            } catch (PDOException $e) {
                $errors[] = 'Fotografija nije mogla biti uklonjena iz baze.';
            }
        }
    }

    if ($action === 'delete_user') {
        $targetId = (int)($_POST['user_id'] ?? 0);
        $targetUser = admin_find_user($targetId);
        $attachmentFiles = [];

        if (!$targetUser) {
            $errors[] = 'Korisnik nije pronađen.';
        } elseif ($targetId === (int)$user['id']) {
            $errors[] = 'Ne možete obrisati sopstveni nalog.';
        } else {
            $adminCountStmt = db()->prepare('SELECT COUNT(*) FROM users WHERE is_system_admin = 1 AND is_active = 1 AND id <> ?');
            $adminCountStmt->execute([$targetId]);
            $remainingAdmins = (int)$adminCountStmt->fetchColumn();
            if ((int)$targetUser['is_system_admin'] === 1 && $remainingAdmins < 1) {
                $errors[] = 'Nije dozvoljeno obrisati poslednji aktivni administratorski nalog.';
            }
        }

        if (!$errors && $targetUser) {
            $oldPhoto = trim((string)($targetUser['profile_photo'] ?? ''));
            try {
                $attachmentStmt = db()->prepare('SELECT DISTINCT a.stored_name
                    FROM ticket_attachments a
                    JOIN tickets t ON t.id = a.ticket_id
                    WHERE a.user_id = ? OR t.user_id = ?');
                $attachmentStmt->execute([$targetId, $targetId]);
                $attachmentFiles = $attachmentStmt->fetchAll();

                $equipmentStmt = db()->prepare('SELECT id, user_id, is_in_warehouse FROM equipment WHERE user_id = ?');
                $equipmentStmt->execute([$targetId]);
                $equipmentToRelease = $equipmentStmt->fetchAll();

                db()->beginTransaction();

                $stmt = db()->prepare('DELETE FROM notifications WHERE user_id = ?');
                $stmt->execute([$targetId]);

                foreach ($equipmentToRelease as $equipmentItem) {
                    record_equipment_assignment_event(
                        (int)$equipmentItem['id'],
                        $targetId,
                        (string)$targetUser['name'],
                        null,
                        null,
                        (int)($equipmentItem['is_in_warehouse'] ?? 0) === 1,
                        false,
                        (int)$user['id']
                    );
                    record_equipment_audit_event(
                        (int)$equipmentItem['id'],
                        (int)$user['id'],
                        'unassigned',
                        ['user_id' => $targetId, 'is_in_warehouse' => (int)($equipmentItem['is_in_warehouse'] ?? 0) === 1],
                        ['user_id' => null, 'is_in_warehouse' => false]
                    );
                }
                $stmt = db()->prepare("UPDATE equipment
                    SET user_id = NULL,
                        is_in_warehouse = 0,
                        assigned_at = NULL,
                        status = CASE WHEN status = 'assigned' THEN 'returned' ELSE status END,
                        updated_at = NOW()
                    WHERE user_id = ?");
                $stmt->execute([$targetId]);

                $stmt = db()->prepare('DELETE FROM ticket_events WHERE user_id = ?');
                $stmt->execute([$targetId]);

                $stmt = db()->prepare('DELETE FROM ticket_comments WHERE user_id = ?');
                $stmt->execute([$targetId]);

                $stmt = db()->prepare('DELETE FROM ticket_attachments WHERE user_id = ?');
                $stmt->execute([$targetId]);

                $stmt = db()->prepare('UPDATE tickets SET assigned_to = NULL, updated_at = ? WHERE assigned_to = ?');
                $stmt->execute([now_app_datetime_sql(), $targetId]);

                $stmt = db()->prepare('DELETE FROM tickets WHERE user_id = ?');
                $stmt->execute([$targetId]);

                $stmt = db()->prepare('DELETE FROM users WHERE id = ?');
                $stmt->execute([$targetId]);

                db()->commit();
                admin_delete_profile_photo_file($oldPhoto);
                foreach ($attachmentFiles as $attachmentFile) {
                    $attachmentPath = __DIR__ . '/uploads/tickets/' . basename((string)$attachmentFile['stored_name']);
                    if (is_file($attachmentPath)) {
                        @unlink($attachmentPath);
                    }
                }
                flash('success', 'Korisnički nalog je potpuno obrisan. Njegova oprema je sačuvana u evidenciji kao nedodeljena, dok su obrisani povezani obaveštenja, komentari, događaji i zahtevi.');
                redirect('users.php');
            } catch (Throwable $e) {
                if (db()->inTransaction()) {
                    db()->rollBack();
                }
                $errors[] = 'Nalog nije mogao biti obrisan. Proverite bazu i pokušajte ponovo.';
            }
        }
    }

}

$userSearch = mb_substr(trim((string)($_GET['q'] ?? '')), 0, 160);
$userPageSize = 10;
$userPage = max(1, (int)($_GET['page'] ?? 1));
$userWhere = ['1=1'];
$userParams = [];

if ($userSearch !== '') {
    $userWhere[] = '(LOCATE(?, u.name) > 0
        OR LOCATE(?, u.email) > 0
        OR LOCATE(?, u.job_title) > 0
        OR LOCATE(?, u.phone) > 0
        OR LOCATE(?, u.location) > 0
        OR LOCATE(?, u.manager_name) > 0
        OR LOCATE(?, u.department) > 0
        OR LOCATE(?, u.employee_code) > 0
        OR EXISTS (
            SELECT 1
            FROM user_roles ur_search
            JOIN roles r_search ON r_search.id = ur_search.role_id
            WHERE ur_search.user_id = u.id
              AND (LOCATE(?, r_search.name) > 0 OR LOCATE(?, r_search.role_code) > 0)
        ))';
    for ($i = 0; $i < 10; $i++) {
        $userParams[] = $userSearch;
    }
}

try {
    $countStmt = db()->prepare('SELECT COUNT(*) FROM users u WHERE ' . implode(' AND ', $userWhere));
    $countStmt->execute($userParams);
    $userTotalItems = (int)$countStmt->fetchColumn();
    $userTotalPages = max(1, (int)ceil($userTotalItems / $userPageSize));
    $userPage = min($userPage, $userTotalPages);
    $userOffset = ($userPage - 1) * $userPageSize;

    $sql = 'SELECT u.id, u.name, u.email, u.is_system_admin, u.is_active, u.must_change_password, u.created_at, u.updated_at, u.job_title, u.phone, u.location, u.manager_name, u.department, u.employee_code, u.last_login_at, u.profile_photo,
        COALESCE((SELECT GROUP_CONCAT(r.role_code ORDER BY r.sort_order SEPARATOR ",") FROM user_roles ur JOIN roles r ON r.id = ur.role_id WHERE ur.user_id = u.id), "") AS role_codes_csv
        FROM users u
        WHERE ' . implode(' AND ', $userWhere) . '
        ORDER BY u.name ASC
        LIMIT ' . $userPageSize . ' OFFSET ' . $userOffset;
    $stmt = db()->prepare($sql);
    $stmt->execute($userParams);
    $users = $stmt->fetchAll();
    foreach ($users as &$listedUser) {
        $listedUser['role_codes'] = array_values(array_filter(explode(',', (string)$listedUser['role_codes_csv'])));
    }
    unset($listedUser);

    $statsStmt = db()->query('SELECT COUNT(*) AS total,
        COALESCE(SUM(is_active = 1), 0) AS active,
        COALESCE(SUM(is_active = 0), 0) AS inactive,
        COALESCE(SUM(is_system_admin = 1), 0) AS admins
        FROM users');
    $statsRow = $statsStmt->fetch() ?: [];
    $processingRoleCodes = processing_role_codes();
    $agentCount = 0;
    if ($processingRoleCodes) {
        $agentPlaceholders = implode(',', array_fill(0, count($processingRoleCodes), '?'));
        $agentStmt = db()->prepare('SELECT COUNT(DISTINCT ur.user_id)
            FROM user_roles ur
            JOIN roles r ON r.id = ur.role_id
            WHERE r.role_code IN (' . $agentPlaceholders . ')');
        $agentStmt->execute($processingRoleCodes);
        $agentCount = (int)$agentStmt->fetchColumn();
    }
    $userStats = [
        'total' => (int)($statsRow['total'] ?? 0),
        'active' => (int)($statsRow['active'] ?? 0),
        'inactive' => (int)($statsRow['inactive'] ?? 0),
        'admins' => (int)($statsRow['admins'] ?? 0),
        'agents' => $agentCount,
    ];
} catch (PDOException $e) {
    exit('Administracija korisnika zahteva import migracije upgrade_v3_16.sql.');
}

$createRoleCodes = ['USERF'];
$createFormSubmitted = is_post() && (string)($_POST['action'] ?? '') === 'create';
$createValues = $createFormSubmitted ? $_POST : [];
if ($createFormSubmitted) {
    $createRoleCodes = normalize_role_codes($_POST['roles'] ?? []);
}


$selectedProfile = null;
$selectedProfileEquipment = [];
$selectedProfileTickets = [];
$selectedProfileRoleEvents = [];
$profileId = (int)($_GET['profile'] ?? 0);
if ($profileId > 0) {
    $profileStmt = db()->prepare('SELECT u.id, u.name, u.email, u.is_system_admin, u.is_active, u.must_change_password, u.created_at, u.updated_at, u.job_title, u.phone, u.location, u.manager_name, u.department, u.employee_code, u.last_login_at, u.profile_photo,
        COALESCE((SELECT GROUP_CONCAT(r.role_code ORDER BY r.sort_order SEPARATOR ",") FROM user_roles ur JOIN roles r ON r.id = ur.role_id WHERE ur.user_id = u.id), "") AS role_codes_csv
        FROM users u WHERE u.id = ? LIMIT 1');
    $profileStmt->execute([$profileId]);
    $selectedProfile = $profileStmt->fetch() ?: null;
    if ($selectedProfile) {
        $selectedProfile['role_codes'] = array_values(array_filter(explode(',', (string)$selectedProfile['role_codes_csv'])));
    }

    if ($selectedProfile) {
        try {
            $equipmentStmt = db()->prepare("SELECT asset_type, asset_name, serial_no, inventory_no, assigned_at, status, notes FROM equipment WHERE user_id = ? ORDER BY FIELD(asset_type, 'Laptop', 'Telefon', 'Tablet', 'Monitor', 'Docking station', 'Ostalo'), asset_name ASC");
            $equipmentStmt->execute([$profileId]);
            $selectedProfileEquipment = $equipmentStmt->fetchAll();
        } catch (Throwable $e) {
            $selectedProfileEquipment = [];
        }

        try {
            $ticketStmt = db()->prepare('SELECT id, ticket_no, title, status, priority, updated_at FROM tickets WHERE user_id = ? ORDER BY updated_at DESC LIMIT 6');
            $ticketStmt->execute([$profileId]);
            $selectedProfileTickets = $ticketStmt->fetchAll();
        } catch (Throwable $e) {
            $selectedProfileTickets = [];
        }
        try {
            $roleEventStmt = db()->prepare('SELECT ure.action, ure.created_at, r.role_code, r.name AS role_name, actor.name AS actor_name
                FROM user_role_events ure
                JOIN roles r ON r.id = ure.role_id
                LEFT JOIN users actor ON actor.id = ure.changed_by
                WHERE ure.target_user_id = ?
                ORDER BY ure.created_at DESC, ure.id DESC
                LIMIT 20');
            $roleEventStmt->execute([$profileId]);
            $selectedProfileRoleEvents = $roleEventStmt->fetchAll();
        } catch (Throwable $e) {
            $selectedProfileRoleEvents = [];
        }
    }
}

require_once __DIR__ . '/app/header.php';
?>
<?php if ($selectedProfile): ?>
<section class="card card-pad admin-profile-card" id="profil-zaposlenog">
    <div class="section-heading">
        <div>
            <span class="badge">Profil zaposlenog</span>
            <h2><?= e($selectedProfile['name']) ?></h2>
            <p>Kompletan administrativni pregled naloga, kontakt podataka, profilne fotografije, opreme i poslednjih zahteva.</p>
        </div>
        <a class="button button-light" href="<?= e(page_url('users.php', ['q' => $userSearch, 'page' => $userPage])) ?>">Zatvori pregled</a>
    </div>
    <?php foreach ($errors as $error): ?>
        <div class="alert alert-danger"><?= e($error) ?></div>
    <?php endforeach; ?>
    <div class="admin-profile-grid">
        <div class="admin-profile-main">
            <?= user_avatar_html($selectedProfile, 'employee-avatar') ?>
            <div>
                <strong><?= e($selectedProfile['name']) ?></strong>
                <span><?= e(user_roles_summary($selectedProfile)) ?> · <?= (int)$selectedProfile['is_active'] === 1 ? 'Aktivan nalog' : 'Neaktivan nalog' ?></span>
                <small><?= e(employee_value($selectedProfile['job_title'] ?? null)) ?></small>
            </div>
        </div>
        <div class="employee-info-grid admin-profile-info">
            <div class="employee-info-item"><span class="info-icon">📍</span><div><small>Lokacija</small><strong><?= e(employee_value($selectedProfile['location'] ?? null)) ?></strong></div></div>
            <div class="employee-info-item"><span class="info-icon info-navy">▦</span><div><small>Sektor</small><strong><?= e(employee_value($selectedProfile['department'] ?? null)) ?></strong></div></div>
            <div class="employee-info-item"><span class="info-icon info-red">👤</span><div><small>Nadređeni</small><strong><?= e(employee_value($selectedProfile['manager_name'] ?? null)) ?></strong></div></div>
            <div class="employee-info-item copy-item"><span class="info-icon info-green">✉</span><div><small>E-pošta</small><strong><?= e($selectedProfile['email']) ?></strong></div><button type="button" class="copy-button" data-copy-value="<?= e($selectedProfile['email']) ?>">Kopiraj</button></div>
            <div class="employee-info-item copy-item"><span class="info-icon info-purple">☎</span><div><small>Telefon</small><strong><?= e(employee_value($selectedProfile['phone'] ?? null)) ?></strong></div><?php if (!empty($selectedProfile['phone'])): ?><button type="button" class="copy-button" data-copy-value="<?= e($selectedProfile['phone']) ?>">Kopiraj</button><?php endif; ?></div>
            <div class="employee-info-item"><span class="info-icon info-orange">◷</span><div><small>Poslednja prijava</small><strong><?= e(format_datetime($selectedProfile['last_login_at'] ?? null)) ?></strong></div></div>
            <div class="employee-info-item"><span class="info-icon info-navy">#</span><div><small>Šifra zaposlenog</small><strong><?= e(employee_value($selectedProfile['employee_code'] ?? null)) ?></strong></div></div>
            <div class="employee-info-item"><span class="info-icon info-green">✓</span><div><small>Kreiran nalog</small><strong><?= e(format_datetime($selectedProfile['created_at'] ?? null)) ?></strong></div></div>
        </div>
    </div>
    <div class="admin-profile-management-grid">
        <article class="admin-profile-tool-card">
            <div class="tool-card-heading">
                <span class="badge">Fotografija</span>
                <h3>Promena profilne fotografije</h3>
                <p>Administrator može da postavi novu JPG/PNG fotografiju do 2 MB i izabere kadar za prikaz.</p>
            </div>
            <form method="post" enctype="multipart/form-data" class="stacked-form profile-photo-form admin-photo-form" id="adminProfilePhotoForm">
                <?= csrf_field() ?>
                <input type="hidden" name="action" value="admin_upload_photo">
                <input type="hidden" name="user_id" value="<?= (int)$selectedProfile['id'] ?>">
                <input type="hidden" name="cropped_photo_data" id="croppedPhotoData" value="">

                <div class="profile-upload-field">
                    <span class="form-label">Nova fotografija zaposlenog</span>
                    <label class="file-dropzone file-dropzone-compact" id="profilePhotoDropzone" for="profilePhotoInput">
                        <input id="profilePhotoInput" class="file-drop-input" type="file" name="profile_photo" accept="image/jpeg,image/png,.jpg,.jpeg,.png" required>
                        <span class="file-drop-icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24" width="26" height="26" focusable="false"><path d="M12 3.5a5.2 5.2 0 0 1 5.1 4.2A4.8 4.8 0 0 1 17 17.3h-3.2v-2H17a2.8 2.8 0 0 0 .1-5.6l-1.5-.1-.3-1.5a3.4 3.4 0 0 0-6.6-.5l-.4 1.2-1.2.2a3.1 3.1 0 0 0 .4 6.2h2.8v2H7.5A5.1 5.1 0 0 1 6.9 7 5.4 5.4 0 0 1 12 3.5Zm0 6.1 3.1 3.1-1.4 1.4-1.7-1.7v6.1h-2v-6.1l-1.7 1.7-1.4-1.4L12 9.6Z" fill="currentColor"/></svg>
                        </span>
                        <span class="file-drop-copy">
                            <strong>Kliknite za izbor fotografije</strong>
                            <small>ili prevucite JPG/PNG fotografiju ovde · maksimalno 2 MB</small>
                        </span>
                        <span class="file-drop-name" id="profilePhotoFileName">Nije izabrana fotografija</span>
                    </label>
                </div>

                <div class="photo-cropper" id="profileCropper" hidden>
                    <div class="photo-cropper-grid">
                        <div>
                            <div class="cropper-stage" id="profileCropStage" aria-label="Preview i izbor kadra fotografije">
                                <img id="profileCropImage" alt="Izabrana profilna fotografija">
                                <span class="cropper-frame" aria-hidden="true"></span>
                            </div>
                            <p class="cropper-help">Prevucite fotografiju i podesite uvećanje. Vidljivi kvadrat biće sačuvan kao profilna fotografija.</p>
                            <label class="range-label">Uvećanje
                                <input id="profileCropZoom" type="range" min="1" max="3" step="0.01" value="1">
                            </label>
                        </div>
                        <div class="cropper-result">
                            <span>Pregled</span>
                            <img id="profileCropResult" alt="Pregled odabranog kadra">
                        </div>
                    </div>
                </div>

                <div class="inline-actions">
                    <button class="button button-primary" type="submit">Sačuvaj fotografiju</button>
                    <?php if (trim((string)($selectedProfile['profile_photo'] ?? '')) !== ''): ?>
                        <button class="button button-light" type="submit" form="adminDeletePhotoForm">Ukloni fotografiju</button>
                    <?php endif; ?>
                </div>
            </form>
            <?php if (trim((string)($selectedProfile['profile_photo'] ?? '')) !== ''): ?>
                <form id="adminDeletePhotoForm" method="post" data-confirm="Da li želite da uklonite profilnu fotografiju ovog zaposlenog?">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="admin_delete_photo">
                    <input type="hidden" name="user_id" value="<?= (int)$selectedProfile['id'] ?>">
                </form>
            <?php endif; ?>
        </article>

        <article class="admin-profile-tool-card danger-zone-card">
            <div class="tool-card-heading">
                <span class="badge badge-danger">Opasna zona</span>
                <h3>Brisanje naloga</h3>
                <p>Trajno briše korisnički nalog, njegovu opremu, obaveštenja, komentare, događaje i zahteve. Ova akcija se ne može poništiti.</p>
            </div>
            <?php if ((int)$selectedProfile['id'] === (int)$user['id']): ?>
                <p class="empty-state">Ne možete obrisati sopstveni nalog.</p>
            <?php else: ?>
                <form method="post" data-confirm="Trajno brisanje naloga briše korisnika i povezane podatke. Da li ste sigurni?">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="delete_user">
                    <input type="hidden" name="user_id" value="<?= (int)$selectedProfile['id'] ?>">
                    <button class="button button-danger" type="submit">Trajno obriši nalog</button>
                </form>
            <?php endif; ?>
        </article>
    </div>

    <div class="admin-profile-sections">
        <div>
            <h3>Oprema zaposlenog</h3>
            <?php if (!$selectedProfileEquipment): ?>
                <p class="empty-state">Nema evidentirane opreme za ovog zaposlenog.</p>
            <?php else: ?>
                <div class="equipment-list compact-equipment-list">
                    <?php foreach ($selectedProfileEquipment as $asset): ?>
                        <div class="equipment-item">
                            <span class="equipment-icon"><?= equipment_icon_html((string)$asset['asset_type']) ?></span>
                            <div>
                                <strong><?= e($asset['asset_name']) ?></strong>
                                <small><?= e($asset['asset_type']) ?> · Ser. br.: <?= e($asset['serial_no'] ?: '—') ?> · Inv. br.: <?= e($asset['inventory_no'] ?: '—') ?></small>
                            </div>
                            <span class="pill <?= e(equipment_status_class($asset['status'])) ?>"><?= e(equipment_status_label($asset['status'])) ?></span>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        <div>
            <h3>Poslednji zahtevi</h3>
            <?php if (!$selectedProfileTickets): ?>
                <p class="empty-state">Nema evidentiranih zahteva za ovog zaposlenog.</p>
            <?php else: ?>
                <div class="mini-ticket-list">
                    <?php foreach ($selectedProfileTickets as $ticket): ?>
                        <a href="<?= e(url('ticket_view.php?id=' . (int)$ticket['id'])) ?>">
                            <strong><?= e($ticket['ticket_no']) ?> · <?= e($ticket['title']) ?></strong>
                            <span><?= e(status_label($ticket['status'])) ?> · <?= e(priority_label($ticket['priority'])) ?> · <?= e(format_datetime($ticket['updated_at'])) ?></span>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        <div>
            <h3>Promene uloga</h3>
            <?php if (!$selectedProfileRoleEvents): ?>
                <p class="empty-state">Nema evidentiranih promena uloga.</p>
            <?php else: ?>
                <ul class="timeline">
                    <?php foreach ($selectedProfileRoleEvents as $roleEvent): ?>
                        <li>
                            <strong><?= $roleEvent['action'] === 'added' ? 'Dodata uloga' : 'Uklonjena uloga' ?></strong>
                            <span><?= e($roleEvent['role_name']) ?> (<?= e($roleEvent['role_code']) ?>)</span>
                            <span><?= e($roleEvent['actor_name'] ?: 'Sistemska migracija') ?> · <?= e(format_datetime($roleEvent['created_at'])) ?></span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </div>
    </div>
</section>
<?php elseif ($profileId > 0): ?>
    <div class="alert alert-warning">Traženi korisnik nije pronađen.</div>
<?php endif; ?>
<section class="user-layout user-admin-layout">
    <article class="card user-admin-panel">
        <div class="section-heading admin-users-heading">
            <div>
                <span class="badge">Administracija</span>
                <h2>Korisnici</h2>
                <p>Centralno upravljanje korisničkim nalozima, ulogama, statusom, kontakt podacima i resetom lozinke.</p>
            </div>
        </div>

        <?php if (!$selectedProfile): ?>
            <?php foreach ($errors as $error): ?>
                <div class="alert alert-danger"><?= e($error) ?></div>
            <?php endforeach; ?>
        <?php endif; ?>

        <details class="admin-create-user-card" <?= $createFormSubmitted && $errors ? 'open' : '' ?>>
            <summary class="button button-primary">Novi korisnik</summary>
            <div class="admin-create-user-body">
                <div>
                    <span class="badge">Novi korisnik</span>
                    <h3>Kreiranje korisnika</h3>
                    <p class="muted small">Nalog se kreira aktivan, a korisnik mora da promeni privremenu lozinku pri prvoj prijavi.</p>
                </div>
                <form method="post" class="admin-create-user-form">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="create">
                    <label>Ime i prezime
                        <input type="text" name="name" required minlength="2" maxlength="120" autocomplete="name" value="<?= e($createValues['name'] ?? '') ?>">
                    </label>
                    <label>Email adresa
                        <input type="email" name="email" required maxlength="190" autocomplete="email" value="<?= e($createValues['email'] ?? '') ?>">
                    </label>
                    <label>Privremena lozinka
                        <input type="password" name="password" required minlength="10" autocomplete="new-password">
                        <small class="form-help">Najmanje 10 karaktera. Korisnik će je promeniti pri prvoj prijavi.</small>
                    </label>
                    <fieldset class="admin-role-fieldset admin-create-role-fieldset">
                        <legend>Dodeljene uloge</legend>
                        <?php foreach (business_role_definitions() as $roleCode => $roleName): ?>
                            <label class="inline-check"><input type="checkbox" name="roles[]" value="<?= e($roleCode) ?>" <?= safe_checked(in_array($roleCode, $createRoleCodes, true)) ?>> <?= e($roleName) ?> (<?= e($roleCode) ?>)</label>
                        <?php endforeach; ?>
                    </fieldset>
                    <label class="admin-check-label">Sistemska administracija
                        <span class="inline-check"><input type="checkbox" name="is_system_admin" value="1" <?= safe_checked(!empty($createValues['is_system_admin'])) ?>> Sistemski administrator</span>
                        <small class="form-help">Dodelite samo korisniku koji treba pristup celoj administraciji.</small>
                    </label>
                    <label>Radno mesto
                        <input type="text" name="job_title" maxlength="120" value="<?= e($createValues['job_title'] ?? '') ?>" placeholder="ICT Coordinator">
                    </label>
                    <label>Telefon
                        <input type="text" name="phone" maxlength="60" value="<?= e($createValues['phone'] ?? '') ?>" placeholder="+381...">
                    </label>
                    <label>Lokacija
                        <input type="text" name="location" maxlength="120" value="<?= e($createValues['location'] ?? '') ?>" placeholder="Centrala, Beograd">
                    </label>
                    <label>Nadređeni
                        <input type="text" name="manager_name" maxlength="120" value="<?= e($createValues['manager_name'] ?? '') ?>" placeholder="Ime i prezime">
                    </label>
                    <label>Sektor
                        <input type="text" name="department" maxlength="120" value="<?= e($createValues['department'] ?? '') ?>" placeholder="ICT & Infrastruktura">
                    </label>
                    <label>Šifra zaposlenog
                        <input type="text" name="employee_code" maxlength="80" value="<?= e($createValues['employee_code'] ?? '') ?>" placeholder="Opcionalno">
                    </label>
                    <div class="inline-actions admin-create-user-actions">
                        <button class="button button-primary" type="submit">Kreiraj korisnika</button>
                    </div>
                </form>
            </div>
        </details>

        <div class="admin-user-stats">
            <div><span>Ukupno</span><strong><?= (int)$userStats['total'] ?></strong></div>
            <div><span>Aktivni</span><strong><?= (int)$userStats['active'] ?></strong></div>
            <div><span>Administratori</span><strong><?= (int)$userStats['admins'] ?></strong></div>
            <div><span>Članovi podrške</span><strong><?= (int)$userStats['agents'] ?></strong></div>
        </div>

        <div class="admin-users-toolbar">
            <form method="get" class="admin-user-search-form">
                <label class="admin-user-search">Pretraga korisnika
                    <input type="search" name="q" value="<?= e($userSearch) ?>" placeholder="Ime, email, sektor, lokacija, uloga...">
                </label>
                <div class="admin-user-search-actions">
                    <button class="button button-blue button-small" type="submit">Pretraži</button>
                    <?php if ($userSearch !== ''): ?>
                        <a class="button button-light button-small" href="<?= e(url('users.php')) ?>">Resetuj</a>
                    <?php endif; ?>
                </div>
            </form>
            <span class="muted small">Kliknite na „Uredi nalog” za izmenu imena, email adrese i profilnih podataka.</span>
        </div>

        <?php if (!$users): ?>
            <p class="empty-state admin-user-no-results">Nema korisnika koji odgovaraju pretrazi.</p>
        <?php else: ?>
        <div class="table-wrap admin-users-table-wrap">
            <table class="admin-users-table">
                <thead>
                    <tr>
                        <th>Korisnik</th>
                        <th>Uloga</th>
                        <th>Entitet</th>
                        <th>Status</th>
                        <th>Kreiran</th>
                        <th>Akcije</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($users as $item): ?>
                    <tr class="admin-user-row">
                        <td>
                            <div class="admin-user-identity">
                                <?= user_avatar_html($item, 'avatar') ?>
                                <div>
                                    <strong><?= e($item['name']) ?></strong>
                                    <span><?= e($item['email']) ?></span>
                                </div>
                            </div>
                        </td>
                        <td><span class="admin-user-role-summary"><?= e(user_roles_summary($item)) ?></span></td>
                        <td><?= e(admin_user_organization_label($item)) ?></td>
                        <td><span class="badge <?= (int)$item['is_active'] === 1 ? 'badge-success' : 'badge-warning' ?>"><?= (int)$item['is_active'] === 1 ? 'Aktivan' : 'Neaktivan' ?></span></td>
                        <td><time datetime="<?= e((string)$item['created_at']) ?>"><?= e(format_datetime($item['created_at'])) ?></time></td>
                        <td><a class="button button-light button-small" href="<?= e(page_url('users.php', ['profile' => (int)$item['id'], 'q' => $userSearch, 'page' => $userPage])) ?>#profil-zaposlenog">Profil</a></td>
                    </tr>
                    <tr class="admin-user-edit-row">
                        <td colspan="6">
                            <details class="admin-user-edit">
                                <summary>Uredi nalog</summary>
                                <form id="user-form-<?= (int)$item['id'] ?>" method="post" class="admin-user-form">
                                    <?= csrf_field() ?>
                                    <input type="hidden" name="action" value="update">
                                    <input type="hidden" name="user_id" value="<?= (int)$item['id'] ?>">
                                    <input type="hidden" name="return_q" value="<?= e($userSearch) ?>">
                                    <input type="hidden" name="return_page" value="<?= (int)$userPage ?>">
                            <div class="admin-user-edit-grid">
                                <label class="admin-user-edit-primary-field">Ime i prezime
                                    <input type="text" name="name" required minlength="2" maxlength="120" value="<?= e($item['name']) ?>" placeholder="Ime i prezime">
                                </label>
                                <label class="admin-user-edit-primary-field">Email adresa
                                    <input type="email" name="email" required maxlength="190" value="<?= e($item['email']) ?>" placeholder="ime.prezime@domen.rs">
                                </label>
                                <fieldset class="admin-role-fieldset">
                                    <legend>Dodeljene uloge</legend>
                                    <?php foreach (business_role_definitions() as $roleCode => $roleName): ?>
                                        <label class="inline-check"><input type="checkbox" name="roles[]" value="<?= e($roleCode) ?>" <?= safe_checked(in_array($roleCode, $item['role_codes'] ?? [], true)) ?>> <?= e($roleName) ?> (<?= e($roleCode) ?>)</label>
                                    <?php endforeach; ?>
                                </fieldset>
                                <label class="admin-check-label">Sistemska administracija
                                    <span class="inline-check"><input type="checkbox" name="is_system_admin" value="1" <?= safe_checked((int)($item['is_system_admin'] ?? 0) === 1) ?>> Sistemski administrator</span>
                                    <small>Ovo pravo je odvojeno od poslovnih uloga.</small>
                                </label>
                                <label class="admin-check-label">Status naloga
                                    <span class="inline-check"><input type="checkbox" name="is_active" value="1" <?= safe_checked((int)$item['is_active'] === 1) ?>> Aktivan nalog</span>
                                </label>
                                <label>Nova lozinka
                                    <input type="password" name="password" minlength="10" autocomplete="new-password" placeholder="Ostaviti prazno ako se ne menja">
                                </label>
                                <label class="admin-check-label">Promena lozinke pri prijavi
                                    <span class="inline-check"><input type="checkbox" name="must_change_password" value="1" <?= safe_checked((int)($item['must_change_password'] ?? 0) === 1) ?>> Korisnik mora da postavi novu lozinku</span>
                                </label>
                                <label>Radno mesto
                                    <input type="text" name="job_title" maxlength="120" value="<?= e($item['job_title']) ?>" placeholder="ICT Coordinator">
                                </label>
                                <label>Telefon
                                    <input type="text" name="phone" maxlength="60" value="<?= e($item['phone']) ?>" placeholder="+381...">
                                </label>
                                <label>Lokacija
                                    <input type="text" name="location" maxlength="120" value="<?= e($item['location']) ?>" placeholder="Centrala, Beograd">
                                </label>
                                <label>Nadređeni
                                    <input type="text" name="manager_name" maxlength="120" value="<?= e($item['manager_name']) ?>" placeholder="Ime i prezime">
                                </label>
                                <label>Sektor
                                    <input type="text" name="department" maxlength="120" value="<?= e($item['department']) ?>" placeholder="ICT & Infrastruktura">
                                </label>
                                <label>Šifra zaposlenog
                                    <input type="text" name="employee_code" maxlength="80" value="<?= e($item['employee_code']) ?>" placeholder="Opcionalno">
                                </label>
                            </div>
                            <div class="inline-actions admin-user-edit-actions">
                                <button class="button button-primary" type="submit">Sačuvaj izmene naloga</button>
                                <a class="button button-light" href="<?= e(page_url('users.php', ['profile' => (int)$item['id'], 'q' => $userSearch, 'page' => $userPage])) ?>#profil-zaposlenog">Otvori kompletan profil</a>
                            </div>
                                </form>
                                <?php if ((int)$item['id'] !== (int)$user['id']): ?>
                                    <form method="post" class="admin-user-delete-form" data-confirm="Trajno brisanje naloga briše korisnika i povezane podatke. Da li ste sigurni?">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="action" value="delete_user">
                                        <input type="hidden" name="user_id" value="<?= (int)$item['id'] ?>">
                                        <button class="button button-danger button-small" type="submit">Obriši nalog</button>
                                    </form>
                                <?php endif; ?>
                            </details>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>

        <?php
            $userRangeStart = $userTotalItems > 0 ? (($userPage - 1) * $userPageSize) + 1 : 0;
            $userRangeEnd = min($userTotalItems, $userPage * $userPageSize);
        ?>
        <div class="pagination-summary">Prikaz <?= (int)$userRangeStart ?>–<?= (int)$userRangeEnd ?> od <?= (int)$userTotalItems ?> korisnika<?= $userSearch !== '' ? ' za izabranu pretragu' : '' ?>.</div>
        <?php if ($userTotalPages > 1): ?>
            <nav class="pagination" aria-label="Paginacija korisnika">
                <?php if ($userPage > 1): ?>
                    <a class="pagination-link" href="<?= e(page_url('users.php', ['q' => $userSearch, 'page' => $userPage - 1])) ?>">← Prethodna</a>
                <?php else: ?>
                    <span class="pagination-link is-disabled" aria-disabled="true">← Prethodna</span>
                <?php endif; ?>
                <div class="pagination-pages">
                    <?php foreach (pagination_page_numbers($userPage, $userTotalPages) as $pageNumber): ?>
                        <?php if ($pageNumber === null): ?>
                            <span class="pagination-ellipsis">…</span>
                        <?php elseif ($pageNumber === $userPage): ?>
                            <span class="pagination-link is-current" aria-current="page"><?= (int)$pageNumber ?></span>
                        <?php else: ?>
                            <a class="pagination-link" href="<?= e(page_url('users.php', ['q' => $userSearch, 'page' => $pageNumber])) ?>"><?= (int)$pageNumber ?></a>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
                <?php if ($userPage < $userTotalPages): ?>
                    <a class="pagination-link" href="<?= e(page_url('users.php', ['q' => $userSearch, 'page' => $userPage + 1])) ?>">Sledeća →</a>
                <?php else: ?>
                    <span class="pagination-link is-disabled" aria-disabled="true">Sledeća →</span>
                <?php endif; ?>
            </nav>
        <?php endif; ?>
    </article>
</section>
<?php require_once __DIR__ . '/app/footer.php'; ?>
