<?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 (SYNCED WITH EQUIPMENT)
=================================*/
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 equipment 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>
        /* ================= CARD DESIGN EXTENSIONS ================= */
        .cards-5 {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }
        .card-bordered {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.04);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .card-bordered i {
            font-size: 24px;
            color: #94a3b8;
        }

        /* ================= 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.overdue { background: #ef4444; }
        .dot.maintenance { background: #f39c12; }
        .dot.inactive { background: #7f8c8d; }

        /* 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>

    <div class="cards-5">

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

        <div class="card-bordered" style="border-left: 5px solid #2ecc71;">
            <div>
                <h3><?= $active_count; ?></h3>
                <p style="color:#2ecc71; font-weight:bold;">Active</p>
            </div>
            <i class="fas fa-check-circle" style="color:#2ecc71;"></i>
        </div>

        <div class="card-bordered" style="border-left: 5px solid #ef4444;">
            <div>
                <h3><?= $overdue_count; ?></h3>
                <p style="color:#ef4444; font-weight:bold;">Overdue</p>
            </div>
            <i class="fas fa-calendar-times" style="color:#ef4444;"></i>
        </div>

        <div class="card-bordered" style="border-left: 5px solid #f39c12;">
            <div>
                <h3><?= $maintenance_count; ?></h3>
                <p style="color:#f39c12; font-weight:bold;">Under Maintenance</p>
            </div>
            <i class="fas fa-tools" style="color:#f39c12;"></i>
        </div>

        <div class="card-bordered" style="border-left: 5px solid #7f8c8d;">
            <div>
                <h3><?= $inactive_count; ?></h3>
                <p style="color:#7f8c8d; font-weight:bold;">Inactive</p>
            </div>
            <i class="fas fa-times-circle" style="color:#7f8c8d;"></i>
        </div>

    </div>

    <div class="section">

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

            <div class="chart-wrapper">

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

                <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 overdue"></span>
                        Overdue
                        <strong><?= $overdue_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>

        <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>

<script>
new Chart(document.getElementById('statusChart'), {
    type: 'doughnut',
    data: {
        labels: ['Active', 'Overdue', 'Under Maintenance', 'Inactive'],
        datasets: [{
            data: [
                <?= $active_count ?>,
                <?= $overdue_count ?>,
                <?= $maintenance_count ?>,
                <?= $inactive_count ?>
            ],
            backgroundColor: [
                '#30D0C3', // Active
                '#ef4444', // Overdue
                '#f39c12', // Under Maintenance
                '#7f8c8d'  // Inactive
            ],
            borderWidth: 0
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false
            }
        }
    }
});
</script>

</body>
</html>