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

$bahagianList = audit_bahagian_list();
$auditId = (int) ($_GET['id'] ?? 0);
$isEdit = $auditId > 0;
require_department_access($conn, 'senarai_maklumat_audit', $isEdit ? 'update' : 'create');
$returnTo = $_GET['return_to'] ?? '';
$backUrl = $returnTo === 'senarai_maklumat_audit' ? 'senarai_maklumat_audit.php' : 'dashboard.php';
$data = [
    'perkara' => '',
    'tarikh_mula' => '',
    'tarikh_akhir' => '',
    'remarks' => '',
];
$selectedAssignments = [];
$existingAttachments = [];

if ($isEdit) {
    $stmt = $conn->prepare("SELECT id, perkara, tarikh_mula, tarikh_akhir, remarks FROM audit_forms WHERE id = ? LIMIT 1");
    $stmt->bind_param('i', $auditId);
    $stmt->execute();
    $found = $stmt->get_result()->fetch_assoc();
    if ($found) {
        $data = $found;
        $assignStmt = $conn->prepare("SELECT assigned_unit FROM audit_form_assignments WHERE audit_form_id = ?");
        $assignStmt->bind_param('i', $auditId);
        $assignStmt->execute();
        $selectedAssignments = array_column($assignStmt->get_result()->fetch_all(MYSQLI_ASSOC), 'assigned_unit');

        $attachmentStmt = $conn->prepare("SELECT attachment_path, attachment_name FROM audit_form_attachments WHERE audit_form_id = ? ORDER BY created_at DESC, id DESC");
        $attachmentStmt->bind_param('i', $auditId);
        $attachmentStmt->execute();
        $existingAttachments = $attachmentStmt->get_result()->fetch_all(MYSQLI_ASSOC);
    } else {
        header('Location: dashboard.php');
        exit();
    }
}

$extraJs = <<<HTML
<script>
function toggleAllBahagian(source) {
    document.querySelectorAll('.assign-checkbox').forEach((checkbox) => {
        checkbox.checked = source.checked;
    });
}
</script>
HTML;

render_layout_start(($isEdit ? 'Kemaskini' : 'Daftar') . ' Maklumat Audit - Dashboard Audit MAINPP');
?>
<style>
.assignment-panel {
    padding: 18px;
    margin-bottom: 0;
    border: 1px solid #e5edf7;
    border-radius: 14px;
    background: linear-gradient(180deg, #ffffff 0%, #f8fbff 100%);
    box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.55);
}
.assignment-master {
    display: flex;
    gap: 10px;
    align-items: center;
    margin-bottom: 14px;
    padding: 12px;
    border-radius: 12px;
    background: #eef7ff;
    color: #0f4c81;
    font-weight: 900;
}
.assignment-master input,
.assignment-option input {
    width: auto;
}
.assignment-option {
    display: flex;
    gap: 10px;
    align-items: flex-start;
    margin-bottom: 0;
    padding: 12px;
    border: 1px solid #e5edf7;
    border-radius: 12px;
    background: #fff;
    min-height: 56px;
}
.assignment-option:hover {
    border-color: #bfdbfe;
    background: #f8fbff;
}
html[data-theme="dark"] .assignment-panel,
html[data-theme="dark"] .assignment-option {
    background: #111827;
    border-color: #263244;
}
html[data-theme="dark"] .assignment-master {
    background: #172033;
    color: #bfdbfe;
}
</style>
<?php if (isset($_GET['error']) && $_GET['error'] === 'invalid_dates'): ?>
    <div class="status-message status-danger">Tarikh akhir mesti sama atau selepas tarikh mula.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'invalid_file'): ?>
    <div class="status-message status-danger">Lampiran tidak sah. Sila muat naik fail PDF, Word, Excel, JPG, JPEG atau PNG.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'upload_failed'): ?>
    <div class="status-message status-danger">Muat naik lampiran gagal. Sila cuba semula.</div>
<?php endif; ?>

<div class="content-card">
    <h3><i class="fa-solid fa-file-circle-plus"></i> <?= $isEdit ? 'Kemaskini' : 'Daftar' ?> Maklumat Audit</h3>
    <form action="proses_daftar_maklumat_audit.php" method="POST" enctype="multipart/form-data">
        <input type="hidden" name="audit_id" value="<?= (int) $auditId ?>">
        <input type="hidden" name="return_to" value="<?= htmlspecialchars($returnTo) ?>">
        <div class="form-grid">
            <div class="full-width">
                <label for="perkara">Perkara</label>
                <input type="text" id="perkara" name="perkara" value="<?= htmlspecialchars($data['perkara']) ?>" required>
            </div>
            <div>
                <label for="tarikh_mula">Tarikh Mula</label>
                <input type="date" id="tarikh_mula" name="tarikh_mula" value="<?= htmlspecialchars($data['tarikh_mula']) ?>" required>
            </div>
            <div>
                <label for="tarikh_akhir">Tarikh Akhir</label>
                <input type="date" id="tarikh_akhir" name="tarikh_akhir" value="<?= htmlspecialchars($data['tarikh_akhir']) ?>" required>
            </div>
            <div class="full-width">
                <label for="audit_attachments">Lampiran Fail</label>
                <input type="file" id="audit_attachments" name="audit_attachments[]" multiple accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png">
                <div class="field-note">Boleh muat naik lebih daripada satu fail. Format dibenarkan: PDF, Word, Excel, JPG, JPEG, PNG.</div>
                <?php if (!empty($existingAttachments)): ?>
                <div class="field-note" style="margin-top:8px;">
                    Lampiran sedia ada:
                    <?php foreach ($existingAttachments as $attachment): ?>
                        <a href="<?= htmlspecialchars($attachment['attachment_path']) ?>" onclick="openAttachmentPreview(event, '<?= htmlspecialchars($attachment['attachment_path'], ENT_QUOTES) ?>', '<?= htmlspecialchars($attachment['attachment_name'], ENT_QUOTES) ?>')"><?= htmlspecialchars($attachment['attachment_name']) ?></a>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
            <div class="full-width">
                <label>Tindakan Bahagian</label>
                <div class="assignment-panel">
                    <label class="assignment-master">
                        <input type="checkbox" onclick="toggleAllBahagian(this)">
                        <span>Pilih Semua Bahagian / Unit</span>
                    </label>
                    <div class="form-grid">
                        <?php foreach ($bahagianList as $bahagian): ?>
                        <label class="assignment-option">
                            <input class="assign-checkbox" type="checkbox" name="assign_to[]" value="<?= htmlspecialchars($bahagian) ?>" <?= in_array($bahagian, $selectedAssignments, true) ? 'checked' : '' ?>>
                            <span><?= htmlspecialchars($bahagian) ?></span>
                        </label>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <div class="full-width">
                <label for="remarks">Ringkasan Perkara Audit</label>
                <textarea id="remarks" name="remarks" rows="15"><?= htmlspecialchars($data['remarks']) ?></textarea>
            </div>
        </div>
        <div class="button-row">
            <button type="submit" class="primary-btn"><?= $isEdit ? 'Kemaskini' : 'Simpan' ?></button>
            <a href="<?= htmlspecialchars($backUrl) ?>" class="secondary-btn">Kembali</a>
        </div>
    </form>
</div>
<?php render_layout_end($extraJs); ?>
