<?php include 'includes/header.php'; ?>
<?php include 'includes/sidebar.php'; ?>
<?php require 'includes/db_connect.php'; ?>

<?php
$mail_id = intval($_GET['mail_id']);
$mail_query = $conn->query("SELECT * FROM mails WHERE id = '$mail_id' ORDER BY id DESC");
$mail = $mail_query->fetch_assoc();
?>

<div class="container mt-4">
    <h4 class="text-orange">Mail History - <?= htmlspecialchars($mail['subject']); ?></h4>

    <div class="card mt-3">
        <div class="card-header text-white" style="background-color: orange;">Tracking No: <?= htmlspecialchars($mail['action']); ?></div>
        <div class="card-body">
            <p><strong>Subject:</strong> <?= htmlspecialchars($mail['subject']); ?></p>
            <p><strong>Type:</strong> <?= htmlspecialchars($mail['mail_type']); ?></p>
            <p><strong>Current Status:</strong> <?= htmlspecialchars($mail['status']); ?></p>
            <p><strong>Last Moved To:</strong> <?= htmlspecialchars($mail['department']); ?></p>
        </div>
    </div>

    <h5 class="mt-4 text-orange">Movement History</h5>

    <table class="table table-bordered mt-3">
        <thead class="text-white" style="background-color: orange;">
            <tr>
                <th>Date</th>
                <th>Moved By</th>
                <th>Moved To</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $history_query = $conn->query("SELECT * FROM mail_history WHERE mail_id = '$mail_id' ORDER BY id DESC");
            if ($history_query->num_rows > 0) {
                while ($history = $history_query->fetch_assoc()) {
                    // Fetch Staff Fullname and Department
                    $staff_id = $history['staff_id'];
                    $staff_query = $conn->query("SELECT fullname, department FROM staff WHERE id = '$staff_id'");
                    $staff_data = $staff_query->fetch_assoc();
                    $moved_by = $staff_data ? $staff_data['fullname'] . " (" . $staff_data['department'] . ")" : "Unknown Staff";

                    echo "<tr>
                        <td>{$history['action_date']}</td>
                        <td>{$moved_by}</td>
                        <td>{$staff_data['department']}</td>
                        <td>{$history['action']}</td>
                    </tr>";
                }
            } else {
                echo "<tr><td colspan='4' class='text-center'>No History Found.</td></tr>";
            }
            ?>
        </tbody>
    </table>

</div>

<?php include 'includes/footer.php'; ?>
