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

authorize();

/* =========================
   FILTERS & SEARCH CONFIG
========================= */
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';
$department_filter = $_GET['department'] ?? '';
$category_filter = $_GET['category'] ?? '';
$search = $_GET['search'] ?? '';

$where = "WHERE mr.status='Completed'";
$params = [];
$types = '';

if (!empty($start_date)) {
    $where .= " AND mr.maintenance_date >= ?";
    $params[] = $start_date;
    $types .= 's';
}
if (!empty($end_date)) {
    $where .= " AND mr.maintenance_date <= ?";
    $params[] = $end_date;
    $types .= 's';
}
if (!empty($department_filter)) {
    $where .= " AND e.department_id = ?";
    $params[] = intval($department_filter);
    $types .= 'i';
}
if (!empty($category_filter)) {
    $where .= " AND e.category = ?";
    $params[] = $category_filter;
    $types .= 's';
}
if (!empty($search)) {
    $where .= " AND (e.equipment_name LIKE ? OR e.serial_number LIKE ?)";
    $search_param = "%" . $search . "%";
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'ss';
}

/* =========================
   ADVANCED RECORDS QUERY (Direct mr.approved_by mapping)
========================= */
$sql = "SELECT 
            mr.id AS mr_id, mr.description AS mr_desc, mr.maintenance_date, mr.created_at AS mr_created, 
            mr.proof_image, mr.hod_comment, mr.updated_at AS mr_updated,
            e.id AS equipment_id, e.equipment_name, e.category, e.serial_number, e.location, e.status AS eq_status,
            d.name AS department_name,
            u_tech.full_name AS technician_name,
            u_req.full_name AS requester_name,
            u_hod.full_name AS hod_name, -- Pulled from the new maintenance_record column
            req.urgency, req.issue_description, req.issue_image, req.reviewed_at
        FROM maintenance_record mr
        JOIN equipment e ON mr.equipment_id = e.id
        LEFT JOIN departments d ON e.department_id = d.id
        LEFT JOIN users u_tech ON mr.technician_id = u_tech.id
        LEFT JOIN users u_hod ON mr.approved_by = u_hod.id -- Join through the new approved_by column 
        LEFT JOIN maintenance_request req ON mr.request_id = req.id
        LEFT JOIN users u_req ON req.requested_by = u_req.id
        $where
        ORDER BY mr.maintenance_date ASC";

$stmt = mysqli_prepare($conn, $sql);
if (!empty($params)) {
    mysqli_stmt_bind_param($stmt, $types, ...$params);
}
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$records = mysqli_fetch_all($result, MYSQLI_ASSOC);

/* =========================
   DROPDOWN ARCHIVE DATA
========================= */
$departmentResult = mysqli_query($conn, "SELECT id, name FROM departments ORDER BY name ASC");
$categoryResult = mysqli_query($conn, "SELECT DISTINCT category FROM equipment WHERE category IS NOT NULL ORDER BY category ASC");
?>

