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

authorize();

/* ===============================
   COUNTS
=================================*/
function getCount($conn, $query) {
    $result = mysqli_query($conn, $query);
    if ($result) {
        return mysqli_fetch_assoc($result)['total'];
    }
    return 0;
}

$totalItems = getCount($conn, "SELECT COUNT(*) as total FROM equipment");
$active = getCount($conn, "SELECT COUNT(*) as total FROM equipment WHERE status='Active'");
$underMaintenance = getCount($conn, "SELECT COUNT(*) as total FROM equipment WHERE status='Under Maintenance'");
$inactive = getCount($conn, "SELECT COUNT(*) as total FROM equipment WHERE status='Inactive'");
$overdue = getCount($conn, "SELECT COUNT(*) as total FROM equipment WHERE status='Overdue'");

/* ===============================
   FILTERS & CONDITIONS
=================================*/
$status_filter = isset($_GET['status']) ? $_GET['status'] : (isset($_GET['q']) || isset($_GET['department_id']) || isset($_GET['category']) ? '' : 'Active');
$department_filter = $_GET['department_id'] ?? '';
$category_filter = $_GET['category'] ?? '';
$search = $_GET['q'] ?? '';

$conditions = [];

/* STATUS FILTER */
if (!empty($status_filter)) {
    $status_safe = mysqli_real_escape_string($conn, $status_filter);
    $conditions[] = "e.status = '$status_safe'";
}

/* DEPARTMENT FILTER */
if (!empty($department_filter)) {
    $dept_id_safe = intval($department_filter);
    $conditions[] = "e.department_id = '$dept_id_safe'";
}

/* CATEGORY FILTER */
if (!empty($category_filter)) {
    $category_safe = mysqli_real_escape_string($conn, $category_filter);
    $conditions[] = "e.category = '$category_safe'";
}

/* SEARCH FILTER */
if (!empty($search)) {
    $search_safe = mysqli_real_escape_string($conn, $search);
    $conditions[] = "(e.equipment_name LIKE '%$search_safe%' OR e.serial_number LIKE '%$search_safe%')";
}

/* CONSTRUCT WHERE CLAUSE */
$whereClause = !empty($conditions) ? "WHERE " . implode(" AND ", $conditions) : "WHERE 1=1";

/* ===============================
   MAIN QUERY (WITH LAST MAINTENANCE)
=================================*/
$sql = "
SELECT
    e.*,
    l.location_name,
    MAX(m.maintenance_date) AS last_maintenance_date
FROM equipment e
LEFT JOIN locations l
    ON e.location_id = l.id
LEFT JOIN maintenance_record m
    ON e.id = m.equipment_id
    AND m.status = 'Completed'
$whereClause
GROUP BY e.id
ORDER BY e.created_at DESC
";

$items = mysqli_query($conn, $sql);

/* ===============================
   DROPDOWN OPTIONS 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 AND category != '' ORDER BY category ASC");
?>

<!DOCTYPE html>
<html>
<head>
    <title>Items - QRCareTrack</title>
    <link rel="stylesheet" href="assets/style.css">
    <link rel="stylesheet" href="assets/items.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">

    <style>
        .qr-small { width: 40px; height: 40px; object-fit: contain; border: 1px solid #ccc; border-radius: 4px; }
        .edit-btn { background: #facc15; color: #000; }
        .edit-btn:hover { background: #eab308; }
        
        .due-overdue { background: #fee2e2; color: #b91c1c; padding: 4px 8px; border-radius: 6px; font-weight: bold; }
        .due-soon { background: #fef9c3; color: #92400e; padding: 4px 8px; border-radius: 6px; font-weight: bold; }
        .last-maintenance { background: #e0f2fe; color: #075985; padding: 4px 8px; border-radius: 6px; font-weight: 500; }
        .new-badge { display: inline-block; margin-left: 8px; padding: 3px 8px; background: #dcfce7; color: #166534; font-size: 12px; font-weight: 700; border-radius: 999px; vertical-align: middle; }
        
        .status-overdue { background: #fca5a5 !important; color: #991b1b !important; font-weight: bold; }
        .cards-5 { display: grid; grid-template-columns: repeat(5, 1fr); gap: 15px; margin-bottom: 20px; }
        .input-with-clear {
    position: relative;
    display: flex;
    align-items: center;
}

.input-with-clear input {
    width: 100%;
    padding-right: 30px; /* space for the ✕ */
}

