<?php
require_once 'header.php';

function dash_table_exists(mysqli $mysqli, string $table): bool {
    $safe = $mysqli->real_escape_string($table);
    $res = $mysqli->query("SHOW TABLES LIKE '{$safe}'");
    return $res && $res->num_rows > 0;
}
function dash_column_exists(mysqli $mysqli, string $table, string $column): bool {
    $table = $mysqli->real_escape_string($table);
    $column = $mysqli->real_escape_string($column);
    $res = $mysqli->query("SHOW COLUMNS FROM `{$table}` LIKE '{$column}'");
    return $res && $res->num_rows > 0;
}
function fmt_date_hr($date): string {
    if (empty($date)) return '—';
    $dt = DateTime::createFromFormat('Y-m-d', (string)$date) ?: new DateTime((string)$date);
    return $dt ? $dt->format('d.m.Y') : (string)$date;
}
function h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function fetch_one(mysqli $mysqli, string $sql, $default = null) {
    $res = $mysqli->query($sql);
    if (!$res) return $default;
    $row = $res->fetch_row();
    return $row ? $row[0] : $default;
}

$me = $_SESSION['user'] ?? [];
$isAdmin = (($me['role'] ?? 'user') === 'admin');
?>

<style>
.dashboard-grid { display:grid; grid-template-columns:repeat(12,minmax(0,1fr)); gap:16px; }
.kpi-card { grid-column:span 3; }
.panel-6 { grid-column:span 6; }
.panel-4 { grid-column:span 4; }
.panel-8 { grid-column:span 8; }
.kpi-value { font-size:2rem; font-weight:800; line-height:1; letter-spacing:-.03em; color:#f8fafc; }
.kpi-label { font-size:.78rem; letter-spacing:.08em; text-transform:uppercase; color:#93a4bf; margin-bottom:8px; }
.kpi-sub { color:#cbd5e1; font-size:.9rem; }
.quick-actions { display:flex; flex-wrap:wrap; gap:10px; }
.dashboard-list { display:flex; flex-direction:column; gap:10px; }
.dashboard-row {
  display:flex; align-items:center; justify-content:space-between; gap:14px;
  padding:12px 14px; border-radius:14px;
  background:rgba(255,255,255,.025);
  border:1px solid rgba(148,163,184,.12);
}
.dashboard-row-main { min-width:0; }
.dashboard-row-title { color:#f8fafc; font-weight:600; }
.dashboard-row-sub { color:#94a3b8; font-size:.83rem; margin-top:2px; }
.dashboard-row-end { text-align:right; white-space:nowrap; color:#e5e7eb; }
.metric-badge {
  display:inline-flex; align-items:center; gap:6px; padding:6px 10px;
  border-radius:999px; border:1px solid rgba(96,165,250,.28);
  background:rgba(59,130,246,.12); color:#dbeafe; font-size:.78rem; font-weight:700;
}
.empty-state {
  padding:18px; border-radius:14px; text-align:center; color:#94a3b8;
  background:rgba(255,255,255,.02); border:1px dashed rgba(148,163,184,.16);
}
.dashboard-icon {
  width:42px; height:42px; border-radius:14px; display:inline-flex; align-items:center; justify-content:center;
  background:linear-gradient(135deg, rgba(59,130,246,.18), rgba(99,102,241,.12));
  border:1px solid rgba(96,165,250,.18); font-size:1.1rem;
}
.work-home {
  min-height:calc(100vh - 260px); display:flex; align-items:center; justify-content:center;
}
.work-home-card {
  max-width:560px; width:100%; text-align:center;
}
.work-home-icon {
  width:72px; height:72px; margin:0 auto 16px; border-radius:22px;
  display:flex; align-items:center; justify-content:center; font-size:1.8rem;
  color:#dbeafe; background:linear-gradient(135deg, rgba(59,130,246,.22), rgba(99,102,241,.14));
  border:1px solid rgba(96,165,250,.22);
}
.work-home-title { font-size:1.4rem; font-weight:800; color:#f8fafc; }
.work-home-sub { color:#94a3b8; max-width:420px; margin:10px auto 0; }
.work-home-actions { display:flex; justify-content:center; gap:10px; flex-wrap:wrap; margin-top:22px; }
.work-home-actions .btn { min-width:180px; }
@media (max-width: 1199px){ .kpi-card{ grid-column:span 6; } .panel-4{ grid-column:span 6; } }
@media (max-width: 767px){
  .dashboard-grid { grid-template-columns:1fr; gap:14px; }
  .kpi-card, .panel-6, .panel-4, .panel-8 { grid-column:auto; }
  .kpi-value { font-size:1.7rem; }
  .dashboard-row { flex-direction:column; align-items:flex-start; }
  .dashboard-row-end { text-align:left; white-space:normal; }
  .work-home { min-height:auto; padding-top:10px; }
}
</style>

<?php if (!$isAdmin): ?>
<div class="work-home">
    <div class="card card-soft work-home-card">
        <div class="card-body card-soft-body py-5 px-4">
            <div class="work-home-icon">🧾</div>
            <div class="work-home-title">Početni ekran</div>
            <div class="work-home-sub"></div>
            <div class="work-home-actions">
                <a href="order_new.php" class="btn btn-primary btn-soft">+ Novi nalog</a>
            </div>
        </div>
    </div>
</div>
<?php require_once 'footer.php'; exit; ?>
<?php endif; ?>

<?php
$hasProjects = dash_table_exists($mysqli, 'projects');
$hasOrders = dash_table_exists($mysqli, 'consumption_orders');
$hasItems = dash_table_exists($mysqli, 'consumption_items') && dash_table_exists($mysqli, 'items');
$hasLabor = dash_table_exists($mysqli, 'consumption_labor') && dash_table_exists($mysqli, 'employees');
$hasWarranty = dash_table_exists($mysqli, 'consumption_items')
    && dash_column_exists($mysqli, 'consumption_items', 'has_warranty')
    && dash_column_exists($mysqli, 'consumption_items', 'warranty_months');

$openProjects = 0;
$hoursOnOpenProjects = 0.0;
$ordersThisMonth = 0;
$activeWarranties = 0;
$lastOrder = null;
$recentOrders = [];
$topProjects = [];
$topItems = [];
$topEmployees = [];

if ($hasProjects) {
    $openProjects = (int) fetch_one($mysqli, "SELECT COUNT(*) FROM projects WHERE project_status='open'", 0);
}
if ($hasOrders) {
    $ordersThisMonth = (int) fetch_one($mysqli, "SELECT COUNT(*) FROM consumption_orders WHERE DATE_FORMAT(usage_date, '%Y-%m') = DATE_FORMAT(CURDATE(), '%Y-%m')", 0);
    $lastSql = "SELECT o.id, o.usage_date, o.note, p.name AS project_name, p.location
                FROM consumption_orders o
                LEFT JOIN projects p ON p.id = o.project_id
                ORDER BY o.usage_date DESC, o.id DESC
                LIMIT 1";
    $lastRes = $mysqli->query($lastSql);
    if ($lastRes) $lastOrder = $lastRes->fetch_assoc();

    $recentSql = "SELECT o.id, o.usage_date, o.note, p.name AS project_name, p.location
                  FROM consumption_orders o
                  LEFT JOIN projects p ON p.id = o.project_id
                  ORDER BY o.usage_date DESC, o.id DESC
                  LIMIT 5";
    $res = $mysqli->query($recentSql);
    if ($res) while ($r = $res->fetch_assoc()) $recentOrders[] = $r;
}
if ($hasLabor && $hasProjects) {
    $hoursOnOpenProjects = (float) fetch_one($mysqli, "
        SELECT COALESCE(SUM(l.hours),0)
        FROM consumption_labor l
        JOIN consumption_orders o ON o.id = l.order_id
        JOIN projects p ON p.id = o.project_id
        WHERE p.project_status='open'
    ", 0);

    $topEmpSql = "
        SELECT e.first_name, e.last_name, SUM(l.hours) AS total_hours
        FROM consumption_labor l
        JOIN employees e ON e.id = l.employee_id
        GROUP BY e.id
        ORDER BY total_hours DESC, e.last_name, e.first_name
        LIMIT 5
    ";
    $res = $mysqli->query($topEmpSql);
    if ($res) while ($r = $res->fetch_assoc()) $topEmployees[] = $r;
}
if ($hasProjects && $hasOrders) {
    $topProjSql = "
        SELECT p.id, p.name, p.location,
               COUNT(DISTINCT o.id) AS orders_count,
               COALESCE(SUM(l.hours),0) AS total_hours,
               MAX(o.usage_date) AS last_activity
        FROM projects p
        LEFT JOIN consumption_orders o ON o.project_id = p.id
        LEFT JOIN consumption_labor l ON l.order_id = o.id
        WHERE p.project_status='open'
        GROUP BY p.id
        ORDER BY total_hours DESC, orders_count DESC, p.name
        LIMIT 5
    ";
    $res = $mysqli->query($topProjSql);
    if ($res) while ($r = $res->fetch_assoc()) $topProjects[] = $r;
}
if ($hasItems) {
    $topItemSql = "
        SELECT i.code, i.name, ci.unit, SUM(ci.quantity) AS total_qty
        FROM consumption_items ci
        JOIN items i ON i.id = ci.item_id
        JOIN consumption_orders o ON o.id = ci.order_id
        WHERE o.usage_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
        GROUP BY ci.item_id, i.code, i.name, ci.unit
        ORDER BY total_qty DESC, i.name
        LIMIT 5
    ";
    $res = $mysqli->query($topItemSql);
    if ($res) while ($r = $res->fetch_assoc()) $topItems[] = $r;
}
if ($hasWarranty && $hasOrders) {
    $activeWarranties = (int) fetch_one($mysqli, "
        SELECT COUNT(*)
        FROM consumption_items ci
        JOIN consumption_orders o ON o.id = ci.order_id
        WHERE ci.has_warranty = 1
          AND ci.warranty_months IS NOT NULL
          AND DATE_ADD(o.usage_date, INTERVAL ci.warranty_months MONTH) >= CURDATE()
    ", 0);
}
?>

<div class="row g-3 mb-3 align-items-center">
    <div class="col">
        <div class="section-title mb-1">Dashboard</div>
        <div class="text-muted small">Brzi pregled projekata, naloga, sati rada i materijala.</div>
    </div>
    <div class="col-auto">
        <div class="quick-actions">
            <a href="order_new.php" class="btn btn-primary btn-soft btn-sm">+ Novi nalog</a>
            <a href="projects.php" class="btn btn-outline-primary btn-soft btn-sm">Projekti</a>
            <a href="items.php" class="btn btn-outline-secondary btn-soft btn-sm">Artikli</a>
            <a href="stock.php" class="btn btn-outline-secondary btn-soft btn-sm">Stanje</a>
        </div>
    </div>
</div>

<div class="dashboard-grid">
    <div class="card card-soft kpi-card">
        <div class="card-body card-soft-body">
            <div class="d-flex justify-content-between align-items-start gap-3">
                <div>
                    <div class="kpi-label">Otvoreni projekti</div>
                    <div class="kpi-value"><?php echo (int)$openProjects; ?></div>
                    <div class="kpi-sub mt-2">Aktivni projekti za daljnji rad.</div>
                </div>
                <div class="dashboard-icon">📁</div>
            </div>
        </div>
    </div>

    <div class="card card-soft kpi-card">
        <div class="card-body card-soft-body">
            <div class="d-flex justify-content-between align-items-start gap-3">
                <div>
                    <div class="kpi-label">Zadnji radni nalog</div>
                    <div class="kpi-value"><?php echo $lastOrder ? '#'.(int)$lastOrder['id'] : '—'; ?></div>
                    <div class="kpi-sub mt-2"><?php echo $lastOrder ? h(($lastOrder['project_name'] ?: 'Bez projekta') . ' • ' . fmt_date_hr($lastOrder['usage_date'])) : 'Nema unesenih naloga'; ?></div>
                </div>
                <div class="dashboard-icon">🧾</div>
            </div>
        </div>
    </div>

    <div class="card card-soft kpi-card">
        <div class="card-body card-soft-body">
            <div class="d-flex justify-content-between align-items-start gap-3">
                <div>
                    <div class="kpi-label">Sati na otvorenim projektima</div>
                    <div class="kpi-value"><?php echo number_format($hoursOnOpenProjects, 2, ',', '.'); ?></div>
                    <div class="kpi-sub mt-2">Ukupno evidentiranih sati rada.</div>
                </div>
                <div class="dashboard-icon">⏱️</div>
            </div>
        </div>
    </div>

    <div class="card card-soft kpi-card">
        <div class="card-body card-soft-body">
            <div class="d-flex justify-content-between align-items-start gap-3">
                <div>
                    <div class="kpi-label">Nalozi ovaj mjesec</div>
                    <div class="kpi-value"><?php echo (int)$ordersThisMonth; ?></div>
                    <div class="kpi-sub mt-2">Ukupan broj unesenih naloga u tekućem mjesecu.</div>
                </div>
                <div class="dashboard-icon">📆</div>
            </div>
        </div>
    </div>

    <div class="card card-soft panel-6">
        <div class="card-header card-soft-header d-flex justify-content-between align-items-center">
            <span class="fw-semibold">Zadnjih 5 naloga</span>
            <a href="orders.php" class="btn btn-outline-secondary btn-soft btn-sm">Svi nalozi</a>
        </div>
        <div class="card-body card-soft-body">
            <?php if (empty($recentOrders)): ?>
                <div class="empty-state">Nema evidentiranih naloga.</div>
            <?php else: ?>
                <div class="dashboard-list">
                    <?php foreach ($recentOrders as $row): ?>
                        <div class="dashboard-row">
                            <div class="dashboard-row-main">
                                <div class="dashboard-row-title">#<?php echo (int)$row['id']; ?> • <?php echo h($row['project_name'] ?: 'Bez projekta'); ?></div>
                                <div class="dashboard-row-sub">
                                    Datum: <?php echo fmt_date_hr($row['usage_date']); ?>
                                    <?php if (!empty($row['location'])): ?> • <?php echo h($row['location']); ?><?php endif; ?>
                                    <?php if (!empty($row['note'])): ?> • <?php echo h(mb_strimwidth($row['note'], 0, 60, '…')); ?><?php endif; ?>
                                </div>
                            </div>
                            <div class="dashboard-row-end">
                                <a href="order_view.php?id=<?php echo (int)$row['id']; ?>" class="btn btn-outline-primary btn-soft btn-sm">Otvori</a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="card card-soft panel-6">
        <div class="card-header card-soft-header d-flex justify-content-between align-items-center">
            <span class="fw-semibold">Top 5 otvorenih projekata po satima</span>
            <a href="projects.php" class="btn btn-outline-secondary btn-soft btn-sm">Svi projekti</a>
        </div>
        <div class="card-body card-soft-body">
            <?php if (empty($topProjects)): ?>
                <div class="empty-state">Nema podataka za otvorene projekte.</div>
            <?php else: ?>
                <div class="dashboard-list">
                    <?php foreach ($topProjects as $row): ?>
                        <div class="dashboard-row">
                            <div class="dashboard-row-main">
                                <div class="dashboard-row-title"><?php echo h($row['name']); ?></div>
                                <div class="dashboard-row-sub">
                                    <?php echo !empty($row['location']) ? h($row['location']) . ' • ' : ''; ?>
                                    Nalozi: <?php echo (int)$row['orders_count']; ?> • Zadnja aktivnost: <?php echo fmt_date_hr($row['last_activity']); ?>
                                </div>
                            </div>
                            <div class="dashboard-row-end">
                                <span class="metric-badge"><?php echo number_format((float)$row['total_hours'], 2, ',', '.'); ?> h</span>
                                <div class="mt-2"><a href="project_detail.php?project_id=<?php echo (int)$row['id']; ?>" class="btn btn-outline-primary btn-soft btn-sm">Detalji</a></div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="card card-soft panel-4">
        <div class="card-header card-soft-header d-flex justify-content-between align-items-center">
            <span class="fw-semibold">Top 5 artikala (30 dana)</span>
            <span class="pill-counter">Utrošak</span>
        </div>
        <div class="card-body card-soft-body">
            <?php if (empty($topItems)): ?>
                <div class="empty-state">Nema utroška artikala u zadnjih 30 dana.</div>
            <?php else: ?>
                <div class="dashboard-list">
                    <?php foreach ($topItems as $row): ?>
                        <div class="dashboard-row">
                            <div class="dashboard-row-main">
                                <div class="dashboard-row-title"><?php echo h($row['name']); ?></div>
                                <div class="dashboard-row-sub">Šifra: <?php echo h($row['code']); ?></div>
                            </div>
                            <div class="dashboard-row-end">
                                <span class="metric-badge"><?php echo number_format((float)$row['total_qty'], 3, ',', '.'); ?> <?php echo h($row['unit']); ?></span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="card card-soft panel-4">
        <div class="card-header card-soft-header d-flex justify-content-between align-items-center">
            <span class="fw-semibold">Top 5 djelatnika po satima</span>
            <span class="pill-counter">Rad</span>
        </div>
        <div class="card-body card-soft-body">
            <?php if (empty($topEmployees)): ?>
                <div class="empty-state">Nema evidentiranih sati rada.</div>
            <?php else: ?>
                <div class="dashboard-list">
                    <?php foreach ($topEmployees as $row): ?>
                        <div class="dashboard-row">
                            <div class="dashboard-row-main">
                                <div class="dashboard-row-title"><?php echo h(trim(($row['first_name'] ?? '').' '.($row['last_name'] ?? ''))); ?></div>
                            </div>
                            <div class="dashboard-row-end">
                                <span class="metric-badge"><?php echo number_format((float)$row['total_hours'], 2, ',', '.'); ?> h</span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="card card-soft panel-4">
        <div class="card-header card-soft-header d-flex justify-content-between align-items-center">
            <span class="fw-semibold">Aktivne garancije</span>
            <span class="pill-counter">Garancija</span>
        </div>
        <div class="card-body card-soft-body">
            <div class="d-flex justify-content-between align-items-center gap-3">
                <div>
                    <div class="kpi-value"><?php echo (int)$activeWarranties; ?></div>
                    <div class="kpi-sub mt-2">Broj stavki kojima garancija još traje.</div>
                </div>
                <div class="dashboard-icon">🛡️</div>
            </div>
        </div>
    </div>
</div>

<?php require_once 'footer.php'; ?>
