<?php
require_once __DIR__ . '/../../inc/auth.php';
require_once __DIR__ . '/../../inc/functions.php';
$session = auth_require('owner');

$pdo = getDB();

// SHS history (last 12 records)
$shsHistory = $pdo->query("SELECT * FROM shs_records ORDER BY id DESC LIMIT 12")->fetchAll();

// Current SHS
$shs = $pdo->query("SELECT * FROM shs_records ORDER BY id DESC LIMIT 1")->fetch();

// MRR
$stmt = $pdo->query("SELECT SUM(sla_price_monthly) as mrr FROM sla_contracts WHERE status='active'");
$mrrData = $stmt->fetch();
$mrr = (float)($mrrData['mrr'] ?? 0);

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

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

// Engineer count
$stmt = $pdo->query("SELECT COUNT(*) FROM users WHERE role IN ('engineer','technician') AND is_active");
$engineerCount = $stmt->fetchColumn();

// SLA compliance
$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();
$slaCompliance = $slaData['total'] > 0 ? round(($slaData['compliant'] / $slaData['total']) * 100, 1) : 0;

// Incident rate
$stmt = $pdo->query("SELECT COUNT(*) FROM incidents WHERE created_at > NOW() - INTERVAL '30 days'");
$incident30 = $stmt->fetchColumn();
$incidentRate = $totalObjects > 0 ? round($incident30 / $totalObjects, 2) : 0;

// Retention (active sla / total ever)
$stmt = $pdo->query("SELECT COUNT(DISTINCT object_id) FROM sla_contracts WHERE status IN ('active','expired','cancelled')");
$totalEver = $stmt->fetchColumn();
$retention = $totalEver > 0 ? round(($activeSla / $totalEver) * 100, 1) : 0;

// Engineer KPI last period
$kpiLatest = $pdo->query("SELECT ek.*, u.full_name FROM engineer_kpi ek JOIN users u ON u.id=ek.engineer_id ORDER BY ek.period_end DESC LIMIT 10")->fetchAll();

// Avg engineer score
$stmt = $pdo->query("SELECT AVG(engineer_score) FROM engineer_kpi WHERE period_end > NOW() - INTERVAL '30 days'");
$avgEngineerScore = round((float)$stmt->fetchColumn(), 1);

// Revenue per engineer
$rpe = $engineerCount > 0 ? round($mrr / $engineerCount, 2) : 0;

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

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

<?php if ($shs && $shs['shs_score'] < 70): ?>
<div class="shs-alert critical">⚠ SHS <?= $shs['shs_score'] ?> — <?= $shs['shs_status'] ?>. Рекомендуется: снизить продажи, запустить аудит, пересмотреть назначения.</div>
<?php elseif ($shs && $shs['shs_score'] < 85): ?>
<div class="shs-alert warning">⚠ SHS <?= $shs['shs_score'] ?> — <?= $shs['shs_status'] ?>. Требуется внимание.</div>
<?php endif; ?>

<?php if ($slaCompliance < 90): ?>
<div class="shs-alert warning">⚠ SLA Compliance <?= $slaCompliance ?>% — ниже 90%. Рекомендуется заморозить неприоритетные проекты, увеличить частоту проверок.</div>
<?php endif; ?>

<?php if ($retention < 90): ?>
<div class="shs-alert critical">⚠ Удержание клиентов <?= $retention ?>% — ниже 90%. Обязательный аудит клиентов, пересмотр назначений инженеров.</div>
<?php endif; ?>

