<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);

require_once "../db.php";

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

function h($v){
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES);
}

/* ================= GET USER ================= */
$user = $_GET['user'] ?? '';

if (!$user) {
    die("User not specified.");
}

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

/* ================= HANDLE DELETE ================= */
if (isset($_POST['delete_id'])) {

    $deleteId = (int)$_POST['delete_id'];

    $stmt = $conn->prepare("
        DELETE FROM enrolment_requests
        WHERE id=? AND user=?
        LIMIT 1
    ");

    $stmt->bind_param("is",$deleteId,$user);
    $stmt->execute();
    $stmt->close();

    header("Location: admin_user_requests.php?user=".urlencode($user)."&search=".urlencode($search));
    exit;
}

/* ================= HANDLE UPDATE ================= */
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['id'])) {

    $id         = (int)$_POST['id'];
    $nin        = trim($_POST['nin']);
    $trackingId = trim($_POST['tracking_id']);
    $status     = trim($_POST['status']);

    /* ===== UPDATE ===== */
    $stmt = $conn->prepare("
        UPDATE enrolment_requests
        SET nin=?, tracking_id=?, status=?
        WHERE id=? AND user=?
    ");

    $stmt->bind_param("sssis",$nin,$trackingId,$status,$id,$user);
    $stmt->execute();
    $stmt->close();

    header("Location: admin_user_requests.php?user=".urlencode($user)."&search=".urlencode($search));
    exit;
}

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

if ($search != '') {

    $stmt = $conn->prepare("
        SELECT id, tracking_id, type, nin, status, created_at
        FROM enrolment_requests
        WHERE user=? 
        AND (
            nin LIKE ?
            OR tracking_id LIKE ?
        )
        ORDER BY id DESC
    ");

    $like = "%".$search."%";

    $stmt->bind_param("sss",$user,$like,$like);

} else {

    $stmt = $conn->prepare("
        SELECT id, tracking_id, type, nin, status, created_at
        FROM enrolment_requests
        WHERE user=?
        ORDER BY id DESC
    ");

    $stmt->bind_param("s",$user);
}

$stmt->execute();
$result = $stmt->get_result();
?>

<!DOCTYPE html>
<html>
<head>
<title>User Requests</title>
<meta name="viewport" content="width=device-width,initial-scale=1">

<style>

body{
    font-family:Arial;
    background:#f3f4f6;
    padding:20px;
}

.card{
    background:#fff;
    padding:20px;
    border-radius:14px;
    max-width:1300px;
    margin:auto;
    overflow:auto;
}

h2{
    margin-bottom:15px;
}

table{
    width:100%;
    border-collapse:collapse;
}

th,td{
    padding:10px;
    border-bottom:1px solid #ddd;
    text-align:center;
}

th{
    background:#111827;
    color:#fff;
}

.back{
    display:inline-block;
    margin-bottom:15px;
    background:#2563eb;
    color:#fff;
    padding:8px 12px;
    border-radius:6px;
    text-decoration:none;
}

input,select{
    padding:6px;
    border-radius:6px;
    border:1px solid #ccc;
    width:100%;
    box-sizing:border-box;
}

button{
    padding:6px 10px;
    border:none;
    border-radius:6px;
    cursor:pointer;
}

.update-btn{
    background:#16a34a;
    color:#fff;
}

.delete-btn{
    background:#dc2626;
    color:#fff;
}

.search-btn{
    background:#2563eb;
    color:#fff;
}

.status-badge{
    padding:6px 10px;
    border-radius:999px;
    color:#fff;
    font-size:12px;
    font-weight:bold;
}

.pending{
    background:#f59e0b;
}

.sent{
    background:#22c55e;
}

.approved{
    background:#2563eb;
}

.validated{
    background:#7c3aed;
}

.failed{
    background:#dc2626;
}

.search-box{
    display:flex;
    gap:10px;
    margin-bottom:20px;
}

.search-box input{
    flex:1;
}

@media(max-width:768px){

    table{
        font-size:13px;
    }

    th,td{
        padding:6px;
    }

}

</style>

<script>
function confirmDelete(){
    return confirm("Are you sure you want to delete this request?");
}
</script>

</head>
<body>

<div class="card">

<a class="back" href="admin_enrolment_summary.php">← Back to Summary</a>

<h2>📄 Requests for: <?= h($user) ?></h2>

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

    <input type="hidden" name="user" value="<?= h($user) ?>">

    <input 
        type="text" 
        name="search"
        placeholder="Search by NIN or Tracking ID"
        value="<?= h($search) ?>"
    >

    <button type="submit" class="search-btn">
        Search
    </button>

</form>

<table>

<tr>
<th>ID</th>
<th>Tracking ID</th>
<th>Type</th>
<th>NIN</th>
<th>Status</th>
<th>Date</th>
<th>Update</th>
<th>Delete</th>
</tr>

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

<tr>

<!-- UPDATE FORM -->
<form method="post">

<td>
<?= $row['id'] ?>
</td>

<td>
<input 
    type="text" 
    name="tracking_id" 
    value="<?= h($row['tracking_id']) ?>" 
    required
>
</td>

<td>
<?= strtoupper(h($row['type'])) ?>
</td>

<td>
<input 
    type="text" 
    name="nin" 
    value="<?= h($row['nin']) ?>"
    required
>
</td>

<td>

<div style="margin-bottom:6px">

<span class="status-badge <?= h($row['status']) ?>">
<?= ucfirst(h($row['status'])) ?>
</span>

</div>

<select name="status">

<option value="pending" <?= $row['status']=='pending'?'selected':'' ?>>
Pending
</option>

<option value="sent" <?= $row['status']=='sent'?'selected':'' ?>>
Sent
</option>

<option value="approved" <?= $row['status']=='approved'?'selected':'' ?>>
Approved
</option>

<option value="validated" <?= $row['status']=='validated'?'selected':'' ?>>
Validated
</option>

<option value="failed" <?= $row['status']=='failed'?'selected':'' ?>>
Failed
</option>

</select>

</td>

<td>
<?= h($row['created_at']) ?>
</td>

<td>

<input type="hidden" name="id" value="<?= $row['id'] ?>">

<button type="submit" class="update-btn">
Update
</button>

</td>

</form>

<!-- DELETE FORM -->
<td>

<form method="post" onsubmit="return confirmDelete();">

<input type="hidden" name="delete_id" value="<?= $row['id'] ?>">

<button type="submit" class="delete-btn">
Delete
</button>

</form>

</td>

</tr>

<?php endwhile; ?>

</table>

</div>

</body>
</html>