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

$perkaraFilter = trim($_GET['perkara'] ?? '');
$bahagianFilter = trim($_GET['bahagian'] ?? '');
$statusFilter = trim($_GET['status'] ?? '');
$statusTindakanFilter = trim($_GET['status_tindakan'] ?? '');
$tarikhMulaFilter = trim($_GET['tarikh_mula'] ?? '');
$tarikhAkhirFilter = trim($_GET['tarikh_akhir'] ?? '');
$bahagianList = audit_bahagian_list();
$canUpdateAuditList = has_department_access($conn, 'senarai_maklumat_audit', 'update');
$canDeleteAuditList = has_department_access($conn, 'senarai_maklumat_audit', 'delete');
$allowedStatuses = ['Belum Dilaksanakan', 'Sedang Dalam Tempoh', 'Telah Selesai'];
$allowedActionStatuses = ['Belum Ambil Tindakan', 'Dikemaskini oleh Bahagian', 'Selesai di Audit'];
$today = new DateTimeImmutable('today');
$assignFeedbackStatusMap = [];

function get_audit_status(?string $tarikhMula, ?string $tarikhAkhir, DateTimeImmutable $today): array
{
    if (empty($tarikhMula) || empty($tarikhAkhir)) {
        return [
            'label' => 'Belum Dilaksanakan',
            'class' => 'audit-status-pending',
        ];
    }

    $mula = new DateTimeImmutable($tarikhMula);
    $akhir = new DateTimeImmutable($tarikhAkhir);

    if ($today < $mula) {
        return [
            'label' => 'Belum Dilaksanakan',
            'class' => 'audit-status-pending',
        ];
    }

    if ($today > $akhir) {
        return [
            'label' => 'Telah Selesai',
            'class' => 'audit-status-completed',
        ];
    }

    return [
        'label' => 'Sedang Dalam Tempoh',
        'class' => 'audit-status-progress',
    ];
}

$assignStatusStmt = $conn->query("
    SELECT audit_form_id, submitted_unit, created_at, updated_at
    FROM audit_feedbacks
");
if ($assignStatusStmt) {
    while ($statusRow = $assignStatusStmt->fetch_assoc()) {
        $auditFormId = (int) ($statusRow['audit_form_id'] ?? 0);
        $submittedUnit = trim((string) ($statusRow['submitted_unit'] ?? ''));
        if ($auditFormId <= 0 || $submittedUnit === '') {
            continue;
        }

        $hasUpdated = strtotime((string) ($statusRow['updated_at'] ?? '')) > strtotime((string) ($statusRow['created_at'] ?? ''));
        if (!isset($assignFeedbackStatusMap[$auditFormId])) {
            $assignFeedbackStatusMap[$auditFormId] = [];
        }

        if ($hasUpdated) {
            $assignFeedbackStatusMap[$auditFormId][$submittedUnit] = 'updated';
            continue;
        }

        if (!isset($assignFeedbackStatusMap[$auditFormId][$submittedUnit])) {
            $assignFeedbackStatusMap[$auditFormId][$submittedUnit] = 'submitted';
        }
    }
}

$result = $conn->query("
    SELECT af.id, af.perkara, af.tarikh_mula, af.tarikh_akhir, af.remarks, af.audit_approval_status,
           GROUP_CONCAT(afa.assigned_unit ORDER BY afa.assigned_unit SEPARATOR '||') AS assigned_units
    FROM audit_forms af
    LEFT JOIN audit_form_assignments afa ON afa.audit_form_id = af.id
    GROUP BY af.id
    ORDER BY af.created_at DESC
");

$records = [];

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $assignedUnits = array_values(array_filter(array_map('trim', explode('||', (string) ($row['assigned_units'] ?? '')))));
        $status = get_audit_status($row['tarikh_mula'] ?? null, $row['tarikh_akhir'] ?? null, $today);

        if ($perkaraFilter !== '' && stripos((string) $row['perkara'], $perkaraFilter) === false) {
            continue;
        }

        if ($bahagianFilter !== '' && !in_array($bahagianFilter, $assignedUnits, true)) {
            continue;
        }

        if ($statusFilter !== '' && $status['label'] !== $statusFilter) {
            continue;
        }

        if ($tarikhMulaFilter !== '' && (string) ($row['tarikh_mula'] ?? '') !== $tarikhMulaFilter) {
            continue;
        }

        if ($tarikhAkhirFilter !== '' && (string) ($row['tarikh_akhir'] ?? '') !== $tarikhAkhirFilter) {
            continue;
        }

        $row['assigned_units_array'] = $assignedUnits;
        $row['status_label'] = $status['label'];
        $row['status_class'] = $status['class'];
        $approvalValue = (string) ($row['audit_approval_status'] ?? 'perlu_kemaskini');
        $allUnitsReadyForApproval = !empty($assignedUnits);
        foreach ($assignedUnits as $unit) {
            $assignStatus = $assignFeedbackStatusMap[(int) $row['id']][$unit] ?? 'pending';
            if (!in_array($assignStatus, ['submitted', 'updated'], true)) {
                $allUnitsReadyForApproval = false;
                break;
            }
        }
        $rowActionStatuses = [];
        foreach ($assignedUnits as $unit) {
            $assignStatus = $assignFeedbackStatusMap[(int) $row['id']][$unit] ?? 'pending';
            if ($approvalValue === 'lulus_diaudit' && $allUnitsReadyForApproval) {
                $rowActionStatuses[] = 'Selesai di Audit';
            } elseif ($assignStatus === 'updated' || $assignStatus === 'submitted') {
                $rowActionStatuses[] = 'Dikemaskini oleh Bahagian';
            } else {
                $rowActionStatuses[] = 'Belum Ambil Tindakan';
            }
        }
        $rowActionStatuses = array_values(array_unique($rowActionStatuses));

        if ($statusTindakanFilter !== '' && !in_array($statusTindakanFilter, $rowActionStatuses, true)) {
            continue;
        }

        $row['action_statuses'] = $rowActionStatuses;
        $records[] = $row;
    }
}

