<?php
include("../includes/auth.php");
include("../config/db.php");

$id = $_GET['id'];

$data = $conn->query("
    SELECT sr.*, u.name as requested_by_name
    FROM suspicious_requests sr
    LEFT JOIN users u ON sr.requested_by = u.id
    WHERE sr.id=$id
")->fetch_assoc();

// history
$history = $conn->query("
    SELECT sh.*, u.name 
    FROM suspicious_history sh
    LEFT JOIN users u ON sh.action_by = u.id
    WHERE sh.request_id=$id
    ORDER BY sh.id ASC
");

// ACTION
if (isset($_POST['action'])) {

    $action = $_POST['action'];
    $note = $_POST['note'];

    $status = ($action == 'approve') ? 'approved' : 'rejected';

    // update request
    $conn->query("
        UPDATE suspicious_requests 
        SET status='$status', super_admin_id=1, super_action_at=NOW()
        WHERE id=$id
    ");

    // insert history
    $conn->query("
        INSERT INTO suspicious_history (request_id, action_by, role, action, note)
        VALUES ($id, 1, 'super_admin', '$action', '$note')
    ");

    header("Location: index.php");
}
?>

<?php include("../includes/header.php"); ?>
<?php include("../includes/sidebar.php"); ?>

<h3>Request Details</h3>

<p><b>Requested By:</b> <?= $data['requested_by_name'] ?></p>
<p><b>Role:</b> <?= $data['requested_role'] ?></p>
<p><b>Reason:</b> <?= $data['reason'] ?></p>

<?php if ($data['document']) { ?>
<p><b>Document:</b><br>
<img src="../../uploads/<?= $data['document'] ?>" width="200">
</p>
<?php } ?>

<hr>

<h5>History</h5>

<ul>
<?php while($h = $history->fetch_assoc()) { ?>
    <li>
        <?= $h['role'] ?> - <?= $h['action'] ?> - <?= $h['note'] ?> (<?= $h['created_at'] ?>)
    </li>
<?php } ?>
</ul>

<hr>

<form method="POST">
    <textarea name="note" class="form-control mb-2" placeholder="Add note"></textarea>

    <button name="action" value="approve" class="btn btn-success">Approve</button>
    <button name="action" value="reject" class="btn btn-danger">Reject</button>
</form>

<?php include("../includes/footer.php"); ?>