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

$auditId = (int) ($_POST['audit_id'] ?? 0);
$ringkasan = trim($_POST['ringkasan'] ?? '');
$maklumBalas = trim($_POST['maklum_balas'] ?? '');

if ($auditId <= 0) {
    header('Location: dashboard.php');
    exit();
}

$auditStmt = $conn->prepare("
    SELECT af.id, af.perkara, af.tarikh_mula, af.tarikh_akhir,
           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();
}

$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();
}

$assignedUnits = array_values(array_filter(array_map('trim', explode('||', (string) ($audit['assigned_units'] ?? '')))));
$currentUnit = current_user_unit();
$currentUserId = current_user_id();

$existingStmt = $conn->prepare("
    SELECT id, attachment_path, attachment_name, assigned_to_user_id, submitted_unit, status_tindakan
    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
");
$existingStmt->bind_param('isii', $auditId, $currentUnit, $currentUserId, $currentUserId);
$existingStmt->execute();
$existing = $existingStmt->get_result()->fetch_assoc();

$effectiveAssignedToUserId = (int) ($existing['assigned_to_user_id'] ?? 0);
if ($effectiveAssignedToUserId <= 0) {
    $effectiveAssignedToUserId = $currentUserId;
}
$effectiveStatusTindakan = trim((string) ($existing['status_tindakan'] ?? '')) !== ''
    ? (string) $existing['status_tindakan']
    : 'Perlu Tindakan';

$currentRole = current_user_role();

$relativePath = (string) ($existing['attachment_path'] ?? '');
$originalName = (string) ($existing['attachment_name'] ?? '');
$allowedExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'jpg', 'jpeg', 'png'];
$attachmentFiles = [];

if (isset($_FILES['attachment_file']) && is_array($_FILES['attachment_file']['name'] ?? null)) {
    foreach ($_FILES['attachment_file']['name'] as $index => $uploadedName) {
        $error = (int) ($_FILES['attachment_file']['error'][$index] ?? UPLOAD_ERR_NO_FILE);

        if ($error === UPLOAD_ERR_NO_FILE) {
            continue;
        }

        if ($error !== UPLOAD_ERR_OK) {
            header('Location: maklum_balas_audit.php?id=' . $auditId . '&error=upload_failed');
            exit();
        }

        $extension = strtolower(pathinfo((string) $uploadedName, PATHINFO_EXTENSION));
        if (!in_array($extension, $allowedExtensions, true)) {
            header('Location: maklum_balas_audit.php?id=' . $auditId . '&error=invalid_file');
            exit();
        }

        $attachmentFiles[] = [
            'name' => (string) $uploadedName,
            'tmp_name' => (string) ($_FILES['attachment_file']['tmp_name'][$index] ?? ''),
            'extension' => $extension,
        ];
    }
}

$hasUploadedFile = !empty($attachmentFiles);

if ($hasUploadedFile) {
    $originalName = $attachmentFiles[0]['name'];
}

$feedbackUnit = trim((string) ($existing['submitted_unit'] ?? $currentUnit));
$canCreateByAssignedUnit = in_array($currentUnit, $assignedUnits, true);

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

if ($existing && (int) ($existing['assigned_to_user_id'] ?? 0) > 0 && (int) ($existing['assigned_to_user_id'] ?? 0) !== $currentUserId && !in_array($currentUnit, $assignedUnits, true)) {
    header('Location: dashboard.php?error=feedback_assigned');
    exit();
}

if ($existing) {
    $updateStmt = $conn->prepare("
        UPDATE audit_feedbacks
        SET submitted_by = ?, submitted_unit = ?, submitted_role = ?, assigned_to_user_id = ?, status_tindakan = ?, ringkasan = ?, maklum_balas = ?, attachment_path = ?, attachment_name = ?
        WHERE id = ?
    ");
    $updateStmt->bind_param(
        'ississsssi',
        $currentUserId,
        $feedbackUnit,
        $currentRole,
        $effectiveAssignedToUserId,
        $effectiveStatusTindakan,
        $ringkasan,
        $maklumBalas,
        $relativePath,
        $originalName,
        $existing['id']
    );
    $updateStmt->execute();

    add_current_user_log($conn, 'Mengemaskini maklum balas audit: ' . ($audit['perkara'] ?? 'Tidak Diketahui'));
    if ($effectiveAssignedToUserId !== $currentUserId) {
        create_notification(
            $conn,
            $effectiveAssignedToUserId,
            'feedback_updated',
            'Maklum Balas Audit Perlu Dikemaskini',
            'Maklum balas audit "' . ($audit['perkara'] ?? 'Tidak Diketahui') . '" telah ditugaskan untuk anda kemas kini.',
            'maklum_balas_audit.php?id=' . $auditId
        );
    }
} else {
    $insertStmt = $conn->prepare("
        INSERT INTO audit_feedbacks (audit_form_id, submitted_by, submitted_unit, submitted_role, assigned_to_user_id, status_tindakan, ringkasan, maklum_balas, attachment_path, attachment_name)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $insertStmt->bind_param(
        'iississsss',
        $auditId,
        $currentUserId,
        $currentUnit,
        $currentRole,
        $effectiveAssignedToUserId,
        $effectiveStatusTindakan,
        $ringkasan,
        $maklumBalas,
        $relativePath,
        $originalName
    );
    $insertStmt->execute();
    $existing['id'] = (int) $conn->insert_id;

    add_current_user_log($conn, 'Mengisi maklum balas audit: ' . ($audit['perkara'] ?? 'Tidak Diketahui'));
    if ($effectiveAssignedToUserId !== $currentUserId) {
        create_notification(
            $conn,
            $effectiveAssignedToUserId,
            'feedback_assigned',
            'Maklum Balas Audit Diperlukan',
            'Anda telah ditugaskan untuk mengisi maklum balas audit "' . ($audit['perkara'] ?? 'Tidak Diketahui') . '".',
            'maklum_balas_audit.php?id=' . $auditId
        );
    }
}

if (!empty($attachmentFiles)) {
    $feedbackId = (int) ($existing['id'] ?? 0);
    $uploadDir = __DIR__ . '/uploads/maklum_balas';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    $attachmentStmt = $conn->prepare("
        INSERT INTO audit_feedback_attachments (audit_feedback_id, attachment_path, attachment_name)
        VALUES (?, ?, ?)
    ");

    foreach ($attachmentFiles as $index => $file) {
        $storedName = 'feedback_' . $auditId . '_' . current_user_id() . '_' . time() . '_' . ($index + 1) . '.' . $file['extension'];
        $targetPath = $uploadDir . '/' . $storedName;

        if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
            header('Location: maklum_balas_audit.php?id=' . $auditId . '&error=upload_failed');
            exit();
        }

        $relativeAttachmentPath = 'uploads/maklum_balas/' . $storedName;
        $attachmentName = $file['name'];
        $attachmentStmt->bind_param('iss', $feedbackId, $relativeAttachmentPath, $attachmentName);
        $attachmentStmt->execute();
    }
}

header('Location: dashboard.php?success=feedback_saved');
exit();
