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

authorize();

$role = $_SESSION['role'];

/* =========================
   FILTERS
========================= */

$status_filter = $_GET['status'] ?? '';
$department_filter = $_GET['department'] ?? '';
$category_filter = $_GET['category'] ?? '';
$type_filter = $_GET['type'] ?? '';
$search = $_GET['search'] ?? '';


/* =========================
   FILTER CONDITIONS
========================= */

$conditions_corrective = [];
$conditions_preventive = [];

/* STATUS FILTER */
if (!empty($status_filter)) {

    if ($status_filter == 'Overdue') {

        $today = date('Y-m-d');

        $conditions_corrective[] = "
            mr.status != 'Completed'
            AND DATE(mr.maintenance_date) < '$today'
        ";

        $conditions_preventive[] = "
            ms.status != 'Completed'
            AND DATE(ms.scheduled_date) < '$today'
        ";

    } else {

        $status = mysqli_real_escape_string($conn, $status_filter);

        $conditions_corrective[] = "mr.status='$status'";
        $conditions_preventive[] = "ms.status='$status'";
    }
}

/* =========================
   DEPARTMENT FILTER
========================= */

if (!empty($department_filter)) {

    $department_id = intval($department_filter);

    $conditions_corrective[] =
        "e.department_id='$department_id'";

    $conditions_preventive[] =
        "e.department_id='$department_id'";
}

/* CATEGORY FILTER */
if (!empty($category_filter)) {

    $category = mysqli_real_escape_string($conn, $category_filter);

    $conditions_corrective[] = "e.category='$category'";
    $conditions_preventive[] = "e.category='$category'";
}

/* SEARCH FILTER */
if (!empty($search)) {

    $search_safe = mysqli_real_escape_string($conn, $search);

    $searchSQL = "
    (
        e.equipment_name LIKE '%$search_safe%'
        OR e.serial_number LIKE '%$search_safe%'
    )";

    $conditions_corrective[] = $searchSQL;
    $conditions_preventive[] = $searchSQL;
}

/* TYPE FILTER */
if (!empty($type_filter)) {

    if ($type_filter == 'Corrective') {
        $conditions_preventive[] = "1=0";
    }

    if ($type_filter == 'Preventive') {
        $conditions_corrective[] = "1=0";
    }
}

/* =========================
   FINAL WHERE
========================= */

$whereCorrective = !empty($conditions_corrective)
    ? "WHERE " . implode(" AND ", $conditions_corrective)
    : "";

$wherePreventive = !empty($conditions_preventive)
    ? "WHERE " . implode(" AND ", $conditions_preventive)
    : "";

/* =========================
   CORRECTIVE QUERY
========================= */

$reqQuery = "

SELECT
    mr.id,
    mr.status,
    mr.maintenance_date AS due_date,

    e.id AS equipment_id,
    e.equipment_name,
    e.serial_number,
    e.category,
    e.department_id,

    d.name AS department_name,

    u.full_name AS technician_name,

    'Corrective' AS type

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
ON mr.technician_id = u.id

$whereCorrective
";

/* =========================
   PREVENTIVE QUERY
========================= */

$schedQuery = "

SELECT
    ms.id,
    ms.status,
    ms.scheduled_date AS due_date,

    e.id AS equipment_id,
    e.equipment_name,
    e.serial_number,
    e.category,
    e.department_id,

    d.name AS department_name,

    u.full_name AS technician_name,

    'Preventive' AS type

FROM maintenance_schedule ms

JOIN equipment e
ON ms.equipment_id = e.id

LEFT JOIN departments d
ON e.department_id = d.id

LEFT JOIN users u
ON ms.assigned_to = u.id

$wherePreventive
";

/* =========================
   UNION QUERY
========================= */

$finalQuery = "
($reqQuery)

UNION

($schedQuery)

ORDER BY due_date ASC
";

$result = mysqli_query($conn, $finalQuery);

