<?php
session_start();
require_once __DIR__ . "/../config/db.php";

/* ================================
   SECURITY
================================ */
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== "hod") {
    header("Location: ../login.php");
    exit();
}

$hod_id = $_SESSION['user_id'];
$department_id = $_SESSION['department_id'];

if (!$department_id) {
    die("HOD has no department assigned. Please contact admin.");
}

/* ================================
   FILTER
================================ */
$status_filter = $_GET['filter'] ?? 'pending';

/* ================================
   FETCH MAINTENANCE REQUESTS
================================ */

$sql = "
SELECT 
    m.*,
    u.full_name,
    e.equipment_name,
    e.department_id

FROM maintenance_request m

JOIN users u 
ON m.requested_by = u.id

JOIN equipment e 
ON m.equipment_id = e.id

WHERE e.department_id = ?
";

/* FILTER */
if($status_filter == 'pending'){
    $sql .= " AND m.status = 'Reported'";
}

$sql .= " ORDER BY m.created_at DESC";

$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "i", $department_id);
mysqli_stmt_execute($stmt);

$requests = mysqli_stmt_get_result($stmt);

/* ================================
   SIMPLE DUPLICATE DETECTION
================================ */

$final_requests = [];
$seen = [];

while($r = mysqli_fetch_assoc($requests)) {

    $key = $r['equipment_id'];

    /* CHECK DUPLICATES IN LAST 3 DAYS */
    $recent_sql = "
    SELECT *
    FROM maintenance_request
    WHERE equipment_id = ?
    AND created_at >= DATE_SUB(NOW(), INTERVAL 3 DAY)
    ORDER BY created_at DESC
    ";

    $recent_stmt = mysqli_prepare($conn, $recent_sql);

    mysqli_stmt_bind_param(
        $recent_stmt,
        "i",
        $r['equipment_id']
    );

    mysqli_stmt_execute($recent_stmt);

    $recent_res = mysqli_stmt_get_result($recent_stmt);

    $is_duplicate = false;

    while($rec = mysqli_fetch_assoc($recent_res)) {

        if($rec['id'] == $r['id']) continue;

        similar_text(
            strtolower($r['issue_description']),
            strtolower($rec['issue_description']),
            $perc
        );

        if($perc > 50) {
            $is_duplicate = true;
            break;
        }
    }

    /* ONLY KEEP LATEST PER EQUIPMENT */
    if(isset($seen[$key])) continue;

    $seen[$key] = true;

    $r['is_duplicate'] = $is_duplicate;

    $final_requests[] = $r;
}
?>

<!DOCTYPE html>
<html>

<head>

<title>HOD Review</title>

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

<style>

body {
    background-color: #f4f6f8;
}

.main {
    margin-left: 260px;
    padding: 20px;
    max-width: 1200px;
}

h2 {
    margin-bottom: 20px;
}

.top-bar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    flex-wrap:wrap;
    margin-bottom:20px;
}

.filter-tabs{
    display:flex;
    gap:10px;
    margin-bottom:20px;
}

.filter-tabs a{
    padding:8px 16px;
    border-radius:6px;
    text-decoration:none;
    font-weight:600;
    transition:0.2s;
}

.active-tab{
    background:#007bff;
    color:#fff;
}

.inactive-tab{
    background:#e9ecef;
    color:#333;
}

