<?php
// includes/reports_table_rows.php
// Mirrors table_rows.php but for the OPPOSITE set: only approved/locked
// certificates (Is_Locked = 1). This is the only place the "Certificate"
// (PDF/print) button appears anywhere in the system — draft/unlocked jobs
// in the main register never show it, by design: a certificate is only
// meant to be handed out once it's been formally approved.

if (!isset($pdo)) {
    require __DIR__ . '/../db.php';
}
// BUG FIX: this file assumed includes/auth.php was already loaded by
// whatever included it — true when reports.php requires it directly, but
// FALSE when the browser's AJAX refresh (refreshReportsTable() in
// reports.php) fetches this file directly as its own top-level request.
// That path never ran includes/auth.php, so current_user() below was an
// undefined-function fatal error every time the table auto-refreshed.
if (!function_exists('current_user')) {
    require_once __DIR__ . '/auth.php';
}

// SECURITY FIX: this fragment is fetched directly via AJAX (see
// reports.php's refreshReportsTable()), which bypasses reports.php's own
// require_role() gate entirely. Without an equivalent check here, anyone
// unauthenticated could request this file directly and read every
// approved certificate's client name, result, and approver. Mirrors
// reports.php's own role gate exactly. ajax=true returns a clean 401/403
// instead of an HTML redirect, so a logged-out request never dumps a
// login page's HTML into the reports table body.
require_role(['admin', 'inspector', 'coordinator'], true);

$me = current_user();

$client   = $_GET['client'] ?? '';
$category = $_GET['category'] ?? '';
$status   = $_GET['status'] ?? '';
$month    = $_GET['month'] ?? ''; // YYYY-MM, optional

$sql = "SELECT j.*, u.Name AS ApproverName
        FROM tbl_jobs j
        LEFT JOIN tbl_users u ON u.UserID = j.Approved_By
        WHERE j.Is_Locked = 1";
$params = [];

if (!empty($client)) {
    $sql .= " AND j.Client_Name LIKE ?";
    $params[] = "%$client%";
}
if (!empty($category)) {
    $sql .= " AND j.Category = ?";
    $params[] = $category;
}
if (!empty($status)) {
    $sql .= " AND j.Approval = ?";
    $params[] = $status;
}
if (!empty($month)) {
    $sql .= " AND DATE_FORMAT(j.Approved_At, '%Y-%m') = ?";
    $params[] = $month;
}

$sql .= " ORDER BY j.Approved_At DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<?php if (count($jobs) > 0): ?>
    <?php foreach ($jobs as $j): ?>
        <tr data-job-id="<?= (int) $j['ID']; ?>">
            <td class="ps-3"><input type="checkbox" class="form-check-input js-row-checkbox" value="<?= (int) $j['ID']; ?>"></td>
            <td class="fw-bold text-primary">
                <?= htmlspecialchars($j['Job_No']); ?>
                <?php if (!empty($j['Work_Order_Ref'])): ?>
                    <div class="text-muted small fw-normal"><i class="fa-solid fa-folder-tree me-1"></i><?= htmlspecialchars($j['Work_Order_Ref']); ?></div>
                <?php endif; ?>
            </td>
            <td><?= htmlspecialchars($j['Issue_Date'] ?? '-'); ?></td>
            <td class="fw-semibold"><?= htmlspecialchars($j['Client_Name'] ?? 'N/A'); ?></td>
            <td><span class="badge bg-secondary"><?= htmlspecialchars($j['Category'] ?? 'NDT'); ?></span></td>
            <td><?= htmlspecialchars($j['Item_Name'] ?? 'N/A'); ?></td>
            <td>
                <?php
                    $app = strtolower($j['Approval'] ?? 'pending');
                    $badgeClass = $app === 'pass' ? 'badge-pass' : ($app === 'fail' ? 'badge-fail' : 'badge-pending');
                ?>
                <span class="badge <?= $badgeClass; ?> fw-bold"><?= strtoupper(htmlspecialchars($j['Approval'] ?? 'PENDING')); ?></span>
            </td>
            <td class="small">
                <span class="badge" style="background: #198754; font-size: 11px; padding: 5px 8px;">
                    <i class="fa-solid fa-circle-check me-1"></i>APPROVED &amp; LOCKED
                </span>
                <div class="text-muted mt-1"><?= htmlspecialchars($j['ApproverName'] ?? '-'); ?> — <?= htmlspecialchars($j['Approved_At'] ?? '-'); ?></div>
            </td>
            <td class="text-center" style="white-space: nowrap;">
                <!-- BUG FIX: these used to be target="_blank" links, opening a
                     brand new browser tab/page for every certificate. Both
                     now open the shared in-page modal instead (see
                     reports.php's openCertificateModal()) — no new tab, no
                     "Back" navigation confusion. -->
                <button type="button" class="btn btn-sm btn-primary fw-bold"
                        onclick="openCertificateModal(<?= (int) $j['ID']; ?>, 'html')"
                        title="View &amp; Print Certificate">
                    <i class="fa-solid fa-eye me-1"></i> View
                </button>
                <button type="button" class="btn btn-sm btn-success fw-bold"
                        onclick="openCertificateModal(<?= (int) $j['ID']; ?>, 'pdf')"
                        title="Download PDF Certificate">
                    <i class="fa-solid fa-file-pdf me-1"></i> PDF
                </button>
                <?php if ($me && $me['role'] === 'admin'): ?>
                    <button type="button" class="btn btn-sm btn-outline-warning js-unlock-job"
                            data-job-id="<?= (int) $j['ID']; ?>" title="Unlock for editing">
                        <i class="fa-solid fa-lock-open"></i>
                    </button>
                <?php endif; ?>
            </td>
        </tr>
    <?php endforeach; ?>
<?php else: ?>
    <tr>
        <td colspan="9" class="text-center text-muted py-4">No approved certificates match your search parameters.</td>
    </tr>
<?php endif; ?>