.clear-btn {
    position: absolute;
    right: 10px;
    font-size: 18px;
    color: #9ca3af;
    cursor: pointer;
    line-height: 1;
    display: none; /* hidden until user types */
    user-select: none;
}

.clear-btn:hover {
    color: #ef4444;
}
    </style>
</head>

<body>

<?php include __DIR__ . '/includes/sidebar.php'; ?>

<div class="main">

    <div class="page-header">
        <div>
            <h1>Items</h1>
            <p>Manage and monitor all registered equipment.</p>
        </div>

        <?php if ($_SESSION['role'] == "admin"): ?>
            <div style="display:flex; gap:10px; align-items:center;">
                
                <a href="../equipment/Category.php" class="add-btn" style="text-decoration:none;">
                    <i class="fas fa-tags"></i> Manage Category
                </a>
        
                <button class="add-btn" onclick="openEquipmentModal()">
                    <i class="fas fa-plus"></i> Add Item
                </button>
        
            </div>
        <?php endif; ?>
    </div>

    <div class="cards cards-5">
        <div class="card">
            <h3><?= $totalItems ?></h3>
            <p>Total Equipment</p>
        </div>
        <div class="card" style="border-left: 5px solid #2ecc71;">
            <h3><?= $active ?></h3>
            <p style="color:#2ecc71; font-weight:bold;">Active</p>
        </div>
        <div class="card" style="border-left: 5px solid #ef4444;">
            <h3><?= $overdue ?></h3>
            <p style="color:#ef4444; font-weight:bold;">Overdue</p>
        </div>
        <div class="card" style="border-left: 5px solid #f39c12;">
            <h3><?= $underMaintenance ?></h3>
            <p style="color:#f39c12; font-weight:bold;">Under Maintenance</p>
        </div>
        <div class="card" style="border-left: 5px solid #7f8c8d;">
            <h3><?= $inactive ?></h3>
            <p style="color:#7f8c8d; font-weight:bold;">Inactive</p>
        </div>
    </div>

    <div class="box">

        <form method="GET" class="search-form">
            
            <select name="status">
                <option value="" <?= ($status_filter === "") ? 'selected' : '' ?>>All Status</option>
                <option value="Active" <?= ($status_filter === "Active") ? 'selected' : '' ?>>Active</option>
                <option value="Overdue" <?= ($status_filter === "Overdue") ? 'selected' : '' ?>>Overdue</option>
                <option value="Under Maintenance" <?= ($status_filter === "Under Maintenance") ? 'selected' : '' ?>>Under Maintenance</option>
                <option value="Inactive" <?= ($status_filter === "Inactive") ? 'selected' : '' ?>>Inactive</option>
            </select>

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

            <select name="category">
                <option value="">All Category</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>

            <input type="text" name="q" placeholder="Search by name or serial number..." value="<?= htmlspecialchars($search) ?>">

            <button type="submit" class="btn primary">Filter</button>
            <a href="items.php" class="btn cancel">Reset</a>
        </form>

        <table>
            <tr>
                <th>QR</th>
                <th>Equipment Name</th>
                <th>Serial Number</th>
                <th>Category</th>
                <th>Location</th>
                <th>Status</th>
                <th>Last Maintenance</th>
                <th>Next Service</th>
                <th>Action</th>
            </tr>

            <?php if (mysqli_num_rows($items) > 0): ?>
                <?php while ($row = mysqli_fetch_assoc($items)): ?>
                    <tr>
                        <td>
                            <?php if (!empty($row['qr_code'])): ?>
                                <img src="assets/qr_codes/<?= htmlspecialchars($row['qr_code']) ?>" class="qr-small">
                            <?php else: ?> - <?php endif; ?>
                        </td>

                        <td>
                            <b><?= htmlspecialchars($row['equipment_name']) ?></b>
                            <?php
                            $created = strtotime($row['created_at']);
                            $daysDiff = (time() - $created) / (60 * 60 * 24);
                            if ($daysDiff <= 7) { echo "<span class='new-badge'>NEW</span>"; }
                            ?>
                        </td>

                        <td><?= htmlspecialchars($row['serial_number'] ?? '-') ?></td>
                        <td><?= htmlspecialchars($row['category'] ?? '-') ?></td>
                        <td><?= htmlspecialchars($row['location_name'] ?? '-') ?></td>
                        
                        <td>
                            <?php
                            $status = $row['status'] ?? '';
                            $statusClass = '';
                            if ($status == "Active") $statusClass = "status-active";
                            elseif ($status == "Under Maintenance") $statusClass = "status-under-maintenance";
                            elseif ($status == "Inactive") $statusClass = "status-inactive";
                            elseif ($status == "Overdue") $statusClass = "status-overdue";
                            ?>
                            <span class="status-badge <?= $statusClass ?>">
                                <?= htmlspecialchars($status) ?>
                            </span>
                        </td>

                        <td>
                            <?php
                            if (!empty($row['last_maintenance_date'])) {
                                echo "<span class='last-maintenance'>" . date("d M Y", strtotime($row['last_maintenance_date'])) . "</span>";
                            } else { echo "-"; }
                            ?>
                        </td>

                        <td>
                            <?php
                            if (!empty($row['next_due_date'])) {
                                $due = strtotime($row['next_due_date']);
                                $diff = ($due - time()) / (60 * 60 * 24);
                                $class = "";

                                if ($diff < 0 || $status == "Overdue") { $class = "due-overdue"; } 
                                elseif ($diff <= 7) { $class = "due-soon"; }

                                echo "<span class='$class'>" . date("d M Y, h:i A", $due) . "</span>";
                            } else { echo "-"; }
                            ?>
                        </td>

                        <td>
                            <a href="equipment/equipment_details.php?id=<?= $row['id'] ?>" class="action-btn view-btn"><i class="fas fa-eye"></i> View</a>
                            <?php if ($_SESSION['role'] == "admin"): ?>
                                <a href="equipment/edit_equipment.php?id=<?= $row['id'] ?>" class="action-btn edit-btn"><i class="fas fa-pen"></i> Edit</a>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="9" style="text-align:center; padding:20px;">No equipment records found.</td></tr>
            <?php endif; ?>
        </table>
    </div>