$hasAuditFilters = ($perkaraFilter !== '' || $bahagianFilter !== '' || $statusFilter !== '' || $statusTindakanFilter !== '' || $tarikhMulaFilter !== '' || $tarikhAkhirFilter !== '');
if ($hasAuditFilters) {
    add_current_user_log($conn, 'Menapis senarai maklumat audit');
} else {
    add_current_user_log($conn, 'Membuka senarai maklumat audit');
}

render_layout_start('Senarai Maklumat Audit - Dashboard Audit MAINPP');
?>
<style>
.assign-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
}
.assign-pill {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 10px;
    border-radius: 999px;
    background: #eef5ff;
    color: #0d6efd;
    font-size: 12px;
    font-weight: 700;
    line-height: 1.2;
}
.assign-pill.assign-pending {
    background: #fee2e2;
    color: #b91c1c;
}
.assign-pill.assign-submitted {
    background: #fef3c7;
    color: #92400e;
}
.assign-pill.assign-updated {
    background: #fef3c7;
    color: #92400e;
}
.assign-pill.assign-approved {
    background: #dcfce7;
    color: #166534;
}
.assign-extra {
    display: none;
}
.assign-extra.show {
    display: flex;
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
}
.assign-more-btn {
    border: none;
    background: transparent;
    color: #0d6efd;
    font-size: 13px;
    font-weight: 700;
    cursor: pointer;
    padding: 0;
}
.assign-more-btn:hover {
    text-decoration: underline;
}
.action-stack {
    display: inline-flex;
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
}
.action-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;
}
.action-btn.edit-btn {
    background: #eef5ff;
    color: #0d6efd;
}
.action-btn.delete-btn {
    background: #fee2e2;
    color: #dc3545;
}
.action-btn.view-btn {
    background: #f3f4f6;
    color: #334155;
}
.audit-filter-grid {
    display: grid;
    grid-template-columns: repeat(6, minmax(0, 1fr));
    gap: 14px;
    margin-top: 18px;
}
.audit-status-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    border-radius: 999px;
    padding: 6px 10px;
    font-size: 12px;
    font-weight: 700;
}
.audit-status-pending {
    background: #fee2e2;
    color: #b91c1c;
}
.audit-status-progress {
    background: #fef3c7;
    color: #92400e;
}
.audit-status-completed {
    background: #dcfce7;
    color: #166534;
}
.remarks-preview {
    max-width: 360px;
}
.remarks-content {
    white-space: pre-line;
    line-height: 1.45;
    overflow: hidden;
}
.remarks-content.is-collapsed {
    display: -webkit-box;
    -webkit-line-clamp: 5;
    -webkit-box-orient: vertical;
}
.remarks-toggle {
    display: none;
    margin-top: 8px;
    border: none;
    background: transparent;
    color: #0d6efd;
    font-size: 13px;
    font-weight: 800;
    cursor: pointer;
    padding: 0;
}
.remarks-toggle.show {
    display: inline-flex;
}
.remarks-toggle:hover {
    text-decoration: underline;
}
@media (max-width: 768px) {
    .audit-filter-grid {
        grid-template-columns: 1fr;
    }
}
</style>
<?php if (isset($_GET['success']) && $_GET['success'] === 'audit_saved'): ?>
    <div class="status-message status-success">Maklumat audit berjaya disimpan.</div>