table {
    width: 100%;
    border-collapse: collapse;
    background: #fff;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

th, td {
    padding: 12px 15px;
    border-bottom: 1px solid #eee;
    text-align: left;
    vertical-align: top;
    font-size: 14px;
}

th {
    background: #f1f3f5;
    font-weight: 600;
}

tr:hover {
    background: #f9f9f9;
}

.badge {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 6px;
    color: #fff;
    font-size: 0.85em;
    font-weight:600;
}

.pending-status{
    background:#f39c12;
}

.approved-status{
    background:#27ae60;
}

.rejected-status{
    background:#e74c3c;
}

.duplicate {
    background-color: #dc3545 !important;
}

.duplicate-note {
    font-size: 0.75em;
    color: #555;
    margin-top: 5px;
}

.issue {
    cursor: pointer;
    color: #333;
    max-width: 300px;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
}

.issue.full {
    white-space: normal;
}

.actions a {
    display: inline-block;
    padding: 5px 10px;
    border-radius: 6px;
    text-decoration: none;
    font-size: 0.8em;
    color: #fff;
    margin-right: 5px;
}

.approve {
    background-color: #28a745;
}

.reject {
    background-color: #dc3545;
}

.view-details {
    background-color: #17a2b8;
}

.btn-back{
    display:inline-block;
    margin-bottom:15px;
    text-decoration:none;
    color:#007bff;
    font-weight:600;
}

.no-data{
    text-align:center;
    padding:30px;
    color:#777;
}

</style>

</head>

<body>

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

<div class="main">

<div class="top-bar">

<div>
    <h2>Department Maintenance Requests</h2>
    <a href="javascript:history.back()" class="btn-back">
        ← Back
    </a>
</div>

</div>

<!-- =========================
     FILTER TABS
========================= -->

<div class="filter-tabs">

    <!-- PENDING -->
    <a href="?filter=pending"
    class="<?= $status_filter=='pending'
    ? 'active-tab'
    : 'inactive-tab' ?>">

        Pending Review

    </a>

    <!-- ALL -->
    <a href="?filter=all"
    class="<?= $status_filter=='all'
    ? 'active-tab'
    : 'inactive-tab' ?>">

        All Requests

    </a>

</div>

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

<table>

<thead>

<tr>
    <th>Equipment</th>
    <th>Requested By</th>
    <th>Issue Description</th>
    <th>Status</th>
    <th>Duplicate</th>
    <th>Date</th>
    <th>Actions</th>
</tr>

</thead>

<tbody>

<?php if(count($final_requests) > 0): ?>

<?php foreach($final_requests as $r): ?>

<tr>

<!-- EQUIPMENT -->
<td>

    <strong>
        <?= htmlspecialchars($r['equipment_name']) ?>
    </strong>

</td>

<!-- REQUESTED BY -->
<td>

    <?= htmlspecialchars($r['full_name']) ?>

</td>

<!-- ISSUE -->
<td>

    <div class="issue"
    onclick="toggleExpand(this)">

        <?= htmlspecialchars($r['issue_description']) ?>

    </div>

</td>

<!-- STATUS -->
<td>

<?php

$statusClass = '';

if($r['status'] == 'Reported'){
    $statusClass = 'pending-status';
}
elseif($r['status'] == 'Approved'){
    $statusClass = 'approved-status';
}
elseif($r['status'] == 'Rejected'){
    $statusClass = 'rejected-status';
}

?>

<span class="badge <?= $statusClass ?>">

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

</span>

</td>

<!-- DUPLICATE -->
<td>

<?php if($r['is_duplicate']): ?>

<div class="duplicate-note">
    Duplicate in last 3 days
</div>

<?php else: ?>

-

<?php endif; ?>

</td>

<!-- DATE -->
<td>

<?= date("d M Y", strtotime($r['created_at'])) ?>

</td>

<!-- ACTION -->
<td class="actions">

<?php if($r['status'] == "Reported"): ?>

<a class="view-details"
href="maintenance_details.php?id=<?= $r['id'] ?>">

    View

</a>

<?php else: ?>

<span style="color:#777; font-size:0.85em;">

    No actions

</span>

<?php endif; ?>

</td>

</tr>

<?php endforeach; ?>

<?php else: ?>

<tr>

<td colspan="7" class="no-data">

    No maintenance requests found.

</td>

</tr>

<?php endif; ?>

</tbody>

</table>

</div>

<script>

function toggleExpand(el){

    el.classList.toggle("full");

}

</script>

</body>
</html>