<?php
require_once __DIR__ . '/app/bootstrap.php';
$user = require_equipment_manager();
$pageTitle = 'Oprema zaposlenih';
$pageSubtitle = 'Pretraga, dodela, magacin, ažuriranje i izvoz ICT opreme';
$errors = [];

$equipmentFilters = normalize_equipment_filters($_GET);
$filterUserId = (int)$equipmentFilters['user_id'];
$filterStatus = (string)$equipmentFilters['status'];
$filterAssetType = (string)$equipmentFilters['asset_type'];
$filterWarehouse = (string)$equipmentFilters['warehouse'];
$filterOrganizationUnit = (string)$equipmentFilters['organization_unit'];
$managerOrganizationUnit = equipment_manager_organization_unit($user);
if (!is_system_admin($user)) {
    $filterOrganizationUnit = (string)$managerOrganizationUnit;
    $equipmentFilters['organization_unit'] = $filterOrganizationUnit;
}
$q = (string)$equipmentFilters['q'];
$equipmentPageSizes = [10, 25, 50];
$equipmentPageSize = (int)($_GET['per_page'] ?? 10);
if (!in_array($equipmentPageSize, $equipmentPageSizes, true)) {
    $equipmentPageSize = 10;
}
$equipmentPage = max(1, (int)($_GET['page'] ?? 1));