<?php endif; ?>

<div class="page-card">
    <h3><i class="fa-solid fa-list-check"></i> Senarai Maklumat Audit</h3>
    <form method="GET">
        <div class="audit-filter-grid">
            <div>
                <label for="perkara">Perkara</label>
                <input type="text" id="perkara" name="perkara" placeholder="Cari perkara audit" value="<?= htmlspecialchars($perkaraFilter) ?>">
            </div>
            <div>
                <label for="bahagian">Bahagian</label>
                <select id="bahagian" 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>
            </div>
            <div>
                <label for="status">Tempoh Audit</label>
                <select id="status" 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>
            </div>
            <div>
                <label for="status_tindakan">Status Tindakan</label>
                <select id="status_tindakan" name="status_tindakan">
                    <option value="">Semua Status Tindakan</option>
                    <?php foreach ($allowedActionStatuses as $actionStatus): ?>
                        <option value="<?= htmlspecialchars($actionStatus) ?>" <?= $statusTindakanFilter === $actionStatus ? 'selected' : '' ?>>
                            <?= htmlspecialchars($actionStatus) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label for="tarikh_mula">Tarikh Mula</label>
                <input type="date" id="tarikh_mula" name="tarikh_mula" value="<?= htmlspecialchars($tarikhMulaFilter) ?>">
            </div>
            <div>
                <label for="tarikh_akhir">Tarikh Akhir</label>
                <input type="date" id="tarikh_akhir" name="tarikh_akhir" value="<?= htmlspecialchars($tarikhAkhirFilter) ?>">
            </div>
        </div>
        <div class="button-row">
            <button type="submit" class="search-btn">Tapis</button>
            <a href="senarai_maklumat_audit.php" class="reset-btn">Reset</a>
        </div>
    </form>
</div>

