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

authorize();
// Filter dates
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';

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

if ($start_date) {
    $where .= " AND mr.maintenance_date >= ?";
    $params[] = $start_date;
    $types .= 's';
}
if ($end_date) {
    $where .= " AND mr.maintenance_date <= ?";
    $params[] = $end_date;
    $types .= 's';
}

// Query all completed maintenance records with equipment info
$sql = "SELECT mr.id AS mr_id, mr.equipment_id, mr.technician_id, mr.description AS mr_desc, mr.maintenance_date, mr.created_at AS mr_created,
        e.equipment_name, e.category, e.purchase_date, e.next_due_date, e.description AS eq_desc,
        e.serial_number, e.location, e.status AS eq_status, e.department
        FROM maintenance_record mr
        JOIN equipment e ON mr.equipment_id = e.id
        $where
        ORDER BY mr.maintenance_date ASC";

$stmt = mysqli_prepare($conn, $sql);
if ($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);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Maintenance Report - QRCareTrack</title>
    <link rel="stylesheet" href="assets/style.css">
    <link rel="stylesheet" href="assets/maintenance.css">
    <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; }
        .filter-bar input { padding:6px 10px; border-radius:4px; border:1px solid #ccc; }
        .btn { padding:6px 12px; border:none; border-radius:4px; cursor:pointer; background:#2bbbad; color:#fff; }
        .btn:hover { background:#239c92; }
        .table-container { overflow-x:auto; }
        table { border-collapse: collapse; width:100%; }
        table th, table td { border:1px solid #ccc; padding:8px; font-size:14px; text-align:left; }
        .modal { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); justify-content:center; align-items:center; }
        .modal-content { background:#fff; padding:20px; border-radius:8px; max-width:700px; width:95%; position:relative; }
        .close { position:absolute; top:10px; right:15px; cursor:pointer; font-weight:bold; }
    </style>
</head>
<body>
<?php include "includes/sidebar.php"; ?>

<div class="main">
    <h1>Maintenance Reports (Completed)</h1>

    <form method="GET" class="filter-bar">
        <label>Start Date: <input type="date" name="start_date" value="<?= htmlspecialchars($start_date) ?>"></label>
        <label>End Date: <input type="date" name="end_date" value="<?= htmlspecialchars($end_date) ?>"></label>
        <button type="submit" class="btn">Filter</button>
        <button type="button" id="download-pdf" class="btn">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</th>
                    <th>Maintenance Date</th>
                    <th>Description</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach($records as $i => $r): ?>
                <tr>
                    <td><?= $i+1 ?></td>
                    <td><?= htmlspecialchars($r['equipment_name']) ?></td>
                    <td><?= htmlspecialchars($r['category']) ?></td>
                    <td><?= htmlspecialchars($r['location']) ?></td>
                    <td><?= htmlspecialchars($r['department']) ?></td>
                    <td><?= htmlspecialchars($r['serial_number']) ?></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 ?>">Details</button>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal -->
<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 imgSrc = r.image ? `assets/images/${r.image}` : 'assets/images/placeholder.png';
        modalBody.innerHTML = `
            <div style="display:flex; gap:15px; flex-wrap:wrap;">
                <div style="flex:0 0 200px;">
                    <img src="${imgSrc}" alt="Equipment Image" style="width:200px; height:200px; object-fit:contain; border:1px solid #ccc; border-radius:6px;">
                </div>
                <div style="flex:1;">
                    <h3>${r.equipment_name} (ID: ${r.equipment_id})</h3>
                    <p><strong>Category:</strong> ${r.category}</p>
                    <p><strong>Location:</strong> ${r.location}</p>
                    <p><strong>Department:</strong> ${r.department}</p>
                    <p><strong>Serial Number:</strong> ${r.serial_number}</p>
                    <p><strong>Purchase Date:</strong> ${r.purchase_date}</p>
                    <p><strong>Next Due Date:</strong> ${r.next_due_date}</p>
                    <p><strong>Equipment Status:</strong> ${r.eq_status}</p>
                    <hr>
                    <p><strong>Maintenance Date:</strong> ${r.maintenance_date}</p>
                    <p><strong>Description:</strong> ${r.mr_desc}</p>
                    <p><strong>Created At:</strong> ${r.mr_created}</p>
                </div>
            </div>
        `;
        modal.style.display = 'flex';
    });
});

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

document.getElementById('download-pdf').addEventListener('click', ()=>{
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF();
    doc.setFontSize(16);
    doc.text("QRCareTrack Maintenance Report", 14, 20);

    const headers = [["#", "Equipment", "Category", "Location", "Dept", "Serial", "Maint Date", "Description"]];
    const data = records.map((r,i)=>[
        i+1,
        r.equipment_name,
        r.category,
        r.location,
        r.department,
        r.serial_number,
        r.maintenance_date,
        r.mr_desc
    ]);

    doc.autoTable({
        startY: 30,
        head: headers,
        body: data,
        styles: { fontSize: 10, cellPadding: 2 },
        headStyles: { fillColor: [43,187,173] },
        margin: { top: 20 }
    });

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