</div>

<div id="addEquipmentModal" class="modal">
    <div class="modal-box" style="width: 850px;">
        <div class="modal-header">
            <h3>Add New Equipment</h3>
            <span class="close" onclick="closeEquipmentModal()">&times;</span>
        </div>

        <form method="POST" action="equipment/add_equipment_process.php" enctype="multipart/form-data">

            <form method="POST" action="equipment/add_equipment_process.php" enctype="multipart/form-data">

    <div class="modal-form-grid">

        <div class="form-group">
            <label>Equipment Name *</label>
            <div class="input-with-clear">
                <input type="text" name="equipment_name" id="equipmentNameInput" required placeholder="e.g. Blood Pressure Monitor">
                <span class="clear-btn" onclick="clearInput('equipmentNameInput')">&times;</span>
            </div>
        </div>

        <div class="form-group">
            <label>Serial Number *</label>
            <div class="input-with-clear">
                <input type="text" name="serial_number" id="serialNumberInput" required placeholder="e.g. SN-2024-00123">
                <span class="clear-btn" onclick="clearInput('serialNumberInput')">&times;</span>
            </div>
        </div>

        <div class="form-group">
            <label>Department *</label>
            <select name="department_id" id="departmentSelect" required>
                <option value="">Select Department</option>
                <?php
                $deptQ = mysqli_query($conn, "SELECT id, name FROM departments ORDER BY name ASC");
                while ($dept = mysqli_fetch_assoc($deptQ)) {
                    echo "<option value='{$dept['id']}'>".htmlspecialchars($dept['name'])."</option>";
                }
                ?>
            </select>
        </div>

        <div class="form-group">
            <label>Status *</label>
            <select name="status" required>
                <option value="Active">Active</option>
                <option value="Under Maintenance">Under Maintenance</option>
                <option value="Inactive">Inactive</option>
            </select>
        </div>

        <div class="form-group">
            <label>Category * <small class="field-hint">(Please choose the department first)</small></label>
            <select name="category" id="categorySelect" required>
                <option value="">Select Category</option>
            </select>
        </div>

        <div class="form-group">
            <label>Location *</label>
            <select name="location_id" required>
                <option value="">Select Location</option>
                <?php
                $locQ = mysqli_query($conn, "SELECT * FROM locations ORDER BY location_name ASC");
                while ($loc = mysqli_fetch_assoc($locQ)) {
                    echo "<option value='{$loc['id']}'>".htmlspecialchars($loc['location_name'])."</option>";
                }
                ?>
            </select>
        </div>

        <div class="form-group">
            <label>Purchase Date</label>
            <input type="date" name="purchase_date" id="purchaseDate" max="">
        </div>

        <div class="form-group">
            <label>Next Maintenance</label>
            <input type="datetime-local" name="next_due_date" id="nextDueDate" disabled
                style="opacity:0.4; cursor:not-allowed; background:#f3f4f6;">
        </div>

        <div class="form-group full-width">
            <label>Description</label>
            <textarea name="description" placeholder="Optional notes about this equipment..."></textarea>
        </div>

        <div class="form-group full-width">
            <label>Image</label>
            <input type="file" name="equipment_image">
        </div>

    </div>

    <div class="modal-actions">
        <button type="button" class="btn cancel" onclick="closeEquipmentModal()">Cancel</button>
        <button type="submit" class="btn primary">Add Equipment</button>
    </div>

