<?php

error_reporting(E_ALL);
ini_set('display_errors',1);

require '../config.php';
session_start();
session_write_close();

if(!isset($_SESSION['user_id'])){
    header("Location: ../login.php");
    exit;
}

$search = trim($_GET['search'] ?? '');

$sql = "
SELECT

dc.*,
e.name employee_name,
u.username issued_by_name

FROM disciplinary_cases dc

LEFT JOIN employees e
ON e.id = dc.employee_id

LEFT JOIN users u
ON u.id = dc.issued_by

WHERE 1
";

if($search != ''){

    $search = $conn->real_escape_string($search);

    $sql .= "
    AND (
        e.name LIKE '%$search%'
        OR dc.subject LIKE '%$search%'
        OR dc.case_type LIKE '%$search%'
    )
    ";
}

$sql .= "
ORDER BY dc.id DESC
";

$res = $conn->query($sql);

?>

<!DOCTYPE html>
<html>
<head>

<title>Disciplinary Cases</title>

<script src="https://cdn.tailwindcss.com"></script>

</head>

<body class="flex bg-gray-100 min-h-screen">

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

<div class="flex-1 p-8" id="main-content">

<div class="flex justify-between items-center mb-6">

<h1 class="text-3xl font-bold">

Disciplinary Cases

</h1>

<a
href="issue_query.php"
class="bg-red-600 text-white px-5 py-3 rounded-lg">

+ New Case

</a>

</div>

<form method="GET" class="mb-6">

<input
type="text"
name="search"
value="<?= htmlspecialchars($search) ?>"
placeholder="Search..."
class="border p-3 rounded-lg w-80">

<button
class="bg-blue-600 text-white px-5 py-3 rounded-lg">

Search

</button>

</form>

<div class="bg-white rounded-xl shadow overflow-hidden">

<table class="w-full">

<thead class="bg-gray-100">

<tr>

<th class="p-4 text-left">Employee</th>
<th class="p-4 text-left">Type</th>
<th class="p-4 text-left">Subject</th>
<th class="p-4 text-left">Issue Date</th>
<th class="p-4 text-left">Status</th>
<th class="p-4 text-left">Action</th>

</tr>

</thead>

<tbody>

<?php while($row=$res->fetch_assoc()): ?>

<tr class="border-b hover:bg-gray-50">

<td class="p-4">

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

</td>

<td class="p-4">

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

</td>

<td class="p-4">

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

</td>

<td class="p-4">

<?= date(
'd M Y',
strtotime($row['issue_date'])
) ?>

</td>

<td class="p-4">

<?php

$badge = "bg-yellow-100 text-yellow-700";

if($row['status']=="Resolved"){
    $badge="bg-green-100 text-green-700";
}

if($row['status']=="Closed"){
    $badge="bg-gray-100 text-gray-700";
}

?>

<span class="px-3 py-1 rounded-full <?= $badge ?>">

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

</span>

</td>

<td class="p-4">

<a
href="disciplinary_review.php?id=<?= $row['id'] ?>"
class="bg-indigo-600 text-white px-4 py-2 rounded">

Review

</a>

</td>

</tr>

<?php endwhile; ?>

</tbody>

</table>

</div>

</div>

</body>
</html>