<!DOCTYPE html>
<html>
<head>
    <title>Maintenance Report - QRCareTrack</title>
    <link rel="stylesheet" href="assets/style.css">
    <link rel="stylesheet" href="assets/maintenance.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.25/jspdf.plugin.autotable.min.js"></script>
    <style>
        .filter-bar { margin-bottom: 20px; display:flex; gap:10px; flex-wrap:wrap; align-items:center; background:#ffffff; padding:15px; border-radius:8px; border:1px solid #ccc; }
        .filter-bar input, .filter-bar select { padding:8px 12px; border-radius:6px; border:1px solid #ccc; font-size:14px; }
        .btn { padding:8px 14px; border:none; border-radius:6px; cursor:pointer; background:#0f766e; color:#fff; font-weight:600; display:inline-flex; align-items:center; gap:6px; font-size:14px; text-decoration:none; }
        .btn:hover { background:#115e59; }
        .btn-reset { background:#64748b; }
        .btn-reset:hover { background:#475569; }
        .btn-pdf { background:#e74c3c; }
        .btn-pdf:hover { background:#c0392b; }
        
        .table-container { overflow-x:auto; background:#fff; border-radius:8px; border:1px solid #ccc; }
        table { border-collapse: collapse; width:100%; }
        table th, table td { padding:12px; font-size:14px; text-align:left; border-bottom:1px solid #eee; }
        table th { background:#f8fafc; color:#0f766e; font-weight:700; border-bottom:2px solid #cbd5e1; }
        
        /* Modal Style Override */
        .modal { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(15,23,42,0.6); justify-content:center; align-items:center; z-index:9999; backdrop-filter: blur(4px); }
        .modal-content { background:#fff; padding:25px; border-radius:14px; max-width:850px; width:95%; max-height:85vh; overflow-y:auto; position:relative; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.15); }
        .close { position:absolute; top:15px; right:20px; cursor:pointer; font-size:24px; font-weight:bold; color:#64748b; transition: color 0.2s; }
        .close:hover { color:#0f172a; }
        
        .popup-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 15px; }
        .popup-section { background:#f8fafc; border:1px solid #e2e8f0; border-radius:10px; padding:15px; }
        .popup-section h4 { margin:0 0 10px 0; color:#0f766e; border-bottom:2px solid #e2e8f0; padding-bottom:5px; font-size:15px; }
        .detail-item { font-size:13px; margin-bottom:6px; color:#334155; }
        .detail-item strong { color:#0f172a; min-width:120px; display:inline-block; }
        .image-preview-box { display:flex; gap:10px; margin-top:10px; }
        .image-preview-box div { flex:1; text-align:center; }
        .image-preview-box img { width:100%; max-height:140px; object-fit:cover; border-radius:6px; border:1px solid #cbd5e1; }
        
        @media(max-width:768px){
            .popup-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
<?php include "includes/sidebar.php"; ?>

<div class="main">
    <h1 style="color:#0f766e; margin-bottom:5px;">Maintenance Reports (Completed)</h1>
    <p style="color:#64748b; margin-bottom:20px;">Review logs, check personnel processing chains, and export analytical outputs.</p>

    <form method="GET" class="filter-bar">
        <input type="text" name="search" placeholder="Search item or serial..." value="<?= htmlspecialchars($search) ?>">
        
        <select name="category">
            <option value="">All Categories</option>
            <?php while($cat = mysqli_fetch_assoc($categoryResult)): ?>
                <option value="<?= htmlspecialchars($cat['category']) ?>" <?=($category_filter == $cat['category']) ? 'selected' : ''?>>
                    <?= htmlspecialchars($cat['category']) ?>
                </option>
            <?php endwhile; ?>
        </select>

        <select name="department">
            <option value="">All Departments</option>
            <?php while($dept = mysqli_fetch_assoc($departmentResult)): ?>
                <option value="<?= $dept['id'] ?>" <?=($department_filter == $dept['id']) ? 'selected' : ''?>>
                    <?= htmlspecialchars($dept['name']) ?>
                </option>
            <?php endwhile; ?>
        </select>

        <input type="date" name="start_date" value="<?= htmlspecialchars($start_date) ?>" title="Start Date">
        <input type="date" name="end_date" value="<?= htmlspecialchars($end_date) ?>" title="End Date">

        <button type="submit" class="btn"><i class="fa-solid fa-magnifying-glass"></i> Filter</button>
        <a href="reports.php" class="btn btn-reset"><i class="fa-solid fa-rotate-left"></i> Reset</a>
        <button type="button" id="download-pdf" class="btn btn-pdf"><i class="fa-solid fa-file-pdf"></i> Download PDF</button>
    </form>

    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Equipment</th>
                    <th>Category</th>
                    <th>Location</th>
                    <th>Department</th>
                    <th>Serial Number</th>
                    <th>Execution Date</th>
                    <th>Description Summary</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
            <?php if(!empty($records)): ?>
                <?php foreach($records as $i => $r): ?>
                    <tr>
                        <td><?= $i+1 ?></td>
                        <td><strong><?= htmlspecialchars($r['equipment_name']) ?></strong></td>
                        <td><?= htmlspecialchars($r['category']) ?></td>
                        <td><?= htmlspecialchars($r['location'] ?? '-') ?></td>
                        <td><?= htmlspecialchars($r['department_name'] ?? '-') ?></td>
                        <td><code><?= htmlspecialchars($r['serial_number'] ?? '-') ?></code></td>
                        <td><?= $r['maintenance_date'] ? date("d/m/Y", strtotime($r['maintenance_date'])) : '-' ?></td>
                        <td><?= htmlspecialchars($r['mr_desc'] ?? '-') ?></td>
                        <td>
                            <button class="btn view-details" data-index="<?= $i ?>"><i class="fa-solid fa-circle-info"></i> Details</button>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="9" style="text-align:center; padding:30px; color:#64748b;">No completed records matched your filter metrics.</td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div id="details-modal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <div id="modal-body"></div>
    </div>
</div>

<script>
const records = <?= json_encode($records) ?>;
const modal = document.getElementById('details-modal');
const modalBody = document.getElementById('modal-body');
const closeBtn = document.querySelector('.close');

document.querySelectorAll('.view-details').forEach(btn => {
    btn.addEventListener('click', () => {
        const index = btn.dataset.index;
        const r = records[index];
        
        const issueImg = r.issue_image ? `assets/issue_images/${r.issue_image}` : 'assets/images/placeholder.png';
        const proofImg = r.proof_image ? `assets/issue_images/${r.proof_image}` : 'assets/images/placeholder.png';
        
        modalBody.innerHTML = `
            <h2 style="color:#0f766e; margin:0 0 5px 0;">Maintenance Fulfillment Summary</h2>
            <p style="color:#64748b; margin:0 0 15px 0;">Comprehensive verification details for Asset EQP-${String(r.equipment_id).padStart(4, '0')}</p>
            
            <div class="popup-grid">
                <div class="popup-section">
                    <h4><i class="fa-solid fa-cubes"></i> Equipment Specifics</h4>
                    <div class="detail-item"><strong>Asset Name:</strong> ${r.equipment_name}</div>
                    <div class="detail-item"><strong>Category:</strong> ${r.category}</div>
                    <div class="detail-item"><strong>Serial Number:</strong> ${r.serial_number || '-'}</div>
                    <div class="detail-item"><strong>Location:</strong> ${r.location || '-'}</div>
                    <div class="detail-item"><strong>Department:</strong> ${r.department_name || '-'}</div>
                    <div class="detail-item"><strong>Current Status:</strong> ${r.eq_status}</div>
                </div>

                <div class="popup-section">
                    <h4><i class="fa-solid fa-user-shield"></i> Chain of Custody</h4>
                    <div class="detail-item"><strong>Requested By:</strong> ${r.requester_name || 'System / Automated'}</div>
                    <div class="detail-item"><strong>Urgency Factor:</strong> Level ${r.urgency || '5'}/10</div>
                    <div class="detail-item"><strong>Approved By (HOD):</strong> ${r.hod_name || 'N/A or Auto-Approved'}</div>
                    <div class="detail-item"><strong>Reviewed At:</strong> ${r.reviewed_at || '-'}</div>
                    <div class="detail-item"><strong>Assigned Technician:</strong> ${r.technician_name || 'Unassigned'}</div>
                </div>
            </div>

            <div class="popup-grid" style="margin-top:15px;">
                <div class="popup-section">
                    <h4><i class="fa-solid fa-triangle-exclamation"></i> Reported Discrepancy</h4>
                    <p style="font-size:13px; background:#fff; padding:10px; border-radius:6px; border:1px solid #e2e8f0; margin:0;">
                        ${r.issue_description || 'No baseline request profile provided.'}
                    </p>
                </div>

                <div class="popup-section">
                    <h4><i class="fa-solid fa-square-check"></i> Technician Action Log</h4>
                    <div class="detail-item"><strong>Fulfillment Date:</strong> ${r.maintenance_date}</div>
                    <p style="font-size:13px; background:#fff; padding:10px; border-radius:6px; border:1px solid #e2e8f0; margin:5px 0 0 0;">
                        ${r.mr_desc || 'No specific technical comments log saved.'}
                    </p>
                    ${r.hod_comment ? `<div class="detail-item" style="margin-top:8px;"><strong>HOD Auditing Note:</strong> <small style="color:#64748b;">${r.hod_comment}</small></div>` : ''}
                </div>
            </div>

            <div class="image-preview-box">
                <div>
                    <span style="font-size:12px; font-weight:600; color:#64748b; display:block; margin-bottom:4px;">Defect Image Attachment</span>
                    <img src="${issueImg}" alt="Defect File Presentation" onerror="this.src='assets/images/placeholder.png'">
                </div>
                <div>
                    <span style="font-size:12px; font-weight:600; color:#64748b; display:block; margin-bottom:4px;">Technical Resolution Proof</span>
                    <img src="${proofImg}" alt="Fulfillment File Presentation" onerror="this.src='assets/images/placeholder.png'">
                </div>
            </div>
        `;
        modal.style.display = 'flex';
    });
});

closeBtn.onclick = () => modal.style.display = 'none';
window.onclick = e => { if (e.target == modal) modal.style.display = 'none'; };

/* =========================
   COMPREHENSIVE EXPORT SYSTEM (jsPDF)
========================= */
document.getElementById('download-pdf').addEventListener('click', () => {
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF('p', 'mm', 'a4');
    
    // Header
    doc.setFontSize(20);
    doc.setTextColor(15, 118, 110);
    doc.text("QRCareTrack Executive Report", 14, 20);
    
    doc.setFontSize(10);
    doc.setTextColor(100, 116, 139);
    doc.text("Completed Maintenance Logs & Workflow Verification Archives", 14, 26);
    doc.text(`Exported: ${new Date().toLocaleDateString('en-GB')} ${new Date().toLocaleTimeString('en-GB')}`, 14, 31);
    
    doc.setDrawColor(226, 232, 240);
    doc.line(14, 35, 196, 35);

    // Index Table Summary
    doc.setFontSize(13);
    doc.setTextColor(15, 118, 110);
    doc.text("1. High-Level Summary Index", 14, 43);

    const summaryHeaders = [["#", "Equipment Name", "Serial Key", "Department", "Resolved On", "Technician"]];
    const summaryData = records.map((r, i) => [
        i + 1,
        r.equipment_name,
        r.serial_number || '-',
        r.department_name || '-',
        r.maintenance_date ? r.maintenance_date.split(' ')[0] : '-',
        r.technician_name || 'Unassigned'
    ]);

    doc.autoTable({
        startY: 47,
        head: summaryHeaders,
        body: summaryData,
        styles: { fontSize: 9, cellPadding: 3 },
        headStyles: { fillColor: [15, 118, 110] },
        margin: { left: 14, right: 14 }
    });

    // Workflow Audit Breakdown
    let currentY = doc.lastAutoTable.finalY + 15;
    
    doc.setFontSize(13);
    doc.setTextColor(15, 118, 110);
    doc.text("2. Complete Workflow Audit Trails", 14, currentY);
    currentY += 5;

    records.forEach((r, i) => {
        if (currentY > 230) {
            doc.addPage();
            currentY = 20;
        }

        doc.setFontSize(10);
        doc.setTextColor(15, 118, 110);
        doc.setFont(undefined, 'bold');
        doc.text(`Log Entry #${i + 1}: ${r.equipment_name} (Serial: ${r.serial_number || 'N/A'})`, 14, currentY);
        doc.setFont(undefined, 'normal');
        currentY += 4;

        const technicalDetailsHeaders = [["Detail Field", "Recorded Operational Profile Info"]];
        const technicalDetailsRows = [
            ["Asset Identifiers", `ID: EQP-${String(r.equipment_id).padStart(4,'0')} | Category: ${r.category} | Location: ${r.location || '-'}`],
            ["Department Context", r.department_name || '-'],
            ["Workflow Initiation", `Requested By: ${r.requester_name || 'System Auto'} | Urgency Factor: Level ${r.urgency || '5'}/10`],
            ["Administrative Chain", `Approved By: ${r.hod_name || 'N/A / Auto-Approved'} | Reviewed At: ${r.reviewed_at || '-'}`],
            ["Fulfillment Personnel", `Technician Assigned: ${r.technician_name || 'Unassigned'}`],
            ["Reported Issue Description", r.issue_description || 'No baseline report text profile context loaded.'],
            ["Resolution Log Details", `Completed On: ${r.maintenance_date} \nLog Notes: ${r.mr_desc || '-'}`]
        ];

        if (r.hod_comment) {
            technicalDetailsRows.push(["HOD Closing Evaluation Note", r.hod_comment]);
        }

        doc.autoTable({
            startY: currentY,
            head: technicalDetailsHeaders,
            body: technicalDetailsRows,
            theme: 'striped',
            styles: { fontSize: 8, cellPadding: 2, overflow: 'linebreak' },
            headStyles: { fillColor: [100, 116, 139] },
            columnStyles: {
                0: { cellWidth: 45, fontStyle: 'bold', fillColor: [248, 250, 252] },
                1: { cellWidth: 'auto' }
            },
            margin: { left: 14, right: 14 },
            pageBreak: 'avoid'
        });

        currentY = doc.lastAutoTable.finalY + 10;
    });

    doc.save("Completed_Comprehensive_Maintenance_Report.pdf");
});
</script>
</body>
</html>