<?php
require_once __DIR__ . '/inc/auth.php';
$session = auth_require();
$role = $session['user_role'];
$pdo = getDB();

// Common stats
$stats = [];

// Total objects
$stmt = $pdo->query("SELECT COUNT(*) FROM objects WHERE status='active'");
$stats['objects'] = $stmt->fetchColumn();

// Active tasks
$stmt = $pdo->query("SELECT COUNT(*) FROM tasks WHERE status IN ('open','in_progress')");
$stats['tasks'] = $stmt->fetchColumn();

// Open incidents
$stmt = $pdo->query("SELECT COUNT(*) FROM incidents WHERE status IN ('open','in_progress')");
$stats['incidents'] = $stmt->fetchColumn();

// Active SLA contracts
$stmt = $pdo->query("SELECT COUNT(*) FROM sla_contracts WHERE status='active'");
$stats['sla_count'] = $stmt->fetchColumn();

// Latest SHS
$stmt = $pdo->query("SELECT shs_score, shs_status FROM shs_records ORDER BY id DESC LIMIT 1");
$stats['shs'] = $stmt->fetch();

// Engineer-specific: tasks assigned to me
if ($role === 'engineer' || $role === 'technician') {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM tasks WHERE assigned_to = ? AND status IN ('open','in_progress')");
    $stmt->execute([$session['user_id']]);
    $stats['my_tasks'] = $stmt->fetchColumn();
}

// SLA compliance (overall)
$stmt = $pdo->query("SELECT COUNT(*) as total, SUM(CASE WHEN sla_compliant=TRUE THEN 1 ELSE 0 END) as compliant FROM tasks WHERE closed_at IS NOT NULL");
$slaData = $stmt->fetch();
$stats['sla_compliance'] = $slaData['total'] > 0 ? round(($slaData['compliant'] / $slaData['total']) * 100, 1) : 0;

$shsAlert = null;
if ($stats['shs'] && $stats['shs']['shs_score'] < 70) {
    $shsAlert = 'SHS ниже 70 (' . $stats['shs']['shs_score'] . ') — ' . $stats['shs']['shs_status'];
}

require __DIR__ . '/inc/header.php';
?>

<div class="main-header">
    <div>
        <h1>Дашборд</h1>
        <div class="breadcrumb"><a href="/service/dashboard.php">Главная</a></div>
    </div>
    <div class="actions">
        <span style="font-size:12px;color:var(--text-muted);"><?= date('d.m.Y H:i') ?></span>
    </div>
</div>

<?php if ($shsAlert): ?>
<div class="shs-alert critical">⚠ <?= htmlspecialchars($shsAlert) ?></div>
<?php endif; ?>

<div class="card-grid">
    <a href="/service/pages/owner/objects.php" class="card card-link">
        <div class="card-label">Активные объекты</div>
        <div class="card-value value-accent"><?= $stats['objects'] ?></div>
    </a>
    <a href="/service/pages/engineer/tasks.php" class="card card-link">
        <div class="card-label">Активные задачи</div>
        <div class="card-value <?= $stats['tasks'] > 0 ? 'value-yellow' : 'value-green' ?>"><?= $stats['tasks'] ?></div>
    </a>
    <a href="/service/pages/engineer/incidents.php" class="card card-link">
        <div class="card-label">Открытые инциденты</div>
        <div class="card-value <?= $stats['incidents'] > 0 ? 'value-red' : 'value-green' ?>"><?= $stats['incidents'] ?></div>
    </a>
    <a href="/service/pages/owner/sla.php" class="card card-link">
        <div class="card-label">SLA контракты</div>
        <div class="card-value value-info"><?= $stats['sla_count'] ?></div>
    </a>
    <a href="/service/pages/owner/sla.php" class="card card-link">
        <div class="card-label">SLA Compliance</div>
        <div class="card-value <?= $stats['sla_compliance'] >= 90 ? 'value-green' : ($stats['sla_compliance'] >= 70 ? 'value-yellow' : 'value-red') ?>"><?= $stats['sla_compliance'] ?>%</div>
    </a>
    <?php if ($stats['shs']): ?>
    <a href="/service/pages/owner/ceo.php" class="card card-link">
        <div class="card-label">SHS (System Health)</div>
        <div class="card-value <?= $stats['shs']['shs_status'] === 'Growth' || $stats['shs']['shs_status'] === 'Stable' ? 'value-green' : 'value-red' ?>"><?= $stats['shs']['shs_score'] ?></div>
        <div class="card-label"><span class="badge badge-<?= strtolower($stats['shs']['shs_status']) ?>"><?= $stats['shs']['shs_status'] ?></span></div>
    </a>
    <?php endif; ?>
    <?php if (isset($stats['my_tasks'])): ?>
    <a href="/service/pages/engineer/tasks.php" class="card card-link">
        <div class="card-label">Мои задачи</div>
        <div class="card-value"><?= $stats['my_tasks'] ?></div>
    </a>
    <?php endif; ?>
</div>

<?php
require __DIR__ . '/inc/footer.php';
?>
<style>
.card-link { text-decoration:none; color:inherit; display:block; transition:transform 0.2s, box-shadow 0.2s; }
.card-link:hover { transform:translateY(-2px); box-shadow:var(--shadow); cursor:pointer; }
</style>