try {
    $usersSql = 'SELECT u.id, u.name, u.email, u.department, u.location,
        CASE
            WHEN SUM(r.role_code = "USERF") > 0 AND SUM(r.role_code = "USERDS") = 0 THEN "F"
            WHEN SUM(r.role_code = "USERDS") > 0 AND SUM(r.role_code = "USERF") = 0 THEN "DS"
            ELSE NULL
        END AS organization_unit
        FROM users u
        LEFT JOIN user_roles ur ON ur.user_id = u.id
        LEFT JOIN roles r ON r.id = ur.role_id AND r.is_active = 1
        WHERE u.is_active = 1';
    $usersParams = [];
    if (!is_system_admin($user)) {
        $baseRole = $managerOrganizationUnit === 'DS' ? 'USERDS' : 'USERF';
        $usersSql .= ' AND EXISTS (
            SELECT 1 FROM user_roles ur_scope
            JOIN roles r_scope ON r_scope.id = ur_scope.role_id AND r_scope.is_active = 1
            WHERE ur_scope.user_id = u.id AND r_scope.role_code = ?
        )';
        $usersParams[] = $baseRole;
    }
    $usersSql .= ' GROUP BY u.id, u.name, u.email, u.department, u.location ORDER BY u.name ASC';
    $usersStmt = db()->prepare($usersSql);
    $usersStmt->execute($usersParams);
    $allUsers = $usersStmt->fetchAll();
} catch (Throwable $e) {
    $allUsers = [];
}

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

    if ($action === 'create' || $action === 'update') {
        $equipmentId = (int)($_POST['equipment_id'] ?? 0);
        $oldItem = null;
        if ($action === 'update') {
            [$itemScopeSql, $itemScopeParams] = equipment_access_scope_sql($user, 'e');
            $equipmentCheck = db()->prepare('SELECT e.*, u.name AS user_name
                FROM equipment e LEFT JOIN users u ON u.id = e.user_id
                WHERE e.id = ? AND ' . $itemScopeSql . ' LIMIT 1');
            $equipmentCheck->execute(array_merge([$equipmentId], $itemScopeParams));
            $oldItem = $equipmentCheck->fetch() ?: null;
            if (!$oldItem) {
                http_response_code(404);
                exit('Stavka opreme nije pronađena.');
            }
        }

        if (is_system_admin($user)) {
            $organizationUnit = strtoupper(trim((string)($_POST['organization_unit'] ?? '')));
        } elseif ($action === 'create') {
            $organizationUnit = (string)$managerOrganizationUnit;
        } else {
            // Ne verujemo POST vrednosti: magacioner zadržava pravno lice zapisa iz baze.
            $organizationUnit = strtoupper(trim((string)($oldItem['organization_unit'] ?? '')));
        }
        $submittedUserId = (int)($_POST['user_id'] ?? 0);
        $userId = $submittedUserId > 0 ? $submittedUserId : null;
        $assetType = trim((string)($_POST['asset_type'] ?? 'Laptop'));
        $assetName = trim((string)($_POST['asset_name'] ?? ''));
        $serialNo = trim((string)($_POST['serial_no'] ?? ''));
        $inventoryNo = trim((string)($_POST['inventory_no'] ?? ''));
        $assignedAt = trim((string)($_POST['assigned_at'] ?? ''));
        $status = trim((string)($_POST['status'] ?? 'assigned'));
        $requestedWarehouse = isset($_POST['is_in_warehouse']) && (string)$_POST['is_in_warehouse'] === '1';
        $isInWarehouse = $userId === null ? $requestedWarehouse : false;
        $notes = trim((string)($_POST['notes'] ?? ''));
        $newUserName = null;

        if (!isset(organization_unit_definitions()[$organizationUnit])) {
            $errors[] = 'Izaberite validno pravno lice opreme.';
        }
        if ($oldItem && is_system_admin($user)
            && (string)$oldItem['organization_unit'] !== $organizationUnit
            && $oldItem['user_id'] !== null) {
            $errors[] = 'Pre promene pravnog lica oprema mora prvo biti razdužena.';
        }

        if ($isInWarehouse) {
            $userId = null;
            $assignedAt = '';
            // Postojeći model nema poseban status "nedodeljeno". Warehouse stavka
            // ne sme ostati prikazana kao Dodeljeno, pa se koristi postojeći Vraćeno.
            if ($status === 'assigned') {
                $status = 'returned';
            }
        } elseif ($userId === null) {
            $assignedAt = '';
            if ($status === 'assigned') {
                $errors[] = 'Status Dodeljeno zahteva izabranog korisnika. Za lager označite Magacin ili izaberite drugi postojeći status.';
            }
        }

        if (!array_key_exists($assetType, equipment_types())) {
            $errors[] = 'Izaberite validan tip opreme.';
        }
        if (mb_strlen($assetName) < 2) {
            $errors[] = 'Naziv opreme mora imati najmanje 2 karaktera.';
        }
        if (mb_strlen($assetName) > 160 || mb_strlen($serialNo) > 120 || mb_strlen($inventoryNo) > 120 || mb_strlen($notes) > 5000) {
            $errors[] = 'Jedno od tekstualnih polja opreme je duže od dozvoljenog.';
        }
        if (!array_key_exists($status, equipment_statuses())) {
            $errors[] = 'Izaberite validan status opreme.';
        }
        if ($assignedAt !== '') {
            $parsedDate = DateTimeImmutable::createFromFormat('!Y-m-d', $assignedAt);
            if (!$parsedDate || $parsedDate->format('Y-m-d') !== $assignedAt) {
                $errors[] = 'Datum dodele mora biti validan datum u formatu YYYY-MM-DD.';
            }
        }
        if ($action === 'update' && $equipmentId <= 0) {
            $errors[] = 'Stavka opreme nije pronađena.';
        }
        if (!$errors && $userId !== null) {
            $assignmentUser = user_with_organization_unit($userId);
            if (!$assignmentUser) {
                $errors[] = 'Izabrani korisnik ne postoji ili nije aktivan.';
            } elseif (($assignmentUser['organization_unit'] ?? null) !== $organizationUnit) {
                $errors[] = 'Oprema može biti dodeljena samo korisniku istog pravnog lica.';
            } else {
                $newUserName = (string)$assignmentUser['name'];
            }
        }
        if (!$errors && equipment_inventory_number_exists($organizationUnit, $inventoryNo, $action === 'update' ? $equipmentId : 0)) {
            $errors[] = 'Inventarski broj već postoji za izabrano pravno lice.';
        }

        if (!$errors) {
            $pdo = db();
            $pdo->beginTransaction();
            try {
                if ($action === 'create') {
                    $stmt = $pdo->prepare('INSERT INTO equipment (organization_unit, user_id, is_in_warehouse, asset_type, asset_name, serial_no, inventory_no, assigned_at, status, notes, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())');
                    $stmt->execute([$organizationUnit, $userId, $isInWarehouse ? 1 : 0, $assetType, $assetName, $serialNo ?: null, $inventoryNo ?: null, $assignedAt ?: null, $status, $notes ?: null]);
                    $equipmentId = (int)$pdo->lastInsertId();
                    record_equipment_assignment_event($equipmentId, null, null, $userId, $newUserName, false, $isInWarehouse, (int)$user['id']);
                    record_equipment_audit_event($equipmentId, (int)$user['id'], 'created', null, [
                        'organization_unit' => $organizationUnit, 'user_id' => $userId,
                        'inventory_no' => $inventoryNo ?: null, 'asset_type' => $assetType, 'asset_name' => $assetName,
                    ]);
                    if ($userId !== null) {
                        record_equipment_audit_event($equipmentId, (int)$user['id'], 'assigned', null, ['user_id' => $userId]);
                    }
                    $pdo->commit();

                    if ($userId !== null) {
                        notify_user($userId, 'Dodeljena vam je oprema', $assetType . ': ' . $assetName . ' je evidentiran kao vaša oprema.', 'dashboard.php');
                        flash('success', 'Oprema je dodeljena korisniku.');
                    } elseif ($isInWarehouse) {
                        flash('success', 'Oprema je evidentirana u magacinu.');
                    } else {
                        flash('success', 'Oprema je evidentirana bez dodeljenog korisnika.');
                    }
                    redirect('equipment.php');
                }

                if ($action === 'update' && $equipmentId > 0 && $oldItem) {
                    [$updateScopeSql, $updateScopeParams] = equipment_access_scope_sql($user, 'equipment');
                    $stmt = $pdo->prepare('UPDATE equipment SET organization_unit = ?, user_id = ?, is_in_warehouse = ?, asset_type = ?, asset_name = ?, serial_no = ?, inventory_no = ?, assigned_at = ?, status = ?, notes = ?, updated_at = NOW() WHERE id = ? AND ' . $updateScopeSql);
                    $stmt->execute(array_merge([$organizationUnit, $userId, $isInWarehouse ? 1 : 0, $assetType, $assetName, $serialNo ?: null, $inventoryNo ?: null, $assignedAt ?: null, $status, $notes ?: null, $equipmentId], $updateScopeParams));

                    $oldUserId = $oldItem['user_id'] !== null ? (int)$oldItem['user_id'] : null;
                    $oldWarehouse = (int)($oldItem['is_in_warehouse'] ?? 0) === 1;
                    if ($oldUserId !== $userId || $oldWarehouse !== $isInWarehouse) {
                        record_equipment_assignment_event(
                            $equipmentId,
                            $oldUserId,
                            $oldItem['user_name'] ?? null,
                            $userId,
                            $newUserName,
                            $oldWarehouse,
                            $isInWarehouse,
                            (int)$user['id']
                        );
                        $assignmentAction = $userId === null ? 'unassigned' : ($oldUserId === null ? 'assigned' : 'reassigned');
                        record_equipment_audit_event($equipmentId, (int)$user['id'], $assignmentAction,
                            ['user_id' => $oldUserId, 'is_in_warehouse' => $oldWarehouse],
                            ['user_id' => $userId, 'is_in_warehouse' => $isInWarehouse]);
                    }
                    $oldAudit = [
                        'organization_unit' => $oldItem['organization_unit'] ?? null,
                        'inventory_no' => $oldItem['inventory_no'] ?? null,
                        'asset_type' => $oldItem['asset_type'] ?? null,
                        'asset_name' => $oldItem['asset_name'] ?? null,
                        'serial_no' => $oldItem['serial_no'] ?? null,
                        'status' => $oldItem['status'] ?? null,
                        'notes' => $oldItem['notes'] ?? null,
                    ];
                    $newAudit = [
                        'organization_unit' => $organizationUnit, 'inventory_no' => $inventoryNo ?: null,
                        'asset_type' => $assetType, 'asset_name' => $assetName, 'serial_no' => $serialNo ?: null,
                        'status' => $status, 'notes' => $notes ?: null,
                    ];
                    record_equipment_audit_event($equipmentId, (int)$user['id'], 'updated', $oldAudit, $newAudit);
                    if (($oldItem['organization_unit'] ?? null) !== $organizationUnit) {
                        record_equipment_audit_event($equipmentId, (int)$user['id'], 'organization_unit_changed', $oldItem['organization_unit'] ?? null, $organizationUnit);
                    }
                    if (($oldItem['inventory_no'] ?? null) !== ($inventoryNo ?: null)) {
                        record_equipment_audit_event($equipmentId, (int)$user['id'], 'inventory_no_changed', $oldItem['inventory_no'] ?? null, $inventoryNo ?: null);
                    }
                    $pdo->commit();

                    if ($userId !== null) {
                        notify_user($userId, 'Ažurirana je vaša oprema', $assetType . ': ' . $assetName . ' je ažuriran u evidenciji.', 'dashboard.php');
                    }
                    flash('success', 'Oprema je ažurirana.');
                    redirect('equipment.php');
                }
                $pdo->rollBack();
            } catch (Throwable $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                throw $e;
            }
        }
    }

    if ($action === 'delete') {
        $equipmentId = (int)($_POST['equipment_id'] ?? 0);
        if ($equipmentId > 0) {
            [$deleteScopeSql, $deleteScopeParams] = equipment_access_scope_sql($user, 'e');
            $lookup = db()->prepare('SELECT e.* FROM equipment e WHERE e.id = ? AND ' . $deleteScopeSql . ' LIMIT 1');
            $lookup->execute(array_merge([$equipmentId], $deleteScopeParams));
            $item = $lookup->fetch();
            if (!$item) {
                http_response_code(404);
                exit('Stavka opreme nije pronađena.');
            }
            $pdo = db();
            $pdo->beginTransaction();
            try {
                record_equipment_audit_event($equipmentId, (int)$user['id'], 'deleted', $item, null);
                $stmt = $pdo->prepare('DELETE FROM equipment WHERE id = ? AND organization_unit = ?');
                $stmt->execute([$equipmentId, $item['organization_unit']]);
                $pdo->commit();
            } catch (Throwable $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                throw $e;
            }
            if ($item && $item['user_id'] !== null) {
                notify_user((int)$item['user_id'], 'Oprema je uklonjena iz evidencije', $item['asset_type'] . ': ' . $item['asset_name'] . ' više nije evidentiran kao vaša oprema.', 'dashboard.php');
            }
            flash('success', 'Oprema je uklonjena iz evidencije.');
            redirect('equipment.php');
        }
    }
}
[$equipmentWhereSql, $equipmentParams] = equipment_filter_sql($equipmentFilters, $user);

