<?php
// reports.php
require_once 'includes/auth.php';
require_role(['admin', 'inspector', 'coordinator']); // Coordinator: read-only

require_once 'db.php';

$me = current_user();

$client   = $_GET['client'] ?? '';
$category = $_GET['category'] ?? '';
$status   = $_GET['status'] ?? '';
$month    = $_GET['month'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="csrf-token" content="<?= htmlspecialchars(csrf_token()); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reports — 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; }
        .table-header { background-color: #2c3e50; color: #fff; }
        .badge-pass { background-color: #198754; }
        .badge-fail { background-color: #dc3545; }
        .badge-pending { background-color: #ffc107; color: #000; }
        #toastContainer { position: fixed; top: 16px; right: 16px; z-index: 2000; }
    </style>
</head>
<body class="bg-light">

<div id="toastContainer"></div>

<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-success m-0"><i class="fa-solid fa-file-shield me-2"></i>REPORTS — APPROVED CERTIFICATES</h2>
            <p class="text-muted small m-0">Final, locked, and officially issued.</p>
        </div>
        <div>
            <?php if (in_array($me['role'], ['admin', 'inspector'], true)): ?>
                <a href="index.php" class="btn btn-outline-primary fw-bold"><i class="fa-solid fa-arrow-left me-1"></i> Back to Register</a>
            <?php endif; ?>
        </div>
    </div>

    <div class="card shadow-sm mb-4 border-0">
        <div class="card-body bg-white rounded p-3">
            <form method="GET" action="reports.php" class="row g-2 align-items-center">
                <div class="col-md-3">
                    <input type="text" name="client" class="form-control" placeholder="Search Client Name..." value="<?= htmlspecialchars($client); ?>">
                </div>
                <div class="col-md-2">
                    <select name="category" class="form-select">
                        <option value="">All Categories</option>
                        <option value="LLG" <?= $category === 'LLG' ? 'selected' : ''; ?>>LLG</option>
                        <option value="Appliance" <?= $category === 'Appliance' ? 'selected' : ''; ?>>Appliance</option>
                        <option value="Misc" <?= $category === 'Misc' ? 'selected' : ''; ?>>Misc</option>
                        <option value="Training" <?= $category === 'Training' ? 'selected' : ''; ?>>Training</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <select name="status" class="form-select">
                        <option value="">All Statuses</option>
                        <option value="Pass" <?= $status === 'Pass' ? 'selected' : ''; ?>>Pass</option>
                        <option value="Fail" <?= $status === 'Fail' ? 'selected' : ''; ?>>Fail</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <input type="month" name="month" class="form-control" value="<?= htmlspecialchars($month); ?>" title="Filter by approval month">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100 fw-bold"><i class="fa-solid fa-filter me-1"></i> Filter</button>
                </div>
                <div class="col-md-1">
                    <a href="reports.php" class="btn btn-outline-secondary w-100">Reset</a>
                </div>
            </form>
        </div>
    </div>

    <div class="card shadow-sm mb-4 border-0 border-start border-4 border-info">
        <div class="card-body bg-white rounded p-3">
            <form method="GET" action="export_certificates_zip.php" class="row g-2 align-items-center">
                <div class="col-auto fw-bold text-info"><i class="fa-solid fa-folder-tree me-1"></i> Download by Work Order:</div>
                <div class="col-md-3">
                    <input type="text" name="work_order_ref" class="form-control" placeholder="e.g. WO-2026-014" required>
                </div>
                <div class="col-auto">
                    <button type="submit" class="btn btn-info fw-bold"><i class="fa-solid fa-file-zipper me-1"></i> Download All as ZIP</button>
                </div>
                <div class="col-auto text-muted small">Only approved certificates sharing that reference are included.</div>
            </form>
        </div>
    </div>

    <div class="d-flex justify-content-end mb-2">
        <button type="button" id="exportSelectedBtn" class="btn btn-outline-info fw-bold" disabled>
            <i class="fa-solid fa-file-zipper me-1"></i> Export Selected (<span id="selectedCount">0</span>)
        </button>
    </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-header">
                        <tr>
                            <th class="ps-3"><input type="checkbox" id="selectAllCheckbox" class="form-check-input"></th>
                            <th>Job No</th>
                            <th>Issue Date</th>
                            <th>Client Name</th>
                            <th>Category</th>
                            <th>Item Name</th>
                            <th>Result</th>
                            <th>Approval</th>
                            <th class="text-center">Actions</th>
                        </tr>

                    </thead>
                    <tbody id="reportsTableBody">
                        <?php include 'includes/reports_table_rows.php'; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

<!-- Certificate Preview Modal — every "View"/"PDF" entry point opens the
     certificate in here instead of a new browser tab/page ("لا حاجة لاي
     صفحة جديدة بلمتصفح سواء كانت pdf او html"). Because the underlying
     page never navigates away, there's no "Back" button confusion either —
     closing the modal simply returns to exactly where you were. -->
<div class="modal fade" id="certificateModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content" style="height: 92vh;">
      <div class="modal-header py-2">
        <h6 class="modal-title fw-bold m-0" id="certificateModalLabel">Certificate</h6>
        <div class="ms-auto me-2 btn-group btn-group-sm">
          <button type="button" class="btn btn-outline-primary" id="certModalViewBtn" onclick="setCertificateModalView('html')">
            <i class="fa-solid fa-eye me-1"></i> View
          </button>
          <button type="button" class="btn btn-outline-success" id="certModalPdfBtn" onclick="setCertificateModalView('pdf')">
            <i class="fa-solid fa-file-pdf me-1"></i> PDF
          </button>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body p-0">
        <!-- BUG FIX (client report 2026-08-20): clicking "PDF" was opening a
             brand new browser tab instead of showing the PDF inside this
             modal iframe. Root cause: generate_certificate_pdf.php streams
             with Content-Disposition: attachment, and modern Chrome BLOCKS
             a download triggered by an iframe's own navigation unless that
             iframe explicitly opts in via the `allow="downloads"`
             Permissions-Policy attribute — when blocked, Chrome's fallback
             is to open the resource in a new top-level tab instead, which
             is exactly the "no need for a new page" behaviour the client
             said they don't want. Adding allow="downloads" lets the
             download happen silently in-place, exactly as originally
             intended (modal stays open, no new tab). -->
        <iframe id="certificateModalFrame" src="about:blank" allow="downloads" style="width:100%; height:100%; border:0;"></iframe>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
var currentQueryString = window.location.search;

// Opens a certificate (HTML view by default) inside the shared modal above
// instead of a new tab. &embed=1 tells generate_certificate.php to hide its
// own "Back" link, since the modal's close button already covers that.
var certModalJobId = null;
function openCertificateModal(jobId, mode) {
    certModalJobId = jobId;
    bootstrap.Modal.getOrCreateInstance(document.getElementById('certificateModal')).show();
    setCertificateModalView(mode === 'pdf' ? 'pdf' : 'html');
}
function setCertificateModalView(mode) {
    if (!certModalJobId) return;
    var frame = document.getElementById('certificateModalFrame');
    var viewBtn = document.getElementById('certModalViewBtn');
    var pdfBtn = document.getElementById('certModalPdfBtn');
    if (mode === 'pdf') {
        // Streamed with Content-Disposition: attachment — this triggers a
        // download rather than replacing the iframe's content, so the
        // modal simply stays open on whatever it was already showing.
        frame.src = 'generate_certificate_pdf.php?id=' + encodeURIComponent(certModalJobId) + '&embed=1';
        pdfBtn.classList.replace('btn-outline-success', 'btn-success');
        viewBtn.classList.replace('btn-primary', 'btn-outline-primary');
    } else {
        frame.src = 'generate_certificate.php?id=' + encodeURIComponent(certModalJobId) + '&embed=1&from=reports';
        viewBtn.classList.replace('btn-outline-primary', 'btn-primary');
        pdfBtn.classList.replace('btn-success', 'btn-outline-success');
    }
}

function showToast(message, isError) {
    var container = document.getElementById('toastContainer');
    var toast = document.createElement('div');
    toast.className = 'alert ' + (isError ? 'alert-danger' : 'alert-success') + ' shadow-sm mb-2';
    toast.style.minWidth = '280px';
    toast.textContent = message;
    container.appendChild(toast);
    setTimeout(function () { toast.remove(); }, 4000);
}

function refreshReportsTable() {
    fetch('includes/reports_table_rows.php' + currentQueryString)
        .then(function (r) { return r.text(); })
        .then(function (html) {
            document.getElementById('reportsTableBody').innerHTML = html;
            bindUnlockButtons();
            document.getElementById('selectAllCheckbox').checked = false;
            updateExportButton();
        });
}

function bindUnlockButtons() {
    document.querySelectorAll('.js-unlock-job').forEach(function (btn) {
        btn.addEventListener('click', function () {
            if (!confirm('Unlock this certificate for editing? It will move back to the active register.')) return;
            var jobId = btn.getAttribute('data-job-id');
            var formData = new FormData();
            formData.append('job_id', jobId);
            formData.append('csrf_token', document.querySelector('meta[name="csrf-token"]').content);

            fetch('unlock_job.php', { method: 'POST', body: formData })
                .then(function (r) {
                    if (r.status === 401) { window.location.href = 'login.php'; return Promise.reject(new Error('Session expired.')); }
                    return r.json();
                })
                .then(function (data) {
                    showToast(data.message, data.status !== 'success');
                    if (data.status === 'success') refreshReportsTable();
                })
                .catch(function (err) { showToast(err.message, true); });
        });
    });
}

bindUnlockButtons();

// Batch export: collects checked row IDs, enables/updates the button, and
// on click navigates to the shared zip-export endpoint with the explicit
// ID list — reuses the exact same download logic as the Work Order box.
function updateExportButton() {
    var checked = document.querySelectorAll('.js-row-checkbox:checked');
    var btn = document.getElementById('exportSelectedBtn');
    document.getElementById('selectedCount').textContent = checked.length;
    btn.disabled = checked.length === 0;
}

document.addEventListener('change', function (e) {
    if (e.target.id === 'selectAllCheckbox') {
        document.querySelectorAll('.js-row-checkbox').forEach(function (cb) { cb.checked = e.target.checked; });
        updateExportButton();
    } else if (e.target.classList.contains('js-row-checkbox')) {
        updateExportButton();
    }
});

document.getElementById('exportSelectedBtn').addEventListener('click', function () {
    var ids = Array.prototype.map.call(document.querySelectorAll('.js-row-checkbox:checked'), function (cb) {
        return cb.value;
    });
    if (!ids.length) return;
    window.location.href = 'export_certificates_zip.php?ids=' + ids.join(',');
});
</script>
</body>
</html>
