<?php
// expiry_dashboard.php
require_once 'includes/auth.php';
require_role(['admin', 'inspector', 'coordinator']);

require_once 'db.php';

$me = current_user();
$windowDays = 45;

// Only APPROVED (Is_Locked=1) certificates are meaningful here — a draft
// job's expiry date is tentative until it's actually issued.
$stmt = $pdo->prepare(
    "SELECT * FROM tbl_jobs
     WHERE Is_Locked = 1
       AND Expiry_Date IS NOT NULL
       AND Expiry_Date <= DATE_ADD(CURDATE(), INTERVAL ? DAY)
     ORDER BY Expiry_Date ASC"
);
$stmt->execute([$windowDays]);
$jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

$today = new DateTime('today');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Expiry Dashboard — Liftek</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background-color: #f4f6f9; font-family: 'Segoe UI', Arial, sans-serif; }
        .row-expired { background-color: #fde2e2 !important; }
        .row-soon { background-color: #fff8e1 !important; }
    </style>
</head>
<body class="bg-light">
<div class="container-fluid py-4 px-4">

    <div class="d-flex justify-content-between align-items-center mb-4 pb-2 border-bottom">
        <div>
            <h2 class="fw-bold text-warning m-0"><i class="fa-solid fa-clock-rotate-left me-2"></i>EXPIRY DASHBOARD</h2>
            <p class="text-muted small m-0">Approved certificates expiring within <?= $windowDays; ?> days, or already expired.</p>
        </div>
        <div>
            <?php if (in_array($me['role'], ['admin', 'inspector'], true)): ?>
                <a href="index.php" class="btn btn-outline-primary fw-bold me-2"><i class="fa-solid fa-arrow-left me-1"></i> Register</a>
                <a href="reports.php" class="btn btn-outline-success fw-bold"><i class="fa-solid fa-file-shield me-1"></i> Reports</a>
            <?php else: ?>
                <a href="reports.php" class="btn btn-outline-success fw-bold me-2"><i class="fa-solid fa-file-shield me-1"></i> Reports</a>
                <a href="logout.php" class="btn btn-outline-danger fw-bold"><i class="fa-solid fa-right-from-bracket me-1"></i> Log Out</a>
            <?php endif; ?>
        </div>
    </div>

    <div class="row mb-4 g-3">
        <?php
            $expiredCount = 0;
            $soonCount = 0;
            foreach ($jobs as $j) {
                if (strtotime($j['Expiry_Date']) < $today->getTimestamp()) $expiredCount++; else $soonCount++;
            }
        ?>
        <div class="col-md-6">
            <div class="card border-danger">
                <div class="card-body text-center">
                    <div class="text-danger fw-bold fs-2"><?= $expiredCount; ?></div>
                    <div class="text-muted small">Already Expired</div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card border-warning">
                <div class="card-body text-center">
                    <div class="text-warning fw-bold fs-2"><?= $soonCount; ?></div>
                    <div class="text-muted small">Expiring Within <?= $windowDays; ?> Days</div>
                </div>
            </div>
        </div>
    </div>

    <div class="card shadow-sm border-0">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle m-0">
                    <thead class="table-dark">
                        <tr>
                            <th class="ps-3">Job No</th>
                            <th>Client Name</th>
                            <th>Category</th>
                            <th>Item Name</th>
                            <th>Expiry Date</th>
                            <th>Days Remaining</th>
                            <th class="text-center">Certificate</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($jobs)): ?>
                            <tr><td colspan="7" class="text-center text-muted py-4">Nothing expiring soon. 👍</td></tr>
                        <?php else: ?>
                            <?php foreach ($jobs as $j):
                                $expiry = new DateTime($j['Expiry_Date']);
                                $diffDays = (int) $today->diff($expiry)->format('%r%a');
                                $isExpired = $diffDays < 0;
                                $rowClass = $isExpired ? 'row-expired' : 'row-soon';
                            ?>
                                <tr class="<?= $rowClass; ?>">
                                    <td class="ps-3 fw-bold"><?= htmlspecialchars($j['Job_No']); ?></td>
                                    <td class="fw-semibold"><?= htmlspecialchars($j['Client_Name'] ?? 'N/A'); ?></td>
                                    <td><span class="badge bg-secondary"><?= htmlspecialchars($j['Category'] ?? '-'); ?></span></td>
                                    <td><?= htmlspecialchars($j['Item_Name'] ?? 'N/A'); ?></td>
                                    <td><?= htmlspecialchars($j['Expiry_Date']); ?></td>
                                    <td class="fw-bold <?= $isExpired ? 'text-danger' : 'text-warning'; ?>">
                                        <?= $isExpired ? abs($diffDays) . ' days ago' : $diffDays . ' days left'; ?>
                                    </td>
                                    <td class="text-center">
                                        <a href="generate_certificate.php?id=<?= (int) $j['ID']; ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                                            <i class="fa-solid fa-file-pdf"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>
</body>
</html>