/* =========================
   DROPDOWN 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 - QRCareTrack</title>

    <link rel="stylesheet" href="assets/style.css">
    <link rel="stylesheet" href="assets/maintenance.css">

</head>

<body>

<?php include "includes/sidebar.php"; ?>

<div class="main">

<?php if(isset($_GET['update']) && $_GET['update'] == 'success'): ?>

<div class="message"
style="
background:#e8f8f5;
color:#1d8348;
padding:8px;
border-radius:5px;
margin-bottom:15px;
font-size:13px;
">
    Record updated successfully.
</div>

<?php endif; ?>

<!-- =========================
     PAGE HEADER
========================= -->

<div class="page-header"
style="
display:flex;
justify-content:space-between;
align-items:center;
flex-wrap:wrap;
border-bottom:1px solid #ccc;
padding-bottom:10px;
margin-bottom:20px;
">

<div>
    <h1>Maintenance</h1>
    <p>All corrective & preventive maintenance tasks</p>
</div>

<div style="display:flex; gap:10px; flex-wrap:wrap; align-items:center;">

    <!-- Schedule -->
    <a href="maintenance/schedule.php"
    style="
    background-color:#27ae60;
    color:#fff;
    padding:8px 16px;
    border-radius:6px;
    font-weight:bold;
    text-decoration:none;
    ">
        📅 Schedule
    </a>

    <!-- Report -->
    <a href="maintenance/report_issue.php"
    style="
    background-color:#e74c3c;
    color:#fff;
    padding:8px 16px;
    border-radius:6px;
    font-weight:bold;
    text-decoration:none;
    ">
        ⚠️ Create Report
    </a>

    <!-- HOD ONLY -->
    <?php if($role == 'hod'): ?>

    <a href="maintenance/hod_review.php"
    style="
    background-color:#2980b9;
    color:#fff;
    padding:8px 16px;
    border-radius:6px;
    font-weight:bold;
    text-decoration:none;
    ">
        📋 Review Reports
    </a>

    <?php endif; ?>

</div>

</div>

<!-- =========================
     FILTER FORM
========================= -->

<form method="GET" class="filter-bar"
style="
display:flex;
gap:10px;
flex-wrap:wrap;
margin-bottom:20px;
">

<!-- STATUS -->
<select name="status">

    <option value="">All Status</option>

    <option value="In Progress"
    <?=($status_filter=='In Progress')?'selected':''?>>
        In Progress
    </option>

    <option value="HOD Review"
    <?=($status_filter=='HOD Review')?'selected':''?>>
        HOD Review
    </option>

    <option value="HOD Rejected"
    <?=($status_filter=='HOD Rejected')?'selected':''?>>
        HOD Rejected
    </option>

    <option value="Completed"
    <?=($status_filter=='Completed')?'selected':''?>>
        Completed
    </option>

    <option value="Overdue"
    <?=($status_filter=='Overdue')?'selected':''?>>
        Overdue
    </option>

</select>

<!-- DEPARTMENT -->
<select name="department">

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

<!-- CATEGORY -->
<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>

<!-- TYPE -->
<select name="type">

    <option value="">All Type</option>

    <option value="Corrective"
    <?=($type_filter=='Corrective')?'selected':''?>>
        Corrective
    </option>

    <option value="Preventive"
    <?=($type_filter=='Preventive')?'selected':''?>>
        Preventive
    </option>

</select>

<!-- SEARCH -->
<input
type="text"
name="search"
placeholder="Search equipment or serial number..."
value="<?= htmlspecialchars($search) ?>"
>

<button class="btn small">
    Filter
</button>

<a href="maintenance.php"
class="btn small"
style="
background:#777;
color:#fff;
text-decoration:none;
padding:8px 14px;
border-radius:5px;
">
    Reset
</a>

</form>

<!-- =========================
     TABLE
========================= -->

<div class="table-container">

<table>

<thead>

<tr>
    <th>Equipment</th>
    <th>Serial Number</th>
    <th>Department</th>
    <th>Category</th>
    <th>Type</th>
    <th>Status</th>
    <th>Due</th>
    <th>Assigned</th>
    <th>Action</th>
</tr>

</thead>

<tbody>

<?php if(mysqli_num_rows($result) > 0): ?>

<?php while($row = mysqli_fetch_assoc($result)): ?>

<tr>

<!-- EQUIPMENT -->
<td>

    <b>
        <?= htmlspecialchars($row['equipment_name']) ?>
    </b>

    <br>

    <small>
        EQP-<?= str_pad($row['equipment_id'],4,"0",STR_PAD_LEFT) ?>
    </small>

</td>

<!-- SERIAL -->
<td>
    <?= htmlspecialchars($row['serial_number'] ?? '-') ?>
</td>

<!-- DEPARTMENT -->
<td>
    <?= htmlspecialchars($row['department_name'] ?? '-') ?>
</td>

<!-- CATEGORY -->
<td>
    <?= htmlspecialchars($row['category'] ?? '-') ?>
</td>

<!-- TYPE -->
<td>

<span class="badge <?= strtolower($row['type']) ?>">

    <?= $row['type'] ?>

</span>

</td>

<!-- STATUS -->
<td>

<span class="badge <?= strtolower(str_replace(' ','-',$row['status'])) ?>">

    <?= $row['status'] ?>

</span>

</td>

<!-- DUE -->
<td>

<?php
$isOverdue =
    !empty($row['due_date']) &&
    strtotime($row['due_date']) < strtotime(date('Y-m-d')) &&
    $row['status'] != 'Completed';
?>

<?= $row['due_date']
    ? date("d/m/Y", strtotime($row['due_date']))
    : '-' ?>

<?php if($isOverdue): ?>

<br>

<span style="
    color:#dc2626;
    font-weight:bold;
    font-size:12px;
">
    (Overdue)
</span>

<?php endif; ?>

</td>

<!-- ASSIGNED -->
<td>

<?= htmlspecialchars($row['technician_name'] ?? 'Unassigned') ?>

</td>

<!-- ACTION -->
<td>

<?php if($row['type'] == 'Corrective'): ?>

<a href="maintenance/record_details.php?id=<?= $row['id'] ?>"
class="btn small">
    Open
</a>

<?php else: ?>

<a href="maintenance/update_schedule.php?id=<?= $row['id'] ?>&status=Completed"
class="btn small primary">
    Complete
</a>

<?php endif; ?>

</td>

</tr>

<?php endwhile; ?>

<?php else: ?>

<tr>

<td colspan="9"
style="text-align:center; padding:20px;">

    No maintenance records found.

</td>

</tr>

<?php endif; ?>

</tbody>

</table>

</div>

</div>

</body>
</html>