<?php
require_once __DIR__ . "/auth/init.php";

authorize();
$user_id = $_SESSION['user_id'];

/* ===============================
   USER INFO
=================================*/
$stmt = mysqli_prepare($conn, "SELECT full_name FROM users WHERE id = ?");
mysqli_stmt_bind_param($stmt, "i", $user_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$user = mysqli_fetch_assoc($result);

/* ===============================
   COUNTS
=================================*/
function getCount($conn, $query) {
    $result = mysqli_query($conn, $query);
    if ($result) {
        return mysqli_fetch_assoc($result)['total'];
    }
    return 0;
}

$total_equipment = getCount($conn, "SELECT COUNT(*) as total FROM equipment");
$active_count = getCount($conn, "SELECT COUNT(*) as total FROM equipment WHERE status='Active'");
$maintenance_count = getCount($conn, "SELECT COUNT(*) as total FROM equipment WHERE status='Under Maintenance'");
$inactive_count = getCount($conn, "SELECT COUNT(*) as total FROM equipment WHERE status='Inactive'");
$overdue_count = getCount($conn, "SELECT COUNT(*) as total FROM maintenance_schedule WHERE status='Overdue'");

/* ===============================
   UPCOMING (SYNCED WITH SYSTEM)
=================================*/
$upcoming_query = "
    SELECT 
        e.equipment_name,
        mr.maintenance_date,
        mr.status
    FROM maintenance_record mr
    JOIN equipment e ON mr.equipment_id = e.id
    WHERE mr.status = 'In Progress'
    ORDER BY mr.maintenance_date ASC
    LIMIT 5
";
$upcoming_result = mysqli_query($conn, $upcoming_query);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Dashboard - QRCareTrack</title>

    <link rel="stylesheet" href="assets/style.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <style>
        /* ================= CHART LAYOUT ================= */
        .chart-wrapper {
            display: flex;
            align-items: center;
            gap: 40px;
        }

        .chart-container {
            width: 300px;
            height: 300px;
        }

        .chart-legend {
            display: flex;
            flex-direction: column;
            gap: 12px;
            font-size: 14px;
            min-width: 180px;
        }

        .legend-item {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .legend-item strong {
            margin-left: auto;
        }

        .dot {
            width: 12px;
            height: 12px;
            border-radius: 50%;
        }

        .dot.active { background: #30D0C3; }
        .dot.maintenance { background: #2196f3; }
        .dot.inactive { background: #ff9800; }

        /* TABLE */
        table {
            width: 100%;
            border-collapse: collapse;
        }

        table th, table td {
            padding: 12px;
            border-bottom: 1px solid #eee;
        }

        table th {
            text-align: left;
            background: #f9f9f9;
        }

        .badge {
            background: #e5e7eb;
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 12px;
        }
    </style>

</head>

<body>

<?php include __DIR__ . '/includes/sidebar.php'; ?>

<div class="main">

    <h1>Dashboard</h1>
    <p>Welcome back, <strong><?= htmlspecialchars($user['full_name'] ?? 'User'); ?></strong>.</p>

    <!-- SUMMARY CARDS -->
    <div class="cards">

        <div class="card">
            <div>
                <h3><?= $total_equipment; ?></h3>
                <p>Total Equipment</p>
            </div>
            <i class="fas fa-box"></i>
        </div>

        <div class="card">
            <div>
                <h3><?= $maintenance_count; ?></h3>
                <p>Under Maintenance</p>
            </div>
            <i class="fas fa-tools"></i>
        </div>

        <div class="card">
            <div>
                <h3><?= $overdue_count; ?></h3>
                <p>Overdue Schedule</p>
            </div>
            <i class="fas fa-calendar-times"></i>
        </div>

    </div>

    <!-- CHART + TABLE -->
    <div class="section">

        <!-- CHART -->
        <div class="box">
            <h3>Equipment Status Overview</h3>

            <div class="chart-wrapper">

                <!-- PIE CHART -->
                <div class="chart-container">
                    <canvas id="statusChart"></canvas>
                </div>

                <!-- LEGEND WITH NUMBERS -->
                <div class="chart-legend">

                    <div class="legend-item">
                        <span class="dot active"></span>
                        Active
                        <strong><?= $active_count ?></strong>
                    </div>

                    <div class="legend-item">
                        <span class="dot maintenance"></span>
                        Under Maintenance
                        <strong><?= $maintenance_count ?></strong>
                    </div>

                    <div class="legend-item">
                        <span class="dot inactive"></span>
                        Inactive
                        <strong><?= $inactive_count ?></strong>
                    </div>

                </div>

            </div>
        </div>

        <!-- TABLE -->
        <div class="box">
            <h3>Upcoming Maintenance</h3>

            <table>
                <tr>
                    <th>Equipment</th>
                    <th>Date</th>
                    <th>Status</th>
                </tr>

                <?php if (mysqli_num_rows($upcoming_result) > 0): ?>
                    <?php while ($row = mysqli_fetch_assoc($upcoming_result)): ?>
                        <tr>
                            <td><?= htmlspecialchars($row['equipment_name']); ?></td>
                            <td>
                                <?= !empty($row['maintenance_date'])
                                    ? date("d/m/Y", strtotime($row['maintenance_date']))
                                    : '-' ?>
                            </td>
                            <td>
                                <span class="badge">
                                    <?= htmlspecialchars($row['status']); ?>
                                </span>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="3" style="text-align:center;">
                            No upcoming maintenance
                        </td>
                    </tr>
                <?php endif; ?>

            </table>
        </div>

    </div>

</div>

<!-- CHART SCRIPT -->
<script>
new Chart(document.getElementById('statusChart'), {
    type: 'doughnut',
    data: {
        labels: ['Active', 'Under Maintenance', 'Inactive'],
        datasets: [{
            data: [
                <?= $active_count ?>,
                <?= $maintenance_count ?>,
                <?= $inactive_count ?>
            ],
            backgroundColor: [
                '#30D0C3',
                '#2196f3',
                '#ff9800'
            ],
            borderWidth: 0
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false
            }
        }
    }
});
</script>

</body>
</html>