<?php
require_once __DIR__ . '/includes/layout.php';
require_login();
require_roles(['Pengguna Biasa', 'Admin Audit', 'Pentadbir Sistem']);
require_department_access($conn, 'senarai_maklum_balas_audit', 'read');

$search = trim($_GET['search'] ?? '');
$statusFilter = trim($_GET['status'] ?? '');
$bahagianFilter = trim($_GET['bahagian'] ?? '');
$bahagianList = audit_bahagian_list();
$allowedStatuses = ['Perlu Tindakan', 'Dalam Tindakan', 'Selesai'];

$whereClauses = [];
$types = '';
$params = [];

if ($search !== '') {
    $searchLike = '%' . $search . '%';
    $whereClauses[] = '(af.perkara LIKE ? OR f.nama LIKE ? OR fb.ringkasan LIKE ? OR fb.maklum_balas LIKE ?)';
    $types .= 'ssss';
    array_push($params, $searchLike, $searchLike, $searchLike, $searchLike);
}

if ($statusFilter !== '' && in_array($statusFilter, $allowedStatuses, true)) {
    $whereClauses[] = 'fb.status_tindakan = ?';
    $types .= 's';
    $params[] = $statusFilter;
}

if ($bahagianFilter !== '' && in_array($bahagianFilter, $bahagianList, true)) {
    $whereClauses[] = 'fb.submitted_unit = ?';
    $types .= 's';
    $params[] = $bahagianFilter;
}

$sql = "
    SELECT fb.id, fb.status_tindakan, fb.ringkasan, fb.maklum_balas, fb.attachment_path, fb.attachment_name, fb.created_at, fb.updated_at,
           af.id AS audit_id, af.perkara,
           f.nama, f.role, f.jabatan
    FROM audit_feedbacks fb
    INNER JOIN audit_forms af ON af.id = fb.audit_form_id
    INNER JOIN users f ON f.id = fb.submitted_by
";

if (!empty($whereClauses)) {
    $sql .= ' WHERE ' . implode(' AND ', $whereClauses);
}

$sql .= ' ORDER BY fb.updated_at DESC, fb.id DESC';

if (!empty($params)) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
} else {
    $result = $conn->query($sql);
    $records = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
}

render_layout_start('Senarai Maklum Balas Audit - Dashboard Audit MAINPP');
?>
<style>
.feedback-status {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 10px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: 700;
}
.feedback-status.perlu {
    background: #fee2e2;
    color: #b91c1c;
}
.feedback-status.proses {
    background: #fef3c7;
    color: #92400e;
}
.feedback-status.selesai {
    background: #dcfce7;
    color: #166534;
}
.feedback-link {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: #0d6efd;
    text-decoration: none;
    font-weight: 700;
}
.feedback-link:hover {
    text-decoration: underline;
}
.action-btn.view-btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 14px;
    border-radius: 999px;
    font-size: 14px;
    font-weight: 700;
    text-decoration: none;
    white-space: nowrap;
    background: #f3f4f6;
    color: #334155;
}
</style>

<div class="page-card">
    <h3><i class="fa-solid fa-comments"></i> Senarai Maklum Balas Audit</h3>
    <form method="GET" class="search-form">
        <div class="search-input-wrap">
            <i class="fa-solid fa-magnifying-glass"></i>
            <input type="text" name="search" class="search-input" placeholder="Cari perkara audit, nama, ringkasan atau maklum balas" value="<?= htmlspecialchars($search) ?>">
        </div>
        <select name="bahagian">
            <option value="">Semua Bahagian / Unit</option>
            <?php foreach ($bahagianList as $bahagian): ?>
                <option value="<?= htmlspecialchars($bahagian) ?>" <?= $bahagianFilter === $bahagian ? 'selected' : '' ?>><?= htmlspecialchars($bahagian) ?></option>
            <?php endforeach; ?>
        </select>
        <select name="status">
            <option value="">Semua Status</option>
            <?php foreach ($allowedStatuses as $status): ?>
                <option value="<?= htmlspecialchars($status) ?>" <?= $statusFilter === $status ? 'selected' : '' ?>><?= htmlspecialchars($status) ?></option>
            <?php endforeach; ?>
        </select>
        <button type="submit" class="search-btn">Cari</button>
        <a href="senarai_maklum_balas_audit.php" class="reset-btn">Reset</a>
    </form>
</div>

<div class="table-container">
    <table>
        <thead>
            <tr>
                <th>Bil</th>
                <th>Perkara Audit</th>
                <th>Nama</th>
                <th>Bahagian / Unit</th>
                <th>Role</th>
                <th>Ringkasan</th>
                <th>Lampiran</th>
                <th>Tarikh Hantar</th>
                <th>Tindakan</th>
            </tr>
        </thead>
        <tbody>
            <?php if (!empty($records)): ?>
                <?php $bil = 1; foreach ($records as $row): ?>
                <tr>
                    <td><?= $bil++ ?></td>
                    <td><strong><?= htmlspecialchars($row['perkara']) ?></strong></td>
                    <td><?= htmlspecialchars($row['nama']) ?></td>
                    <td><?= htmlspecialchars($row['jabatan']) ?></td>
                    <td><span class="role-badge"><i class="fa-solid fa-user-shield"></i><?= htmlspecialchars($row['role']) ?></span></td>
                    <td>
                        <strong><?= htmlspecialchars($row['ringkasan']) ?></strong><br>
                        <span><?= nl2br(htmlspecialchars($row['maklum_balas'])) ?></span>
                    </td>
                    <td>
                        <a href="<?= htmlspecialchars($row['attachment_path']) ?>" class="feedback-link" onclick="openAttachmentPreview(event, '<?= htmlspecialchars($row['attachment_path'], ENT_QUOTES) ?>', '<?= htmlspecialchars($row['attachment_name'], ENT_QUOTES) ?>')">
                            <i class="fa-solid fa-paperclip"></i> <?= htmlspecialchars($row['attachment_name']) ?>
                        </a>
                    </td>
                    <td><?= date('d/m/Y h:i A', strtotime($row['updated_at'] ?: $row['created_at'])) ?></td>
                    <td>
                        <a href="detail_maklum_balas_audit.php?id=<?= (int) $row['id'] ?>" class="action-btn view-btn">
                            <i class="fa-solid fa-eye"></i> View
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            <?php else: ?>
            <tr>
                <td colspan="9" class="empty-state">Tiada maklum balas audit ditemui.</td>
            </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>
<?php render_layout_end(); ?>
