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

$auditId = (int) ($_POST['audit_id'] ?? 0);
require_department_access($conn, 'senarai_maklumat_audit', $auditId > 0 ? 'update' : 'create');
$perkara = trim($_POST['perkara'] ?? '');
$tarikhMula = trim($_POST['tarikh_mula'] ?? '');
$tarikhAkhir = trim($_POST['tarikh_akhir'] ?? '');
$remarks = trim($_POST['remarks'] ?? '');
$assignTo = $_POST['assign_to'] ?? [];
$returnTo = $_POST['return_to'] ?? '';
$successRedirect = $returnTo === 'senarai_maklumat_audit'
    ? 'senarai_maklumat_audit.php?success=audit_saved'
    : 'dashboard.php?success=audit_saved';

$validAssignments = array_values(array_intersect(audit_bahagian_list(), is_array($assignTo) ? $assignTo : []));

$redirectForm = static function (int $auditId, string $error): string {
    return $auditId > 0
        ? 'daftar_maklumat_audit.php?id=' . $auditId . '&error=' . $error
        : 'daftar_maklumat_audit.php?error=' . $error;
};

if ($tarikhMula !== '' && $tarikhAkhir !== '' && $tarikhAkhir < $tarikhMula) {
    header('Location: ' . $redirectForm($auditId, 'invalid_dates'));
    exit();
}

$allowedExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'jpg', 'jpeg', 'png'];
$attachmentFiles = [];

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

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

        if ($error !== UPLOAD_ERR_OK) {
            header('Location: ' . $redirectForm($auditId, 'upload_failed'));
            exit();
        }

        $extension = strtolower(pathinfo((string) $originalName, PATHINFO_EXTENSION));
        if (!in_array($extension, $allowedExtensions, true)) {
            header('Location: ' . $redirectForm($auditId, 'invalid_file'));
            exit();
        }

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

if ($auditId > 0) {
    $stmt = $conn->prepare("UPDATE audit_forms SET perkara = ?, tarikh_mula = ?, tarikh_akhir = ?, remarks = ? WHERE id = ?");
    $stmt->bind_param('ssssi', $perkara, $tarikhMula, $tarikhAkhir, $remarks, $auditId);
    $stmt->execute();
    $conn->query("DELETE FROM audit_form_assignments WHERE audit_form_id = " . $auditId);
    $logAction = 'Mengemaskini maklumat audit: ' . $perkara;
} else {
    $createdBy = (int) $_SESSION['user_id'];
    $stmt = $conn->prepare("INSERT INTO audit_forms (perkara, tarikh_mula, tarikh_akhir, remarks, created_by) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param('ssssi', $perkara, $tarikhMula, $tarikhAkhir, $remarks, $createdBy);
    $stmt->execute();
    $auditId = (int) $conn->insert_id;
    $logAction = 'Mendaftar maklumat audit: ' . $perkara;
}

if (!empty($attachmentFiles)) {
    $uploadDir = __DIR__ . '/uploads/audit';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

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

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

        if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
            header('Location: ' . $redirectForm($auditId, 'upload_failed'));
            exit();
        }

        $relativePath = 'uploads/audit/' . $storedName;
        $attachmentName = $file['name'];
        $attachmentStmt->bind_param('iss', $auditId, $relativePath, $attachmentName);
        $attachmentStmt->execute();
    }
}

if (!empty($validAssignments)) {
    $assignStmt = $conn->prepare("INSERT INTO audit_form_assignments (audit_form_id, assigned_unit) VALUES (?, ?)");
    foreach ($validAssignments as $unit) {
        $assignStmt->bind_param('is', $auditId, $unit);
        $assignStmt->execute();
        create_notifications_for_unit(
            $conn,
            $unit,
            'audit_assigned',
            'Ada Perkara Baru Yang Perlu Diambil Tindakan oleh Bahagian Anda.',
            'Perkara audit "' . $perkara . '" memerlukan tindakan daripada bahagian anda.',
            'dashboard.php'
        );
    }
}

add_current_user_log($conn, $logAction);

header('Location: ' . $successRedirect);
exit();