<div class="table-container">
    <table>
        <thead>
            <tr>
                <th>Bil</th>
                <th>Perkara</th>
                <th>Tarikh Mula</th>
                <th>Tarikh Akhir</th>
                <th>Tempoh Audit</th>
                <th>Tindakan Bahagian</th>
                <th>Ringkasan Perkara Audit</th>
                <th>Tindakan</th>
            </tr>
        </thead>
        <tbody>
            <?php if (!empty($records)): ?>
                <?php $bil = 1; foreach ($records as $row): ?>
                <?php
                $approvalValue = (string) ($row['audit_approval_status'] ?? 'perlu_kemaskini');
                $allUnitsReadyForApproval = !empty($row['assigned_units_array']);
                foreach ($row['assigned_units_array'] as $unit) {
                    $unitStatus = $assignFeedbackStatusMap[(int) $row['id']][$unit] ?? 'pending';
                    if (!in_array($unitStatus, ['submitted', 'updated'], true)) {
                        $allUnitsReadyForApproval = false;
                        break;
                    }
                }
                ?>
                <tr>
                    <td><?= $bil++ ?></td>
                    <td><?= htmlspecialchars($row['perkara']) ?></td>
                    <td><?= !empty($row['tarikh_mula']) ? date('d/m/Y', strtotime($row['tarikh_mula'])) : '-' ?></td>
                    <td><?= !empty($row['tarikh_akhir']) ? date('d/m/Y', strtotime($row['tarikh_akhir'])) : '-' ?></td>
                    <td>
                        <span class="audit-status-badge <?= htmlspecialchars($row['status_class']) ?>">
                            <?= htmlspecialchars($row['status_label']) ?>
                        </span>
                    </td>
                    <td>
                        <?php if (!empty($row['assigned_units_array'])): ?>
                        <div class="assign-list">
                            <?php foreach (array_slice($row['assigned_units_array'], 0, 2) as $unit): ?>
                            <?php
                            $assignStatus = $assignFeedbackStatusMap[(int) $row['id']][$unit] ?? 'pending';
                            $assignClass = 'assign-pending';
                            if ($assignStatus === 'submitted') {
                                $assignClass = 'assign-submitted';
                            } elseif ($assignStatus === 'updated') {
                                $assignClass = 'assign-updated';
                            }
                            if ($approvalValue === 'lulus_diaudit' && $allUnitsReadyForApproval) {
                                $assignClass = 'assign-approved';
                            }
                            ?>
                            <span class="assign-pill <?= $assignClass ?>">
                                <i class="fa-solid fa-building"></i>
                                <?= htmlspecialchars($unit) ?>
                            </span>
                            <?php endforeach; ?>
                            <?php if (count($row['assigned_units_array']) > 2): ?>
                            <div class="assign-extra" id="assign-extra-<?= (int) $row['id'] ?>">
                                <?php foreach (array_slice($row['assigned_units_array'], 2) as $unit): ?>
                                <?php
                                $assignStatus = $assignFeedbackStatusMap[(int) $row['id']][$unit] ?? 'pending';
                                $assignClass = 'assign-pending';
                                if ($assignStatus === 'submitted') {
                                    $assignClass = 'assign-submitted';
                                } elseif ($assignStatus === 'updated') {
                                    $assignClass = 'assign-updated';
                                }
                                if ($approvalValue === 'lulus_diaudit' && $allUnitsReadyForApproval) {
                                    $assignClass = 'assign-approved';
                                }
                                ?>
                                <span class="assign-pill <?= $assignClass ?>">
                                    <i class="fa-solid fa-building"></i>
                                    <?= htmlspecialchars($unit) ?>
                                </span>
                                <?php endforeach; ?>
                            </div>
                            <button type="button" class="assign-more-btn" onclick="toggleAssignMore(<?= (int) $row['id'] ?>, this)">Lihat Lagi</button>
                            <?php endif; ?>
                        </div>
                        <?php else: ?>
                        -
                        <?php endif; ?>
                    </td>
                    <td>
                        <div class="remarks-preview">
                            <div class="remarks-content is-collapsed"><?= htmlspecialchars($row['remarks'] ?: '-') ?></div>
                            <button type="button" class="remarks-toggle" onclick="toggleRemarks(this)">Lihat Lagi</button>
                        </div>
                    </td>
                    <td>
                        <div class="action-stack">
                            <?php if ($canUpdateAuditList): ?>
                                <a href="daftar_maklumat_audit.php?id=<?= (int) $row['id'] ?>&return_to=senarai_maklumat_audit" class="action-btn edit-btn">
                                    <i class="fa-solid fa-pen"></i> Edit
                                </a>
                            <?php endif; ?>
                            <?php if ($canDeleteAuditList): ?>
                                <a href="padam_maklumat_audit.php?id=<?= (int) $row['id'] ?>" class="action-btn delete-btn" onclick="return confirm('Padam maklumat audit ini?')">
                                    <i class="fa-solid fa-trash"></i> Delete
                                </a>
                            <?php endif; ?>
                            <a href="detail_maklumat_audit.php?id=<?= (int) $row['id'] ?>" class="action-btn view-btn">
                                <i class="fa-solid fa-eye"></i> View
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr><td colspan="8" class="empty-state">Tiada maklumat audit ditemui.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>
<?php
$extraJs = <<<HTML
<script>
function toggleAssignMore(recordId, button) {
    const extra = document.getElementById('assign-extra-' + recordId);
    if (!extra) return;
    const isOpen = extra.classList.toggle('show');
    button.textContent = isOpen ? 'Lihat Kurang' : 'Lihat Lagi';
}

function toggleRemarks(button) {
    const wrapper = button.closest('.remarks-preview');
    const content = wrapper ? wrapper.querySelector('.remarks-content') : null;
    if (!content) return;
    const isOpening = content.classList.toggle('is-collapsed') === false;
    button.textContent = isOpening ? 'Lihat Kurang' : 'Lihat Lagi';
}

document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.remarks-preview').forEach(function (wrapper) {
        const content = wrapper.querySelector('.remarks-content');
        const button = wrapper.querySelector('.remarks-toggle');
        if (!content || !button) return;
        if (content.scrollHeight > content.clientHeight + 2) {
            button.classList.add('show');
        }
    });
});
</script>
HTML;

render_layout_end($extraJs);
?>