$equipmentStats = [
    'total' => 0,
    'assigned' => 0,
    'repair' => 0,
    'returned' => 0,
    'retired' => 0,
    'users_count' => 0,
];
$equipment = [];
$equipmentByUser = [];
$equipmentTotalPages = 1;
$equipmentOffset = 0;

try {
    $statsSql = 'SELECT COUNT(*) AS total,
        COALESCE(SUM(e.status = "assigned"), 0) AS assigned,
        COALESCE(SUM(e.status = "repair"), 0) AS repair,
        COALESCE(SUM(e.status = "returned"), 0) AS returned,
        COALESCE(SUM(e.status = "retired"), 0) AS retired,
        COUNT(DISTINCT e.user_id) AS users_count
        FROM equipment e
        LEFT JOIN users u ON u.id = e.user_id
        WHERE ' . $equipmentWhereSql;
    $statsStmt = db()->prepare($statsSql);
    $statsStmt->execute($equipmentParams);
    $statsRow = $statsStmt->fetch() ?: [];
    foreach (array_keys($equipmentStats) as $statsKey) {
        $equipmentStats[$statsKey] = (int)($statsRow[$statsKey] ?? 0);
    }

    $equipmentTotalPages = max(1, (int)ceil($equipmentStats['total'] / $equipmentPageSize));
    $equipmentPage = min($equipmentPage, $equipmentTotalPages);
    $equipmentOffset = ($equipmentPage - 1) * $equipmentPageSize;

    $sql = 'SELECT e.*, u.name AS user_name, u.email AS user_email, u.department AS user_department, u.location AS user_location
            FROM equipment e
            LEFT JOIN users u ON u.id = e.user_id
            WHERE ' . $equipmentWhereSql . '
            ORDER BY CASE WHEN u.name IS NULL THEN 1 ELSE 0 END, u.name ASC, FIELD(e.status, "assigned", "repair", "returned", "retired"), FIELD(e.asset_type, "Laptop", "Telefon", "Tablet", "Monitor", "Docking station", "Ostalo"), e.asset_name ASC
            LIMIT ' . $equipmentPageSize . ' OFFSET ' . $equipmentOffset;
    $stmt = db()->prepare($sql);
    $stmt->execute($equipmentParams);
    $equipment = $stmt->fetchAll();
} catch (Throwable $e) {
    $equipment = [];
    $errors[] = 'Tabela za opremu nije dostupna. Importujte 20260823_magacioner_organization_unit.sql.';
}