</form>

    </div>
</div>

<script>
function openEquipmentModal(){
    document.getElementById("addEquipmentModal").style.display = "flex";
}

function closeEquipmentModal(){
    document.getElementById("addEquipmentModal").style.display = "none";
}

/* =========================
   CATEGORY FILTER AJAX
========================= */
document.getElementById("departmentSelect").addEventListener("change", function () {

    let deptId = this.value;
    let categorySelect = document.getElementById("categorySelect");

    categorySelect.innerHTML = "<option>Loading...</option>";

    fetch("equipment/get_categories.php?department_id=" + deptId)
        .then(res => res.json())
        .then(data => {

            categorySelect.innerHTML = "<option value=''>Select Category</option>";

            data.forEach(cat => {
                let option = document.createElement("option");
                option.value = cat.name;
                option.textContent = cat.name;
                categorySelect.appendChild(option);
            });

        })
        .catch(err => {
            categorySelect.innerHTML = "<option>Error loading categories</option>";
        });

});

/* =========================
   PURCHASE DATE: max = today
========================= */
const today = new Date().toISOString().split("T")[0];
document.getElementById("purchaseDate").setAttribute("max", today);

/* =========================
   NEXT MAINTENANCE: unlock after purchase date picked
========================= */
document.getElementById("purchaseDate").addEventListener("change", function () {
    const nextDue = document.getElementById("nextDueDate");
    const val = this.value;

    if (val) {
        // min = day after purchase date, at 00:00
        const afterPurchase = new Date(val);
        afterPurchase.setDate(afterPurchase.getDate() + 1);

        // Format to datetime-local min: "YYYY-MM-DDTHH:MM"
        const minVal = afterPurchase.toISOString().slice(0, 16);

        nextDue.setAttribute("min", minVal);
        nextDue.disabled = false;
        nextDue.style.opacity = "1";
        nextDue.style.cursor = "pointer";
        nextDue.style.background = "";

        // Reset value if it's now before the new min
        if (nextDue.value && nextDue.value < minVal) {
            nextDue.value = "";
        }
    } else {
        // No purchase date → lock it again
        nextDue.disabled = true;
        nextDue.style.opacity = "0.4";
        nextDue.style.cursor = "not-allowed";
        nextDue.style.background = "#f3f4f6";
        nextDue.value = "";
    }
});

/* =========================
   CLEAR BUTTON LOGIC
========================= */
function clearInput(inputId) {
    const input = document.getElementById(inputId);
    input.value = "";
    input.focus();
    // Hide the ✕ button after clearing
    input.nextElementSibling.style.display = "none";
}

// Show ✕ only when input has text
["equipmentNameInput", "serialNumberInput"].forEach(id => {
    const input = document.getElementById(id);
    input.addEventListener("input", function () {
        this.nextElementSibling.style.display = this.value ? "block" : "none";
    });
});
</script>
</body>
</html>