<?php
require_once __DIR__ . '/../../../includes/auth.php';
requireLogin();
requirePermission('manage_operations');

require_once __DIR__ . '/../../../config/database.php';

/* ===== LOAD MASTER LAYOUT ===== */
require_once __DIR__ . '/../../../includes/layout.php';

$company_id = $_SESSION['company_id'];

/* =====================================================
   BASIC STAT FUNCTION
===================================================== */
function countStat($pdo, $sql, $params){
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    return (int)$stmt->fetchColumn();
}

/* =====================================================
   CORE METRICS
===================================================== */

$total = countStat($pdo,
    "SELECT COUNT(*) FROM operations_tickets WHERE tenant_id=?",
    [$company_id]
);

$open = countStat($pdo,
    "SELECT COUNT(*) FROM operations_tickets 
     WHERE tenant_id=? AND status='Open'",
    [$company_id]
);

$inProgress = countStat($pdo,
    "SELECT COUNT(*) FROM operations_tickets 
     WHERE tenant_id=? AND status='In Progress'",
    [$company_id]
);

$escalated = countStat($pdo,
    "SELECT COUNT(*) FROM operations_tickets 
     WHERE tenant_id=? AND status='Escalated'",
    [$company_id]
);

$overdue = countStat($pdo,
    "SELECT COUNT(*) FROM operations_tickets
     WHERE tenant_id=?
     AND due_at IS NOT NULL
     AND due_at < NOW()
     AND status NOT IN ('Resolved','Closed')",
    [$company_id]
);

/* =====================================================
   STATUS BREAKDOWN
===================================================== */
$statusBreakdown = $pdo->prepare("
    SELECT status, COUNT(*) AS total
    FROM operations_tickets
    WHERE tenant_id=?
    GROUP BY status
    ORDER BY total DESC
");
$statusBreakdown->execute([$company_id]);
$statusRows = $statusBreakdown->fetchAll(PDO::FETCH_ASSOC);

?>

<div class="page-header">
    <h2>Operations Reports</h2>
    <p class="page-subtitle">
        Performance, workload & SLA monitoring
    </p>
</div>

<div style="margin-bottom:20px;">
    <a href="<?= $BASE ?>/operations/reports/export.php" class="btn btn-primary">
        Export to CSV
    </a>
</div>

<div class="report-grid">

    <div class="report-card">
        <h4>Total Tickets</h4>
        <div class="metric"><?= $total ?></div>
    </div>

    <div class="report-card">
        <h4>Open</h4>
        <div class="metric warning"><?= $open ?></div>
    </div>

    <div class="report-card">
        <h4>In Progress</h4>
        <div class="metric"><?= $inProgress ?></div>
    </div>

    <div class="report-card">
        <h4>Escalated</h4>
        <div class="metric"><?= $escalated ?></div>
    </div>

    <div class="report-card">
        <h4>Overdue</h4>
        <div class="metric danger"><?= $overdue ?></div>
    </div>

</div>

<!-- ================= STATUS BREAKDOWN SECTION ================= -->

<div style="margin-top:50px; display:flex; gap:50px; align-items:flex-start; flex-wrap:wrap;">

    <!-- LEFT SIDE: Chart -->
    <div style="width:360px; height:300px;">
        <h3 style="margin-bottom:15px;">Status Breakdown</h3>
        <canvas id="slaChart"></canvas>
    </div>

    <!-- RIGHT SIDE: Table -->
    <div class="table-wrap" style="flex:1;">
        <table>
            <thead>
                <tr>
                    <th>Status</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($statusRows as $row): ?>
                    <tr>
                        <td><?= htmlspecialchars($row['status']) ?></td>
                        <td><?= (int)$row['total'] ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

</div>

<!-- ================= CHART SCRIPT ================= -->

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('slaChart');

new Chart(ctx, {
    type: 'doughnut',
    data: {
        labels: <?= json_encode(array_column($statusRows, 'status')) ?>,
        datasets: [{
            data: <?= json_encode(array_column($statusRows, 'total')) ?>,
            backgroundColor: [
                '#f59e0b',
                '#10b981',
                '#ef4444',
                '#3b82f6',
                '#8b5cf6',
                '#6366f1'
            ]
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'bottom'
            }
        }
    }
});
</script>

<?php
require_once __DIR__ . '/../../../includes/helper.php';
renderHelper('index');
require_once __DIR__ . '/../../../includes/layout_footer.php'; ?>