<?php
session_start();
include '../../connection.php';

if (isset($_POST['loading_complaints'])) {
    $id = $_SESSION['resident_id'];

    echo '
    <table class="table table-sm table-striped" id="mytable">
        <thead>
            <tr>
                <th>ID</th>
                <th>Complaint Type</th>
                <th>Incident Address</th>
                <th>Date of Incident</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
    ';

    $query = "
        SELECT 
            t.UniqueID,
            t.incident_address,
            t.description,
            t.status,
            t.incident_date,
            t.date_created,
            c.complain_name
        FROM tbl_transaction t
        LEFT JOIN tbl_complaint_types c ON t.complaint_type_id = c.complaint_type_id
        WHERE t.resident_id = '$id'
        ORDER BY t.UniqueID DESC
    ";

    $query_result = $conn->query($query);

    if ($query_result && $query_result->num_rows > 0) {
        while ($row = $query_result->fetch_assoc()) {
            // Optional: format ID with prefix (e.g., BC-0001)
            $formattedID = "#BC-" . str_pad($row['UniqueID'], 4, "0", STR_PAD_LEFT);

            // Status badge color
            $statusClass = '';
            switch (strtolower($row['status'])) {
                case 'pending': $statusClass = 'badge badge-warning'; break;
                case 'in progress': $statusClass = 'badge badge-info'; break;
                case 'resolved': $statusClass = 'badge badge-success'; break;
                default: $statusClass = 'badge badge-secondary'; break;
            }

            echo '
                <tr>
                    <td>' . $formattedID . '</td>
                    <td>' . htmlspecialchars($row['complain_name']) . '</td>
                    <td>' . htmlspecialchars($row['incident_address']) . '</td>
                    <td>' . htmlspecialchars($row['incident_date']) . '</td>
                    <td><span class="' . $statusClass . '">' . htmlspecialchars(ucwords($row['status'])) . '</span>
                    </td>
                </tr>
            ';
        }
    } else {
        echo '
            <tr>
                <td colspan="6" class="text-center text-muted">No complaints found.</td>
            </tr>
        ';
    }

    echo '
        </tbody>
    </table>
    ';
}
?>