<div class="card-grid">
    <div class="card">
        <div class="card-label">SHS (System Health)</div>
        <div class="card-value <?= $shs ? ($shs['shs_score'] >= 70 ? 'value-green' : 'value-red') : 'value-yellow' ?>"><?= $shs ? $shs['shs_score'] : '—' ?></div>
        <div class="card-label"><?= $shs ? '<span class="badge badge-'.strtolower($shs['shs_status']).'">'.$shs['shs_status'].'</span>' : 'Нет данных' ?></div>
    </div>
    <div class="card">
        <div class="card-label">MRR (месячный доход)</div>
        <div class="card-value value-green"><?= fmt_money($mrr) ?></div>
        <div class="card-label"><?= $activeSla ?> активных контрактов</div>
    </div>
    <div class="card">
        <div class="card-label">SLA Compliance</div>
        <div class="card-value <?= $slaCompliance >= 90 ? 'value-green' : ($slaCompliance >= 70 ? 'value-yellow' : 'value-red') ?>"><?= $slaCompliance ?>%</div>
    </div>
    <div class="card">
        <div class="card-label">Удержание (Retention)</div>
        <div class="card-value <?= $retention >= 90 ? 'value-green' : 'value-red' ?>"><?= $retention ?>%</div>
    </div>
    <div class="card">
        <div class="card-label">Incident Rate (30 дн)</div>
        <div class="card-value <?= $incidentRate < 1 ? 'value-green' : 'value-red' ?>"><?= $incidentRate ?></div>
    </div>
    <div class="card">
        <div class="card-label">Средний Engineer Score</div>
        <div class="card-value <?= $avgEngineerScore >= 80 ? 'value-green' : ($avgEngineerScore >= 70 ? 'value-yellow' : 'value-red') ?>"><?= $avgEngineerScore ?: '—' ?></div>
    </div>
    <div class="card">
        <div class="card-label">Revenue per Engineer</div>
        <div class="card-value value-accent"><?= fmt_money($rpe) ?></div>
    </div>
    <div class="card">
        <div class="card-label">Активных объектов</div>
        <div class="card-value"><?= $totalObjects ?></div>
        <div class="card-label">Инженеров / техников: <?= $engineerCount ?></div>
    </div>
</div>

<div class="card">
    <div class="card-header"><h2>SHS Trend</h2></div>
    <?php if (empty($shsHistory)): ?>
    <p style="color:var(--text-muted);">Нет данных SHS. Записи появятся после создания KPI и расчётов.</p>
    <?php else: ?>
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>Период</th>
                    <th>SLA Stability</th>
                    <th>Revenue</th>
                    <th>Retention</th>
                    <th>Engineer Perf</th>
                    <th>Incident Stability</th>
                    <th>SHS Score</th>
                    <th>Статус</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($shsHistory as $s): ?>
                <tr>
                    <td><?= $s['period_start'] ?> — <?= $s['period_end'] ?></td>
                    <td><?= $s['sla_stability'] ?>%</td>
                    <td><?= $s['revenue_stability'] ?>%</td>
                    <td><?= $s['retention'] ?>%</td>
                    <td><?= $s['engineer_performance'] ?>%</td>
                    <td><?= $s['incident_stability'] ?>%</td>
                    <td><strong class="<?= $s['shs_score'] >= 70 ? 'value-green' : 'value-red' ?>"><?= $s['shs_score'] ?></strong></td>
                    <td><span class="badge badge-<?= strtolower($s['shs_status']) ?>"><?= $s['shs_status'] ?></span></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<div class="card">
    <div class="card-header"><h2>Engineer KPI (последние)</h2></div>
    <?php if (empty($kpiLatest)): ?>
    <p style="color:var(--text-muted);">Нет KPI записей.</p>
    <?php else: ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Инженер</th>
                    <th>Период</th>
                    <th>SLA Compliance</th>
                    <th>Engineer Score</th>
                    <th>Грейд</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($kpiLatest as $k): ?>
                <tr>
                    <td><strong><?= htmlspecialchars($k['full_name']) ?></strong></td>
                    <td><?= $k['period_start'] ?> — <?= $k['period_end'] ?></td>
                    <td><?= $k['sla_compliance'] ?>%</td>
                    <td class="<?= $k['engineer_score'] >= 80 ? 'value-green' : ($k['engineer_score'] >= 70 ? 'value-yellow' : 'value-red') ?>"><strong><?= $k['engineer_score'] ?></strong></td>
                    <td><span class="badge badge-<?= $k['grade'] === 'Senior' ? 'critical' : ($k['grade'] === 'Strong' ? 'high' : 'medium') ?>"><?= $k['grade'] ?></span></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<div class="card">
    <div class="card-header"><h2>Расчёт SHS</h2></div>
    <div style="display:flex;gap:10px;flex-wrap:wrap;">
        <form method="post" action="ceo_calc.php" style="display:inline;">
            <input type="hidden" name="csrf_token" value="<?= auth_csrf_token() ?>">
            <button type="submit" class="btn btn-primary">🔄 Рассчитать SHS</button>
        </form>
        <form method="post" action="kpi_calc.php" style="display:inline;">
            <input type="hidden" name="csrf_token" value="<?= auth_csrf_token() ?>">
            <button type="submit" class="btn btn-secondary">📊 Рассчитать KPI инженеров</button>
        </form>
        <span style="font-size:12px;color:var(--text-muted);align-self:center;">На основе текущих данных системы</span>
    </div>
</div>

<?php require __DIR__ . '/../../inc/footer.php'; ?>