foreach ($equipment as $item) {
    $groupKey = $item['user_id'] !== null ? 'user:' . (int)$item['user_id'] : 'unassigned';
    $equipmentByUser[$groupKey]['user'] = [
        'name' => $item['user_name'] ?: 'Nije dodeljeno',
        'email' => $item['user_email'] ?: 'Oprema bez dodeljenog korisnika',
        'department' => $item['user_department'],
        'location' => $item['user_location'],
    ];
    $equipmentByUser[$groupKey]['items'][] = $item;
}

$exportQuery = http_build_query([
    'q' => $q,
    'user_id' => $filterUserId ?: '',
    'asset_type' => $filterAssetType,
    'status' => $filterStatus,
    'warehouse' => $filterWarehouse,
    'organization_unit' => $filterOrganizationUnit,
]);
$equipmentPaginationParams = [
    'q' => $q,
    'user_id' => $filterUserId ?: '',
    'asset_type' => $filterAssetType,
    'status' => $filterStatus,
    'warehouse' => $filterWarehouse,
    'organization_unit' => $filterOrganizationUnit,
    'per_page' => $equipmentPageSize,
];

require_once __DIR__ . '/app/header.php';
?>
<section class="equipment-admin-page">
    <section class="equipment-hero card card-pad">
        <div class="section-heading">
            <div>
                <span class="badge">Inventar</span>
                <h2>Oprema zaposlenih</h2>
                <p>Pretraga po korisniku, tipu opreme, serijskom/inventarskom broju, magacinu i izvoz trenutnog stanja za Excel.</p>
            </div>
            <div class="equipment-hero-actions">
                <a class="button button-blue" href="<?= e(url('equipment_export.php' . ($exportQuery ? '?' . $exportQuery : ''))) ?>">Izvoz u Excel</a>
                <a class="button button-light" href="<?= e(url('equipment.php')) ?>">Resetuj filtere</a>
            </div>
        </div>
        <?php foreach ($errors as $error): ?>
            <div class="alert alert-danger"><?= e($error) ?></div>
        <?php endforeach; ?>
        <div class="metric-grid equipment-metrics">
            <div class="metric-card"><span>Ukupno stavki</span><strong><?= (int)$equipmentStats['total'] ?></strong><small>Prema aktivnim filterima</small></div>
            <div class="metric-card"><span>Dodeljeno</span><strong><?= (int)$equipmentStats['assigned'] ?></strong><small>Trenutno zaduženo</small></div>
            <div class="metric-card"><span>Na servisu</span><strong><?= (int)$equipmentStats['repair'] ?></strong><small>Oprema van upotrebe</small></div>
            <div class="metric-card"><span>Korisnici</span><strong><?= (int)$equipmentStats['users_count'] ?></strong><small>Imaju evidentiranu opremu</small></div>
        </div>
    </section>

    <section class="equipment-control-grid">
        <article class="card card-pad equipment-filter-card">
            <div class="section-heading admin-equipment-toolbar">
                <div>
                    <span class="badge">Pretraga</span>
                    <h3>Filteri opreme</h3>
                </div>
                <a class="button button-primary" href="<?= e(url('equipment.php?create=1#dodaj-opremu')) ?>" data-equipment-create-trigger>Dodaj opremu</a>
            </div>
            <form method="get" class="equipment-filter-form">
                <label>Pretraga
                    <input type="search" name="q" value="<?= e($q) ?>" placeholder="Laptop, serijski broj, inventarski broj, korisnik...">
                </label>
                <label>Korisnik
                    <select name="user_id">
                        <option value="">Svi korisnici</option>
                        <?php foreach ($allUsers as $employee): ?>
                            <option value="<?= (int)$employee['id'] ?>" <?= safe_selected($filterUserId, $employee['id']) ?>><?= e($employee['name']) ?> · <?= e($employee['email']) ?> · <?= e(equipment_organization_unit_label($employee['organization_unit'] ?? null)) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <?php if (is_system_admin($user)): ?>
                <label>Pravno lice
                    <select name="organization_unit">
                        <option value="">Sva</option>
                        <?php foreach (organization_unit_definitions() as $value => $label): ?>
                            <option value="<?= e($value) ?>" <?= safe_selected($filterOrganizationUnit, $value) ?>><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <?php else: ?>
                <label>Pravno lice
                    <input type="text" value="<?= e(equipment_organization_unit_label($managerOrganizationUnit)) ?>" readonly>
                </label>
                <?php endif; ?>
                <label>Tip opreme
                    <select name="asset_type">
                        <option value="">Svi tipovi</option>
                        <?php foreach (equipment_filter_types() as $value => $label): ?>
                            <option value="<?= e($value) ?>" <?= safe_selected($filterAssetType, $value) ?>><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <label>Status
                    <select name="status">
                        <option value="">Svi statusi</option>
                        <?php foreach (equipment_statuses() as $value => $label): ?>
                            <option value="<?= e($value) ?>" <?= safe_selected($filterStatus, $value) ?>><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <label>Magacin
                    <select name="warehouse">
                        <option value="">Sve</option>
                        <option value="1" <?= safe_selected($filterWarehouse, '1') ?>>U magacinu</option>
                        <option value="0" <?= safe_selected($filterWarehouse, '0') ?>>Van magacina</option>
                    </select>
                </label>
                <label>Stavki po stranici
                    <select name="per_page">
                        <?php foreach ($equipmentPageSizes as $pageSizeOption): ?>
                            <option value="<?= (int)$pageSizeOption ?>" <?= safe_selected($equipmentPageSize, $pageSizeOption) ?>><?= (int)$pageSizeOption ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <div class="inline-actions">
                    <button class="button button-blue" type="submit">Primeni filter</button>
                    <a class="button button-light" href="<?= e(url('equipment.php')) ?>">Resetuj</a>
                </div>
            </form>
        </article>

        <details class="card equipment-create-card equipment-create-disclosure" id="dodaj-opremu" <?= ((string)($_GET['create'] ?? '') === '1' || (is_post() && (string)($_POST['action'] ?? '') === 'create' && $errors)) ? 'open' : '' ?>>
            <summary class="button button-primary">Dodaj opremu</summary>
            <div class="equipment-create-body card-pad">
                <span class="badge">Nova oprema</span>
                <h3>Dodaj opremu</h3>
            <form method="post" class="stacked-form compact-form equipment-create-form">
                <?= csrf_field() ?>
                <input type="hidden" name="action" value="create">
                <?php if (is_system_admin($user)): ?>
                <label>Pravno lice
                    <select name="organization_unit" required>
                        <?php foreach (organization_unit_definitions() as $value => $label): ?>
                            <option value="<?= e($value) ?>" <?= safe_selected($_POST['organization_unit'] ?? 'F', $value) ?>><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <?php else: ?>
                <label>Pravno lice
                    <input type="text" value="<?= e(equipment_organization_unit_label($managerOrganizationUnit)) ?>" readonly>
                </label>
                <?php endif; ?>
                <label>Korisnik
                    <select name="user_id">
                        <option value="">Nije dodeljeno</option>
                        <?php foreach ($allUsers as $employee): ?>
                            <option value="<?= (int)$employee['id'] ?>"><?= e($employee['name']) ?> · <?= e($employee['email']) ?> · <?= e(equipment_organization_unit_label($employee['organization_unit'] ?? null)) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <label class="inline-check equipment-warehouse-check"><input type="checkbox" name="is_in_warehouse" value="1"> Oprema se nalazi u magacinu</label>
                <div class="two-col-form">
                    <label>Tip opreme
                        <select name="asset_type">
                            <?php foreach (equipment_types() as $value => $label): ?>
                                <option value="<?= e($value) ?>"><?= e($label) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <label>Status
                        <select name="status">
                            <?php foreach (equipment_statuses() as $value => $label): ?>
                                <option value="<?= e($value) ?>"><?= e($label) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                </div>
                <label>Naziv opreme
                    <input type="text" name="asset_name" required placeholder="HP EliteBook 450 G6">
                </label>
                <div class="two-col-form">
                    <label>Serijski broj
                        <input type="text" name="serial_no" placeholder="3107FA123">
                    </label>
                    <label>Inventarski broj
                        <input type="text" name="inventory_no" placeholder="INV-3107FA123">
                    </label>
                </div>
                <label>Datum dodele
                    <input type="date" name="assigned_at" value="<?= e(date('Y-m-d')) ?>">
                </label>
                <label>Napomena
                    <textarea name="notes" rows="3" placeholder="Interna napomena, lokacija ili stanje opreme."></textarea>
                </label>
                <button class="button button-primary" type="submit">Sačuvaj opremu</button>
            </form>
            </div>
        </details>
    </section>

    <section class="card card-pad equipment-by-user-card">
        <div class="section-heading">
            <div>
                <span class="badge">Po korisniku</span>
                <h2>Ko je šta zadužio</h2>
                <p>Sažetak opreme grupisan po zaposlenom za stavke prikazane na trenutnoj stranici.</p>
            </div>
        </div>
        <?php if (!$equipmentByUser): ?>
            <p class="empty-state">Nema opreme koja odgovara izabranim filterima.</p>
        <?php else: ?>
            <div class="equipment-user-grid">
                <?php foreach ($equipmentByUser as $group): ?>
                    <article class="equipment-user-card">
                        <div class="equipment-user-head">
                            <div>
                                <strong><?= e($group['user']['name']) ?></strong>
                                <span><?= e($group['user']['email']) ?></span>
                            </div>
                            <em><?= count($group['items']) ?> stavki</em>
                        </div>
                        <div class="equipment-user-items">
                            <?php foreach ($group['items'] as $asset): ?>
                                <div class="equipment-user-item">
                                    <span class="equipment-icon"><?= equipment_icon_html((string)$asset['asset_type']) ?></span>
                                    <div>
                                        <strong><?= e($asset['asset_name']) ?></strong>
                                        <small><?= e(equipment_organization_unit_label($asset['organization_unit'] ?? null)) ?> · <?= e($asset['asset_type']) ?> · Ser. <?= e($asset['serial_no'] ?: '—') ?> · Inv. <?= e($asset['inventory_no'] ?: '—') ?></small>
                                    </div>
                                    <span class="equipment-item-badges">
                                        <?php if ((int)$asset['is_in_warehouse'] === 1): ?><span class="pill equipment-warehouse">Magacin</span><?php endif; ?>
                                        <span class="pill <?= e(equipment_status_class($asset['status'])) ?>"><?= e(equipment_status_label($asset['status'])) ?></span>
                                    </span>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>

    <section class="card card-pad equipment-table-card">
        <div class="section-heading">
            <div>
                <span class="badge">Spisak</span>
                <h2>Celokupan spisak opreme</h2>
                <p>Pregled filtriranog inventara sa server-side paginacijom, izmenom i uklanjanjem iz evidencije.</p>
            </div>
            <a class="button button-blue" href="<?= e(url('equipment_export.php' . ($exportQuery ? '?' . $exportQuery : ''))) ?>">Izvezi trenutno stanje</a>
        </div>
        <?php if (!$equipment): ?>
            <p class="empty-state">Nema opreme koja odgovara izabranim filterima.</p>
        <?php else: ?>
            <div class="table-wrap equipment-table-wrap">
                <table class="equipment-table">
                    <thead>
                    <tr>
                        <th>Korisnik</th>
                        <th>Pravno lice</th>
                        <th>Oprema</th>
                        <th>Identifikatori</th>
                        <th>Status</th>
                        <th>Datum dodele</th>
                        <th>Napomena</th>
                        <th>Ažurirano</th>
                        <th>Akcije</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($equipment as $item): ?>
                        <tr>
                            <td>
                                <strong><?= e($item['user_name'] ?: 'Nije dodeljeno') ?></strong>
                                <?php if ($item['user_email']): ?><small><?= e($item['user_email']) ?></small><?php endif; ?>
                                <small><?= e(employee_value($item['user_department'] ?? null)) ?> · <?= e(employee_value($item['user_location'] ?? null)) ?></small>
                            </td>
                            <td><strong><?= e(equipment_organization_unit_label($item['organization_unit'] ?? null)) ?></strong></td>
                            <td>
                                <div class="equipment-table-asset">
                                    <span class="equipment-icon"><?= equipment_icon_html((string)$item['asset_type']) ?></span>
                                    <div>
                                        <strong><?= e($item['asset_name']) ?></strong>
                                        <small><?= e($item['asset_type']) ?></small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <small>Ser. br.: <?= e($item['serial_no'] ?: '—') ?></small><br>
                                <small>Inv. br.: <?= e($item['inventory_no'] ?: '—') ?></small>
                            </td>
                            <td>
                                <div class="equipment-status-stack">
                                    <?php if ((int)$item['is_in_warehouse'] === 1): ?><span class="pill equipment-warehouse">Magacin</span><?php endif; ?>
                                    <span class="pill <?= e(equipment_status_class($item['status'])) ?>"><?= e(equipment_status_label($item['status'])) ?></span>
                                </div>
                            </td>
                            <td><?= e($item['assigned_at'] ? (new DateTimeImmutable((string)$item['assigned_at']))->format('d.m.Y.') : '—') ?></td>
                            <td class="equipment-notes-cell"><?= e(employee_value($item['notes'] ?? null)) ?></td>
                            <td><?= e(format_datetime($item['updated_at'] ?? null)) ?></td>
                            <td>
                                <details class="equipment-row-editor">
                                    <summary>Uredi</summary>
                                    <form method="post" class="equipment-row-form">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="equipment_id" value="<?= (int)$item['id'] ?>">
                                        <?php if (is_system_admin($user)): ?>
                                        <label>Pravno lice
                                            <select name="organization_unit" required>
                                                <?php foreach (organization_unit_definitions() as $value => $label): ?>
                                                    <option value="<?= e($value) ?>" <?= safe_selected($item['organization_unit'] ?? '', $value) ?>><?= e($label) ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </label>
                                        <?php else: ?>
                                        <label>Pravno lice
                                            <input type="text" value="<?= e(equipment_organization_unit_label($item['organization_unit'] ?? null)) ?>" readonly>
                                        </label>
                                        <?php endif; ?>
                                        <label>Korisnik
                                            <select name="user_id">
                                                <option value="" <?= $item['user_id'] === null ? 'selected' : '' ?>>Nije dodeljeno</option>
                                                <?php foreach ($allUsers as $employee): ?>
                                                    <option value="<?= (int)$employee['id'] ?>" <?= safe_selected($item['user_id'], $employee['id']) ?>><?= e($employee['name']) ?> · <?= e($employee['email']) ?> · <?= e(equipment_organization_unit_label($employee['organization_unit'] ?? null)) ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </label>
                                        <label class="inline-check equipment-warehouse-check"><input type="checkbox" name="is_in_warehouse" value="1" <?= safe_checked((int)$item['is_in_warehouse'] === 1) ?>> Oprema se nalazi u magacinu</label>
                                        <div class="two-col-form">
                                            <label>Tip
                                                <select name="asset_type" required>
                                                    <?php foreach (equipment_types() as $value => $label): ?>
                                                        <option value="<?= e($value) ?>" <?= safe_selected($item['asset_type'], $value) ?>><?= e($label) ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </label>
                                            <label>Status
                                                <select name="status">
                                                    <?php foreach (equipment_statuses() as $value => $label): ?>
                                                        <option value="<?= e($value) ?>" <?= safe_selected($item['status'], $value) ?>><?= e($label) ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </label>
                                        </div>
                                        <label>Naziv opreme
                                            <input type="text" name="asset_name" required value="<?= e($item['asset_name']) ?>">
                                        </label>
                                        <div class="two-col-form">
                                            <label>Serijski broj
                                                <input type="text" name="serial_no" value="<?= e($item['serial_no']) ?>">
                                            </label>
                                            <label>Inventarski broj
                                                <input type="text" name="inventory_no" value="<?= e($item['inventory_no']) ?>">
                                            </label>
                                        </div>
                                        <label>Datum dodele
                                            <input type="date" name="assigned_at" value="<?= e($item['assigned_at']) ?>">
                                        </label>
                                        <label>Napomena
                                            <textarea name="notes" rows="2"><?= e($item['notes']) ?></textarea>
                                        </label>
                                        <div class="inline-actions equipment-admin-actions">
                                            <button class="button button-blue" type="submit" name="action" value="update">Sačuvaj</button>
                                            <button class="button button-danger" type="submit" name="action" value="delete" data-confirm="Da li ste sigurni da želite da uklonite ovu opremu iz evidencije?">Ukloni</button>
                                        </div>
                                    </form>
                                </details>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>

        <?php
            $equipmentRangeStart = $equipmentStats['total'] > 0 ? $equipmentOffset + 1 : 0;
            $equipmentRangeEnd = min($equipmentStats['total'], $equipmentOffset + count($equipment));
        ?>
        <div class="pagination-summary">Prikaz <?= (int)$equipmentRangeStart ?>–<?= (int)$equipmentRangeEnd ?> od <?= (int)$equipmentStats['total'] ?> stavki prema aktivnim filterima.</div>
        <?php if ($equipmentTotalPages > 1): ?>
            <nav class="pagination" aria-label="Paginacija opreme">
                <?php if ($equipmentPage > 1): ?>
                    <a class="pagination-link" href="<?= e(page_url('equipment.php', array_merge($equipmentPaginationParams, ['page' => $equipmentPage - 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($equipmentPage, $equipmentTotalPages) as $pageNumber): ?>
                        <?php if ($pageNumber === null): ?>
                            <span class="pagination-ellipsis">…</span>
                        <?php elseif ($pageNumber === $equipmentPage): ?>
                            <span class="pagination-link is-current" aria-current="page"><?= (int)$pageNumber ?></span>
                        <?php else: ?>
                            <a class="pagination-link" href="<?= e(page_url('equipment.php', array_merge($equipmentPaginationParams, ['page' => $pageNumber]))) ?>"><?= (int)$pageNumber ?></a>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
                <?php if ($equipmentPage < $equipmentTotalPages): ?>
                    <a class="pagination-link" href="<?= e(page_url('equipment.php', array_merge($equipmentPaginationParams, ['page' => $equipmentPage + 1]))) ?>">Sledeća →</a>
                <?php else: ?>
                    <span class="pagination-link is-disabled" aria-disabled="true">Sledeća →</span>
                <?php endif; ?>
            </nav>
        <?php endif; ?>
    </section>
</section>
<?php require_once __DIR__ . '/app/footer.php'; ?>
