<?php
require_once __DIR__ . '/includes/layout.php';
require_login();

$auditId = (int) ($_GET['id'] ?? 0);
if ($auditId <= 0) {
    header('Location: dashboard.php');
    exit();
}

$auditStmt = $conn->prepare("
    SELECT af.id, af.perkara, af.tarikh_mula, af.tarikh_akhir, af.remarks,
           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
    WHERE af.id = ?
    GROUP BY af.id
    LIMIT 1
");
$auditStmt->bind_param('i', $auditId);
$auditStmt->execute();
$audit = $auditStmt->get_result()->fetch_assoc();

if (!$audit) {
    header('Location: dashboard.php');
    exit();
}

$assignedUnits = array_values(array_filter(array_map('trim', explode('||', (string) ($audit['assigned_units'] ?? '')))));
$currentUnit = current_user_unit();
$currentUserId = current_user_id();
$todayDate = date('Y-m-d');
$tarikhMula = trim((string) ($audit['tarikh_mula'] ?? ''));
$tarikhAkhir = trim((string) ($audit['tarikh_akhir'] ?? ''));

if ($tarikhMula !== '' && $todayDate < $tarikhMula) {
    header('Location: dashboard.php?error=feedback_not_started');
    exit();
}

if ($tarikhAkhir !== '' && $todayDate > $tarikhAkhir) {
    header('Location: dashboard.php?error=feedback_closed');
    exit();
}

$feedbackData = [
    'submitted_unit' => $currentUnit,
    'assigned_to_user_id' => '',
    'status_tindakan' => 'Perlu Tindakan',
    'ringkasan' => '',
    'maklum_balas' => '',
    'attachment_name' => '',
];
$existingAttachments = [];

$feedbackStmt = $conn->prepare("
    SELECT submitted_unit, assigned_to_user_id, status_tindakan, ringkasan, maklum_balas, attachment_name
    FROM audit_feedbacks
    WHERE audit_form_id = ?
      AND (submitted_unit = ? OR assigned_to_user_id = ?)
    ORDER BY CASE WHEN assigned_to_user_id = ? THEN 0 ELSE 1 END, id DESC
    LIMIT 1
");
$feedbackStmt->bind_param('isii', $auditId, $currentUnit, $currentUserId, $currentUserId);
$feedbackStmt->execute();
$existingFeedback = $feedbackStmt->get_result()->fetch_assoc();
if ($existingFeedback) {
    $feedbackData = $existingFeedback;
    $feedbackIdStmt = $conn->prepare("
        SELECT id
        FROM audit_feedbacks
        WHERE audit_form_id = ?
          AND (submitted_unit = ? OR assigned_to_user_id = ?)
        ORDER BY CASE WHEN assigned_to_user_id = ? THEN 0 ELSE 1 END, id DESC
        LIMIT 1
    ");
    $feedbackIdStmt->bind_param('isii', $auditId, $currentUnit, $currentUserId, $currentUserId);
    $feedbackIdStmt->execute();
    $feedbackIdRow = $feedbackIdStmt->get_result()->fetch_assoc();
    $feedbackId = (int) ($feedbackIdRow['id'] ?? 0);
    if ($feedbackId > 0) {
        $attachmentStmt = $conn->prepare("
            SELECT attachment_path, attachment_name
            FROM audit_feedback_attachments
            WHERE audit_feedback_id = ?
            ORDER BY created_at DESC, id DESC
        ");
        $attachmentStmt->bind_param('i', $feedbackId);
        $attachmentStmt->execute();
        $existingAttachments = $attachmentStmt->get_result()->fetch_all(MYSQLI_ASSOC);
    }
}

$assignedToUserId = (int) ($feedbackData['assigned_to_user_id'] ?? 0);
$feedbackUnit = trim((string) ($feedbackData['submitted_unit'] ?? $currentUnit));
$canOpenByAssignedUnit = in_array($currentUnit, $assignedUnits, true);
$canOpenByAssignedUser = $assignedToUserId > 0 && $assignedToUserId === $currentUserId;

if (!$existingFeedback && !$canOpenByAssignedUnit) {
    header('Location: dashboard.php');
    exit();
}

if ($existingFeedback && !$canOpenByAssignedUnit && !$canOpenByAssignedUser) {
    header('Location: dashboard.php?error=feedback_assigned');
    exit();
}

render_layout_start('Maklum Balas Audit - Dashboard Audit MAINPP');
?>
<?php if (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 elseif (isset($_GET['error']) && $_GET['error'] === 'invalid_assign_to'): ?>
<?php endif; ?>

<div class="content-card">
    <h3><i class="fa-solid fa-comment-dots"></i> Borang Maklum Balas Audit</h3>
    <form action="proses_maklum_balas_audit.php" method="POST" enctype="multipart/form-data">
        <input type="hidden" name="audit_id" value="<?= (int) $auditId ?>">
        <div class="form-grid">
            <div class="full-width">
                <label>Perkara Audit</label>
                <input type="text" value="<?= htmlspecialchars($audit['perkara']) ?>" readonly>
            </div>
            <div>
                <label>Bahagian / Unit</label>
                <input type="text" value="<?= htmlspecialchars($feedbackUnit) ?>" readonly>
            </div>
            <div>
                <label>Tarikh Maklum Balas</label>
                <input type="text" value="<?= date('d/m/Y') ?>" readonly>
            </div>
            <div class="full-width">
                <label for="ringkasan">Ringkasan Maklum Balas</label>
                <input type="text" id="ringkasan" name="ringkasan" value="<?= htmlspecialchars($feedbackData['ringkasan'] ?? '') ?>" placeholder="Contoh: Tindakan pembetulan sedang dijalankan">
            </div>
            <div class="full-width">
                <label for="maklum_balas">Maklum Balas / Tindakan Susulan</label>
                <textarea id="maklum_balas" name="maklum_balas" rows="25"><?= htmlspecialchars($feedbackData['maklum_balas'] ?? '') ?></textarea>
                <div class="field-note">Cadangan sesuai: nyatakan isu, tindakan yang telah diambil, pegawai terlibat, dan tarikh sasaran jika masih dalam tindakan.</div>
            </div>
            <div class="full-width">
                <label for="attachment_file">Lampiran Fail</label>
                <input type="file" id="attachment_file" name="attachment_file[]" multiple accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png">
                <?php if (!empty($existingAttachments)): ?>
                    <div class="field-note">
                        Lampiran semasa:
                        <?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 elseif (!empty($feedbackData['attachment_name'])): ?>
                    <div class="field-note">Lampiran semasa: <?= htmlspecialchars($feedbackData['attachment_name']) ?>. Fail baru yang dimuat naik akan ditambah sebagai lampiran tambahan.</div>
                <?php else: ?>
                    <div class="field-note">Lampiran adalah pilihan dan boleh lebih daripada satu fail. Format dibenarkan: PDF, Word, Excel, JPG, JPEG, PNG.</div>
                <?php endif; ?>
            </div>
        </div>
        <div class="button-row">
            <button type="submit" class="primary-btn">Simpan Maklum Balas</button>
        </div>
    </form>
</div>
<?php render_layout_end(); ?>
