<?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'");

/* ===============================
   SEARCH & FILTER
=================================*/
$where = "WHERE 1=1";
$params = [];
$types = "";

/* ✅ DEFAULT: ACTIVE ONLY */
if (empty($_GET['status'])) {
    $where .= " AND e.status = 'Active'";
}

/* SEARCH */
if (!empty($_GET['q'])) {
    $where .= " AND (e.equipment_name LIKE ? OR e.serial_number LIKE ?)";
    $search = "%" . $_GET['q'] . "%";
    $params[] = $search;
    $params[] = $search;
    $types .= "ss";
}

/* STATUS FILTER (OVERRIDE DEFAULT) */
if (!empty($_GET['status'])) {
    $where .= " AND e.status = ?";
    $params[] = $_GET['status'];
    $types .= "s";
}

/* DEPARTMENT FILTER */
if (!empty($_GET['department_id'])) {
    $where .= " AND e.department_id = ?";
    $params[] = $_GET['department_id'];
    $types .= "i";
}
/* ===============================
   MAIN QUERY (WITH LAST MAINTENANCE)
=================================*/
$sql = "
SELECT e.*, 
       MAX(m.maintenance_date) AS last_maintenance_date
FROM equipment e
LEFT JOIN maintenance_record m 
    ON e.id = m.equipment_id 
    AND m.status = 'Completed'
$where
GROUP BY e.id
ORDER BY e.created_at DESC
";

$stmt = mysqli_prepare($conn, $sql);

if (!empty($params)) {
    mysqli_stmt_bind_param($stmt, $types, ...$params);
}

mysqli_stmt_execute($stmt);
$items = mysqli_stmt_get_result($stmt);
?>

<!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 TAG */
        .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;
        }
    </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"): ?>
            <button class="add-btn" onclick="openEquipmentModal()">
                <i class="fas fa-plus"></i> Add Item
            </button>
        <?php endif; ?>
    </div>

    <!-- SUMMARY -->
    <div class="cards">
        <div class="card">
            <h3><?= $totalItems ?></h3>
            <p>Total Equipment</p>
        </div>

        <div class="card">
            <h3><?= $active ?></h3>
            <p>Active</p>
        </div>

        <div class="card">
            <h3><?= $underMaintenance ?></h3>
            <p>Under Maintenance</p>
        </div>

        <div class="card">
            <h3><?= $inactive ?></h3>
            <p>Inactive</p>
        </div>
    </div>

    <div class="box">

        <!-- SEARCH -->
        <form method="GET" class="search-form">

            <input 
                type="text" 
                name="q"
                placeholder="Search by name or serial number"
                value="<?= isset($_GET['q']) ? htmlspecialchars($_GET['q']) : '' ?>"
            >

            <select name="status">
                <option value="">All Status</option>
                <option value="Active" <?= (isset($_GET['status']) && $_GET['status'] == "Active") ? 'selected' : '' ?>>Active</option>
                <option value="Under Maintenance" <?= (isset($_GET['status']) && $_GET['status'] == "Under Maintenance") ? 'selected' : '' ?>>Under Maintenance</option>
                <option value="Inactive" <?= (isset($_GET['status']) && $_GET['status'] == "Inactive") ? 'selected' : '' ?>>Inactive</option>
            </select>

            <select name="department_id">
                <option value="">All Department</option>

                <?php
                $deptQuery = mysqli_query($conn, "SELECT id, name FROM departments ORDER BY name ASC");

                while ($dept = mysqli_fetch_assoc($deptQuery)) {
                    $selected = (
                        isset($_GET['department_id']) &&
                        $_GET['department_id'] == $dept['id']
                    ) ? 'selected' : '';

                    echo "<option value='{$dept['id']}' $selected>"
                        . htmlspecialchars($dept['name']) .
                        "</option>";
                }
                ?>
            </select>

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

        </form>

        <!-- TABLE -->
        <table>
            <tr>
                <th>QR</th>
                <th>Equipment Name</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>

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

                        <!-- EQUIPMENT NAME + NEW TAG -->
                        <td>
                            <?= htmlspecialchars($row['equipment_name']) ?>

                            <?php
                            $created = strtotime($row['created_at']);
                            $today = strtotime(date("Y-m-d"));
                            $daysDiff = ($today - $created) / (60 * 60 * 24);

                            if ($daysDiff <= 7) {
                                echo "<span class='new-badge'>NEW</span>";
                            }
                            ?>
                        </td>

                        <td><?= htmlspecialchars($row['category'] ?? '-') ?></td>
                        <td><?= htmlspecialchars($row['location']) ?></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";
    }
    ?>

    <span class="status-badge <?= $statusClass ?>">
        <?= htmlspecialchars($status) ?>
    </span>
</td>

                        <!-- LAST MAINTENANCE -->
                        <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>

                        <!-- NEXT DUE -->
                        <td>
                            <?php
                            if (!empty($row['next_due_date'])) {
                                $due = strtotime($row['next_due_date']);
                                $today = strtotime(date("Y-m-d"));
                                $diff = ($due - $today) / (60 * 60 * 24);

                                $class = "";

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

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

                        <!-- ACTION -->
                        <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="8" style="text-align:center;">
                        No items found
                    </td>
                </tr>
            <?php endif; ?>
        </table>

    </div>
</div>
<div id="addEquipmentModal" class="modal">

    <div class="modal-box" style="width: 800px;">

        <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">

            <div class="form-grid">

                <!-- LEFT -->
                <div>

                    <div class="form-group">
                        <label>Equipment Name *</label>
                        <input type="text" name="equipment_name" required>
                    </div>

                    <div class="form-group">
                        <label>Serial Number *</label>
                        <input type="text" name="serial_number" required>
                    </div>

                    <div class="form-group">
                        <label>Category *</label>
                        <select name="category" required>
                            <option value="">Select Category</option>
                            <option value="Ventilator">Ventilator</option>
                            <option value="ECG Machine">ECG Machine</option>
                            <option value="Infusion Pump">Infusion Pump</option>
                            <option value="Defibrillator">Defibrillator</option>
                            <option value="Patient Monitor">Patient Monitor</option>
                            <option value="Computers">Computers</option>
                            <option value="Servers">Servers</option>
                            <option value="Networking Equipment">Networking Equipment</option>
                            <option value="MRI Scanner">MRI Scanner</option>
                            <option value="CT Scanner">CT Scanner</option>
                            <option value="X-Ray Machine">X-Ray Machine</option>
                            <option value="Other">Other</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Location *</label>
                        <input type="text" name="location" required>
                    </div>

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

                </div>

                <!-- RIGHT -->
                <div>

                    <div class="form-group">
                        <label>Department *</label>
                        <select name="department_id" required>
                            <option value="">Select Department</option>

                            <?php
                            $deptQuery = mysqli_query($conn, "SELECT id, name FROM departments ORDER BY name ASC");
                            while ($dept = mysqli_fetch_assoc($deptQuery)) {
                                echo "<option value='{$dept['id']}'>"
                                    . htmlspecialchars($dept['name']) .
                                "</option>";
                            }
                            ?>
                        </select>
                    </div>

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

                    <div class="form-group">
                        <label>Next Service</label>
                        <input type="date" name="next_due_date">
                    </div>

                    <div class="form-group">
                        <label>Description</label>
                        <textarea name="description" rows="3"></textarea>
                    </div>

                    <div class="form-group">
                        <label>Upload Image</label>
                        <input type="file" name="equipment_image">
                        <small>Optional. Max 2MB</small>
                    </div>

                </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";
}
</script>
</body>
</html>
```
