<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn);

$action = $_GET['action'] ?? '';
$user_department = currentUserDepartment($conn);

function parseIniSizeToBytes($value) {
    $value = trim((string) $value);
    if ($value === '') {
        return 0;
    }

    $unit = strtolower(substr($value, -1));
    $bytes = (float) $value;

    switch ($unit) {
        case 'g':
            $bytes *= 1024;
        case 'm':
            $bytes *= 1024;
        case 'k':
            $bytes *= 1024;
            break;
    }

    return (int) round($bytes);
}

function isPostBodyTooLarge() {
    if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
        return false;
    }

    $content_length = (int) ($_SERVER['CONTENT_LENGTH'] ?? 0);
    if ($content_length <= 0 || !empty($_POST) || !empty($_FILES)) {
        return false;
    }

    $max_post_size = parseIniSizeToBytes(ini_get('post_max_size'));
    return $max_post_size > 0 && $content_length > $max_post_size;
}

// PROSES TAMBAH DOKUMEN
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'add') {
    if (isPostBodyTooLarge()) {
        echo "<script>alert('Saiz muat naik melebihi had maksimum 40MB. Sila kecilkan lampiran atau pecahkan kepada beberapa fail.'); window.history.back();</script>";
        exit();
    }

    if (!hasUserPermission($conn, $_SESSION['user_id'], 'document', 'create', $user_department)) {
        echo "<script>alert('Anda tidak mempunyai kebenaran untuk mendaftar fail dalam bahagian ini!'); window.history.back();</script>";
        exit();
    }

    $folder_id_raw = $_POST['folder_id'] ?? '';
    $folder_id   = intval($folder_id_raw);
    $form_mode   = ($_POST['mode'] ?? '') === 'upload' ? 'upload' : 'add';
    $ref_no      = trim($_POST['ref_no'] ?? '');
    $subject     = trim($_POST['subject'] ?? '');
    $doc_date    = trim($_POST['doc_date'] ?? '');
    $from_person = trim($_POST['from_person'] ?? '');
    $to_person   = trim($_POST['to_person'] ?? '');
    $doc_type    = trim($_POST['doc_type'] ?? '');
    $uploaded_files = normalizeUploadedFiles('file_upload');

    if ($subject === '' || $doc_date === '' || $to_person === '' || $doc_type === '' || ($form_mode !== 'upload' && $from_person === '')) {
        echo "<script>alert('Sila lengkapkan semua maklumat dokumen yang wajib sebelum menyimpan.'); window.history.back();</script>";
        exit();
    }

    if ($form_mode === 'upload' && empty($uploaded_files)) {
        echo "<script>alert('Sila pilih sekurang-kurangnya satu fail surat untuk diupload.'); window.history.back();</script>";
        exit();
    }

    if ($folder_id <= 0) {
        if (isset($_SESSION['user_id'])) {
            logActivity($conn, $_SESSION['user_id'], 'create_document_failed',
                "Save document failed: invalid folder_id value [$folder_id_raw]");
        }
        header("Location: list_folder.php?error=invalid_folder_id&folder_id=0&source=process_document");
        exit();
    }

    if ($to_person === '' || ($form_mode !== 'upload' && $from_person === '')) {
        header("Location: add_documents.php?folder_id=$folder_id&mode=$form_mode&error=missing_department");
        exit();
    }

    if ($form_mode !== 'upload' && $from_person === $to_person) {
        if (isset($_SESSION['user_id'])) {
            logActivity($conn, $_SESSION['user_id'], 'create_document_failed',
                "From and to department are identical for folder_id: $folder_id");
        }
        echo "<script>alert('Pilihan Daripada dan Kepada tidak boleh sama!'); window.history.back();</script>";
        exit();
    }
    mysqli_begin_transaction($conn);

    try {
        $folder_stmt = mysqli_prepare($conn, "SELECT folder_code, folder_type, department, closed_at FROM folders WHERE id = ? AND deleted_at IS NULL FOR UPDATE");
        mysqli_stmt_bind_param($folder_stmt, "i", $folder_id);
        mysqli_stmt_execute($folder_stmt);
        $folder_row = mysqli_fetch_assoc(mysqli_stmt_get_result($folder_stmt));

        if (!$folder_row) {
            throw new Exception('folder_not_found');
        }

        if (!isSameDepartmentDb($conn, $folder_row['department'] ?? '', $user_department)) {
            throw new Exception('unauthorized_department');
        }

        if (!empty($folder_row['closed_at'])) {
            throw new Exception('folder_closed');
        }

        if ($form_mode === 'upload') {
            $folder_department = trim((string) ($folder_row['department'] ?? ''));
            $folder_positions = getDepartmentPositions($folder_department);
            $from_person = getMemoDepartmentHeadPosition($folder_department);
            if ($from_person === '' && !empty($folder_positions)) {
                $from_person = getDisplayPositionForDepartment($folder_department, $folder_positions[0]);
            }

            $valid_upload_positions = [];
            foreach (getMemoPositionOptions() as $positions) {
                foreach ($positions as $position) {
                    $valid_upload_positions[$position] = true;
                }
            }

            if (!isset($valid_upload_positions[$to_person])) {
                throw new Exception('invalid_position');
            }
        }

        if ($from_person === '' || $to_person === '') {
            throw new Exception('missing_department');
        }

        if ($from_person === $to_person) {
            throw new Exception('same_department');
        }

        $folder_code = trim($folder_row['folder_code'] ?? '');
        $folder_type = strtolower(trim($folder_row['folder_type'] ?? 'office'));

        if ($folder_type === 'sendirian') {
            if ($ref_no === '') {
                throw new Exception('missing_ref_no');
            }
        } else {
            $ref_no = generateNextDocumentReference($folder_code);
        }

        $file_numbering = generateNextDocumentFileNumbering($conn, $folder_id);

        if ($folder_type === 'sendirian') {
            $ref_conflict_stmt = mysqli_prepare($conn, "SELECT id FROM documents WHERE folder_id = ? AND ref_no = ? AND deleted_at IS NULL LIMIT 1");
            mysqli_stmt_bind_param($ref_conflict_stmt, "is", $folder_id, $ref_no);
        } else {
            $ref_conflict_stmt = mysqli_prepare($conn, "SELECT id FROM documents WHERE folder_id = ? AND ref_no = ? AND file_numbering = ? AND deleted_at IS NULL LIMIT 1");
            mysqli_stmt_bind_param($ref_conflict_stmt, "iss", $folder_id, $ref_no, $file_numbering);
        }
        mysqli_stmt_execute($ref_conflict_stmt);
        if (mysqli_num_rows(mysqli_stmt_get_result($ref_conflict_stmt)) > 0) {
            throw new Exception('duplicate_ref_no');
        }

        $file_path = null;
        $insert = mysqli_prepare($conn, "INSERT INTO documents (folder_id, ref_no, file_numbering, subject, doc_date, from_person, to_person, doc_type, file_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        mysqli_stmt_bind_param($insert, "issssssss", $folder_id, $ref_no, $file_numbering, $subject, $doc_date, $from_person, $to_person, $doc_type, $file_path);

        if (!mysqli_stmt_execute($insert)) {
            throw new Exception(mysqli_error($conn));
        }

        $doc_id = mysqli_insert_id($conn);
        $attachment_result = saveDocumentAttachments($conn, $doc_id, $folder_id, $uploaded_files);
        if (!empty($attachment_result['first_path'])) {
            $file_path = $attachment_result['first_path'];
            $update_primary_file = mysqli_prepare($conn, "UPDATE documents SET file_path = ? WHERE id = ?");
            mysqli_stmt_bind_param($update_primary_file, "si", $file_path, $doc_id);
            mysqli_stmt_execute($update_primary_file);
        }
        saveCustomData($conn, 'document', $doc_id);
        mysqli_commit($conn);

        if (isset($_SESSION['user_id'])) {
            $attachment_count = (int) ($attachment_result['count'] ?? 0);
            $file_info = $attachment_count > 0 ? " | Attachment: {$attachment_count} fail" : " | No attachment";
            logActivity($conn, $_SESSION['user_id'], 'create_document',
                "Create document: $ref_no - $subject (Fail: $folder_id)$file_info");
        }

        header("Location: view_folder.php?id=$folder_id&success=document_added");
        exit();
    } catch (Exception $e) {
        mysqli_rollback($conn);

        if ($e->getMessage() === 'folder_not_found') {
            if (isset($_SESSION['user_id'])) {
                logActivity($conn, $_SESSION['user_id'], 'create_document_failed',
                    "Save document failed: folder_id $folder_id not found during submit");
            }
            header("Location: list_folder.php?error=folder_not_found&folder_id=$folder_id&source=process_document");
            exit();
        }
        if ($e->getMessage() === 'folder_closed') {
            echo "<script>alert('Fail ini telah ditutup. Dokumen baru tidak boleh ditambah.'); window.location='view_folder.php?id=$folder_id';</script>";
            exit();
        }

        if ($e->getMessage() === 'unauthorized_department') {
            echo "<script>alert('Anda tidak boleh mendaftar dokumen pada fail bahagian lain.'); window.location='list_folder.php';</script>";
            exit();
        }

        if ($e->getMessage() === 'missing_department') {
            header("Location: add_documents.php?folder_id=$folder_id&mode=$form_mode&error=missing_department");
            exit();
        }

        if ($e->getMessage() === 'same_department') {
            echo "<script>alert('Pilihan Daripada dan Kepada tidak boleh sama!'); window.history.back();</script>";
            exit();
        }

        if ($e->getMessage() === 'invalid_position') {
            header("Location: add_documents.php?folder_id=$folder_id&mode=$form_mode&error=invalid_position");
            exit();
        }

        if ($e->getMessage() === 'missing_ref_no') {
            header("Location: add_documents.php?folder_id=$folder_id&mode=$form_mode&error=missing_ref_no");
            exit();
        }

        if ($e->getMessage() === 'duplicate_ref_no') {
            header("Location: add_documents.php?folder_id=$folder_id&mode=$form_mode&error=duplicate_ref_no");
            exit();
        }

        if (isset($_SESSION['user_id'])) {
            logActivity($conn, $_SESSION['user_id'], 'create_document_failed',
                "System error creating document in fail $folder_id: " . $e->getMessage());
        }

        header("Location: add_documents.php?folder_id=$folder_id&error=system&msg=" . urlencode($e->getMessage()));
        exit();
    }
}

// PROSES PADAM DOKUMEN
elseif ($action === 'delete' && isset($_GET['id'], $_GET['folder_id'])) {

    $doc_id = intval($_GET['id']);
    $folder_id = intval($_GET['folder_id']);

    if (!hasUserPermission($conn, $_SESSION['user_id'], 'document', 'delete', $user_department)) {
        if (isset($_SESSION['user_id'])) {
            logActivity($conn, $_SESSION['user_id'], 'delete_document_unauthorized',
                "Unauthorized attempt to delete document ID: $doc_id");
        }
        echo "<script>alert('Anda tidak mempunyai kebenaran untuk memadam fail dalam bahagian ini!'); window.history.back();</script>";
        exit();
    }

    $doc_info = mysqli_prepare($conn, "SELECT d.ref_no, d.subject, d.file_path, f.department
        FROM documents d
        LEFT JOIN folders f ON f.id = d.folder_id
        WHERE d.id = ? AND d.deleted_at IS NULL");
    mysqli_stmt_bind_param($doc_info, "i", $doc_id);
    mysqli_stmt_execute($doc_info);
    $doc_data = mysqli_fetch_assoc(mysqli_stmt_get_result($doc_info));

    if ($doc_data) {
        if (!isSameDepartmentDb($conn, $doc_data['department'] ?? '', $user_department)) {
            echo "<script>alert('Anda tidak boleh memadam dokumen bahagian lain.'); window.location='list_folder.php';</script>";
            exit();
        }

        $ref_no = $doc_data['ref_no'];
        $subject = $doc_data['subject'];
        $current_user_id = (int) ($_SESSION['user_id'] ?? 0);

        mysqli_begin_transaction($conn);
        try {
            $delete = mysqli_prepare($conn, "UPDATE documents SET deleted_at = NOW(), deleted_by = ? WHERE id = ? AND deleted_at IS NULL");
            mysqli_stmt_bind_param($delete, "ii", $current_user_id, $doc_id);
            if (!mysqli_stmt_execute($delete)) {
                throw new Exception(mysqli_error($conn));
            }

            $delete_draft = mysqli_prepare($conn, "UPDATE letter_drafts SET deleted_at = NOW(), deleted_by = ? WHERE document_id = ? AND deleted_at IS NULL");
            if ($delete_draft) {
                mysqli_stmt_bind_param($delete_draft, "ii", $current_user_id, $doc_id);
                if (!mysqli_stmt_execute($delete_draft)) {
                    throw new Exception(mysqli_error($conn));
                }
            }

            $delete_log = mysqli_prepare($conn, "INSERT INTO document_delete_log (document_id, document_subject, deleted_by, deleted_at, reason) VALUES (?, ?, ?, NOW(), ?)");
            if ($delete_log) {
                $delete_reason = 'Dipadam dari Pengurusan Fail';
                mysqli_stmt_bind_param($delete_log, "isis", $doc_id, $subject, $current_user_id, $delete_reason);
                mysqli_stmt_execute($delete_log);
            }

            mysqli_commit($conn);
            if (isset($_SESSION['user_id'])) {
                logActivity($conn, $_SESSION['user_id'], 'delete_document',
                    "Delete document and linked draft if any: $ref_no - $subject (ID: $doc_id)");
            }
            header("Location: view_folder.php?id=$folder_id&success=document_deleted");
            exit();
        } catch (Exception $e) {
            mysqli_rollback($conn);
            if (isset($_SESSION['user_id'])) {
                logActivity($conn, $_SESSION['user_id'], 'delete_document_failed',
                    "Failed to delete document ID $doc_id: " . $e->getMessage());
            }
            header("Location: view_folder.php?id=$folder_id&error=delete_failed");
            exit();
        }
    } else {
        if (isset($_SESSION['user_id'])) {
            logActivity($conn, $_SESSION['user_id'], 'delete_document_failed',
                "Document ID $doc_id not found for deletion");
        }
        header("Location: view_folder.php?id=$folder_id&error=not_found");
        exit();
    }
}

// PADAM ATTACHMENT DOKUMEN
elseif ($action === 'delete_attachment' && isset($_GET['id'], $_GET['folder_id'], $_GET['attachment_id'])) {

    $doc_id = intval($_GET['id']);
    $folder_id = intval($_GET['folder_id']);
    $attachment_id = intval($_GET['attachment_id']);

    if (!hasUserPermission($conn, $_SESSION['user_id'], 'document', 'update', $user_department)) {
        echo "<script>alert('Anda tidak mempunyai kebenaran untuk memadam attachment dokumen ini!'); window.history.back();</script>";
        exit();
    }

    $attachment_stmt = mysqli_prepare($conn, "SELECT a.id, a.file_path, a.original_name, d.ref_no, d.subject
        , f.department
        FROM document_attachments a
        INNER JOIN documents d ON a.document_id = d.id
        LEFT JOIN folders f ON f.id = d.folder_id
        WHERE a.id = ? AND d.id = ? AND d.folder_id = ? AND d.deleted_at IS NULL");
    mysqli_stmt_bind_param($attachment_stmt, "iii", $attachment_id, $doc_id, $folder_id);
    mysqli_stmt_execute($attachment_stmt);
    $attachment = mysqli_fetch_assoc(mysqli_stmt_get_result($attachment_stmt));

    if (!$attachment) {
        header("Location: edit_document.php?id=$doc_id&folder_id=$folder_id&error=attachment_not_found");
        exit();
    }

    if (!isSameDepartmentDb($conn, $attachment['department'] ?? '', $user_department)) {
        echo "<script>alert('Anda tidak boleh memadam attachment bahagian lain.'); window.location='list_folder.php';</script>";
        exit();
    }

    mysqli_begin_transaction($conn);

    try {
        $delete_stmt = mysqli_prepare($conn, "DELETE FROM document_attachments WHERE id = ?");
        mysqli_stmt_bind_param($delete_stmt, "i", $attachment_id);
        if (!mysqli_stmt_execute($delete_stmt)) {
            throw new Exception('Gagal memadam attachment.');
        }

        if (!syncDocumentPrimaryFilePath($conn, $doc_id)) {
            throw new Exception('Gagal mengemaskini attachment utama.');
        }

        mysqli_commit($conn);

        $file_path = $attachment['file_path'] ?? '';
        if ($file_path !== '' && file_exists($file_path)) {
            unlink($file_path);
        }

        if (isset($_SESSION['user_id'])) {
            $attachment_name = $attachment['original_name'] ?: basename($file_path);
            logActivity($conn, $_SESSION['user_id'], 'delete_document_attachment',
                "Delete attachment: {$attachment_name} for document {$attachment['ref_no']} - {$attachment['subject']} (ID: $doc_id)");
        }

        header("Location: edit_document.php?id=$doc_id&folder_id=$folder_id&success=attachment_deleted");
        exit();
    } catch (Exception $e) {
        mysqli_rollback($conn);
        header("Location: edit_document.php?id=$doc_id&folder_id=$folder_id&error=attachment_delete_failed");
        exit();
    }
}

// PROSES PULIHKAN DOKUMEN
elseif ($action === 'restore' && isset($_GET['id'])) {

    if (!currentUserCan($conn, 'deleted_item', 'restore')) {
        echo "<script>alert('Anda tidak mempunyai kebenaran untuk memulihkan data dipadam.'); window.history.back();</script>";
        exit();
    }

    $doc_id = intval($_GET['id']);

    $doc_info = mysqli_prepare($conn, "SELECT d.id, d.folder_id, d.ref_no, d.subject, f.id AS folder_exists, f.deleted_at AS folder_deleted_at, f.department
        FROM documents d
        LEFT JOIN folders f ON d.folder_id = f.id
        WHERE d.id = ? AND d.deleted_at IS NOT NULL");
    mysqli_stmt_bind_param($doc_info, "i", $doc_id);
    mysqli_stmt_execute($doc_info);
    $doc_data = mysqli_fetch_assoc(mysqli_stmt_get_result($doc_info));

    if (!$doc_data) {
        header("Location: deleted_items.php?error=document_not_found");
        exit();
    }

    if (($_SESSION['role'] ?? 'user') !== 'superadmin' && !isSameDepartmentDb($conn, $doc_data['department'] ?? '', $user_department)) {
        header("Location: deleted_items.php?error=restore_failed");
        exit();
    }

    if (empty($doc_data['folder_exists'])) {
        header("Location: deleted_items.php?error=folder_missing");
        exit();
    }

    if (!empty($doc_data['folder_deleted_at'])) {
        header("Location: deleted_items.php?error=restore_folder_first");
        exit();
    }

    $conflict = mysqli_prepare($conn, "SELECT id FROM documents WHERE folder_id = ? AND ref_no = ? AND deleted_at IS NULL LIMIT 1");
    mysqli_stmt_bind_param($conflict, "is", $doc_data['folder_id'], $doc_data['ref_no']);
    mysqli_stmt_execute($conflict);
    $conflict_row = mysqli_fetch_assoc(mysqli_stmt_get_result($conflict));

    if ($conflict_row) {
        header("Location: deleted_items.php?error=duplicate_ref_conflict");
        exit();
    }

    mysqli_begin_transaction($conn);
    try {
        $restore = mysqli_prepare($conn, "UPDATE documents SET deleted_at = NULL, deleted_by = NULL WHERE id = ? AND deleted_at IS NOT NULL");
        mysqli_stmt_bind_param($restore, "i", $doc_id);
        if (!mysqli_stmt_execute($restore)) {
            throw new Exception(mysqli_error($conn));
        }

        $restore_draft = mysqli_prepare($conn, "UPDATE letter_drafts SET deleted_at = NULL, deleted_by = NULL WHERE document_id = ? AND deleted_at IS NOT NULL");
        if ($restore_draft) {
            mysqli_stmt_bind_param($restore_draft, "i", $doc_id);
            if (!mysqli_stmt_execute($restore_draft)) {
                throw new Exception(mysqli_error($conn));
            }
        }

        mysqli_commit($conn);
        logActivity(
            $conn,
            (int) ($_SESSION['user_id'] ?? 0),
            'restore_document',
            'Pulihkan dokumen: ' . ($doc_data['ref_no'] ?? '') . ' - ' . ($doc_data['subject'] ?? '') . ' (ID: ' . $doc_id . ')'
        );
        header("Location: deleted_items.php?success=document_restored");
        exit();
    } catch (Exception $e) {
        mysqli_rollback($conn);
    }

    header("Location: deleted_items.php?error=restore_failed");
    exit();
}

header("Location: dashboard.php");
exit();
?>

