<?php
require_once __DIR__ . '/app/bootstrap.php';
$user = require_auth();
$pageTitle = 'Moj panel';
$hasAdditionalRole = user_has_additional_role($user);
$dashboardTicketView = is_system_admin($user) ? 'all' : 'mine';
$pageSubtitle = is_system_admin($user)
    ? 'Administratorski pregled zahteva i aktivnosti sistema'
    : 'Personalizovani pregled vaših zahteva i brzi pristup podršci';

[$accessSql, $accessParams] = ticket_list_access_sql($user, $dashboardTicketView);

$statusStmt = db()->prepare("SELECT status, COUNT(*) AS total FROM tickets t WHERE $accessSql GROUP BY status");
$statusStmt->execute($accessParams);
$statusCounts = ['open' => 0, 'in_progress' => 0, 'waiting' => 0, 'resolved' => 0, 'closed' => 0];
foreach ($statusStmt->fetchAll() as $row) {
    $statusCounts[$row['status']] = (int)$row['total'];
}
$resolvedAndClosedCount = (int)$statusCounts['resolved'] + (int)$statusCounts['closed'];

$recentStmt = db()->prepare("SELECT t.*, u.name AS requester_name, a.name AS assigned_name
    FROM tickets t
    JOIN users u ON u.id = t.user_id
    LEFT JOIN users a ON a.id = t.assigned_to
    WHERE $accessSql
    ORDER BY t.updated_at DESC
    LIMIT 8");
$recentStmt->execute($accessParams);
$recentTickets = $recentStmt->fetchAll();

try {
    $equipmentStmt = db()->prepare("SELECT id, asset_type, asset_name, serial_no, inventory_no, assigned_at, status, notes FROM equipment WHERE user_id = ? AND status IN ('assigned', 'repair') ORDER BY FIELD(asset_type, 'Laptop', 'Telefon', 'Tablet', 'Monitor', 'Docking station', 'Ostalo'), asset_name ASC");
    $equipmentStmt->execute([(int)$user['id']]);
    $myEquipment = $equipmentStmt->fetchAll();
} catch (Throwable $e) {
    $myEquipment = [];
}

require_once __DIR__ . '/app/header.php';
?>
<section class="employee-card card">
    <div class="employee-identity">
        <?= user_avatar_html($user, 'employee-avatar') ?>
        <h2><?= e($user['name']) ?></h2>
        <p><?= e(employee_value($user['job_title'] ?? null)) ?></p>
        <span class="employee-role"><?= e(user_roles_summary($user)) ?></span>
        <a class="employee-photo-link" href="<?= e(url('account.php')) ?>">Podaci o nalogu</a>
    </div>
    <div class="employee-info">
        <span class="employee-section-label">Informacije o zaposlenom</span>
        <div class="employee-info-grid">
            <div class="employee-info-item">
                <span class="info-icon">📍</span>
                <div><small>Lokacija</small><strong><?= e(employee_value($user['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($user['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($user['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($user['email']) ?></strong></div>
                <button type="button" class="copy-button" data-copy-value="<?= e($user['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($user['phone'] ?? null)) ?></strong></div>
                <?php if (!empty($user['phone'])): ?><button type="button" class="copy-button" data-copy-value="<?= e($user['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($user['last_login_at'] ?? null)) ?></strong></div>
            </div>
        </div>
    </div>
</section>

<section class="dashboard-grid">
    <div class="card metric">
        <span>Otvoreni zahtevi</span>
        <strong><?= (int)$statusCounts['open'] ?></strong>
        <small>Zahtevi koji čekaju početak obrade</small>
        <div class="metric-icon metric-open"><?= status_metric_icon_html('open') ?></div>
    </div>
    <div class="card metric">
        <span>U obradi</span>
        <strong><?= (int)$statusCounts['in_progress'] ?></strong>
        <small>Zahtevi na kojima podrška trenutno radi</small>
        <div class="metric-icon metric-progress"><?= status_metric_icon_html('in_progress') ?></div>
    </div>
    <div class="card metric">
        <span>Na čekanju</span>
        <strong><?= (int)$statusCounts['waiting'] ?></strong>
        <small>Zahtevi koji čekaju informaciju ili odobrenje</small>
        <div class="metric-icon metric-waiting"><?= status_metric_icon_html('waiting') ?></div>
    </div>
    <div class="card metric">
        <span>Rešeni</span>
        <strong><?= $resolvedAndClosedCount ?></strong>
        <small>Rešeni zahtevi koji mogu biti zatvoreni</small>
        <div class="metric-icon metric-resolved"><?= status_metric_icon_html('resolved') ?></div>
    </div>
</section>

<section class="card quick-card">
    <h2>Brzi pristup</h2>
    <p>Prijavite novi zahtev, proverite svoje tikete ili otvorite zasebnu listu tiketa za koje ste zaduženi.</p>
    <div class="inline-actions">
        <?php if (can_create_ticket($user)): ?><a class="button button-primary" href="<?= e(url('ticket_create.php')) ?>">Novi zahtev</a><?php endif; ?>
        <a class="button button-light" href="<?= e(url('tickets.php?view=mine')) ?>">Moji tiketi</a>
        <?php if ($hasAdditionalRole): ?><a class="button button-light" href="<?= e(url('tickets.php?view=assigned')) ?>">Tiketi za koje sam zadužen</a><?php endif; ?>
        <?php if (is_system_admin($user)): ?><a class="button button-light" href="<?= e(url('tickets.php?view=all')) ?>">Svi zahtevi</a><?php endif; ?>
    </div>
</section>

<section class="dashboard-two-col">
    <article class="card card-pad">
        <div class="section-heading compact-heading">
            <div>
                <span class="badge">Moja oprema</span>
                <h2>Dodeljena oprema</h2>
                <p>Laptop, telefon i druga zadužena oprema na vaše ime.</p>
            </div>
            <?php if (is_system_admin($user)): ?><a class="button button-light" href="<?= e(url('equipment.php')) ?>">Administracija opreme</a><?php endif; ?>
        </div>
        <?php if (!$myEquipment): ?>
            <p class="empty-state">Trenutno nema evidentirane opreme za vaš nalog.</p>
        <?php else: ?>
            <div class="equipment-list">
                <?php foreach ($myEquipment 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>
                            <?php if (!empty($asset['notes'])): ?><small><?= e($asset['notes']) ?></small><?php endif; ?>
                        </div>
                        <div class="equipment-item-actions">
                            <span class="pill <?= e(equipment_status_class($asset['status'])) ?>"><?= e(equipment_status_label($asset['status'])) ?></span>
                            <?php if (can_create_ticket($user)): ?><a class="button button-danger equipment-report-button" href="<?= e(url('ticket_create.php?equipment_id=' . (int)$asset['id'])) ?>">Prijavi problem</a><?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </article>
</section>

<section class="card card-pad recent-tickets-card">
    <div class="section-heading">
        <div>
            <span class="badge">Aktivnost</span>
            <h2>Najnoviji zahtevi</h2>
            <p><?= is_system_admin($user) ? 'Poslednji izmenjeni tiketi u sistemu.' : 'Poslednji izmenjeni tiketi koje ste otvorili.' ?></p>
        </div>
        <?php if (can_create_ticket($user)): ?><a class="button button-blue" href="<?= e(url('ticket_create.php')) ?>">Novi zahtev</a><?php endif; ?>
    </div>

    <?php if (!$recentTickets): ?>
        <p class="empty-state">Još uvek nema kreiranih zahteva.</p>
    <?php else: ?>
        <div class="table-wrap">
            <table>
                <thead>
                <tr>
                    <th>Broj</th>
                    <th>Zahtev</th>
                    <th>Status</th>
                    <th>Prioritet</th>
                    <th>Podnosilac</th>
                    <th>Izmenjeno</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($recentTickets as $ticket): ?>
                    <tr>
                        <td><a href="<?= e(url('ticket_view.php?id=' . (int)$ticket['id'])) ?>"><?= e($ticket['ticket_no']) ?></a></td>
                        <td class="ticket-title"><strong><?= e($ticket['title']) ?></strong><small><?= e(limit_text($ticket['description'], 90)) ?></small></td>
                        <td><span class="pill <?= e(status_class($ticket['status'])) ?>"><?= e(status_label($ticket['status'])) ?></span></td>
                        <td><span class="pill <?= e(priority_class($ticket['priority'])) ?>"><?= e(priority_label($ticket['priority'])) ?></span></td>
                        <td><?= e($ticket['requester_name']) ?></td>
                        <td><?= e(format_datetime($ticket['updated_at'])) ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</section>

<?php require_once __DIR__ . '/app/footer.php'; ?>
