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

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

if ($action === 'add' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hasUserPermission($conn, $_SESSION['user_id'], 'folder', 'create', $user_department)) {
        echo "<script>alert('Anda tidak mempunyai kebenaran untuk menambah fail dalam bahagian ini!'); window.history.back();</script>";
        exit();
    }

    $code = trim($_POST['folder_code'] ?? '');
    $name = trim($_POST['folder_name'] ?? '');
    $department = trim($_POST['department'] ?? '');
    $folder_type = strtolower(trim($_POST['folder_type'] ?? ''));
    $file_number_start = (int) ($_POST['file_number_start'] ?? 1);
    $allowed_folder_types = getFolderTypeList();

    if (empty($department)) {
        echo "<script>alert('Sila pilih Bahagian/Unit!'); window.history.back();</script>";
        exit();
    }

    if (!in_array($folder_type, $allowed_folder_types, true)) {
        echo "<script>alert('Sila pilih jenis fail yang sah!'); window.history.back();</script>";
        exit();
    }

    if ($file_number_start < 1) {
        echo "<script>alert('No. rujukan mula mesti bermula dari nombor 1 atau lebih.'); window.history.back();</script>";
        exit();
    }

    if ($folder_type === 'office') {
        if (!isValidOfficeFolderCode($code)) {
            echo "<script>alert('Kod fail office mesti ikut format rasmi, contoh: MAINPP/BTM.500-6/2/1 atau MAINPP/BTM.500-6/2/1 Jld.2'); window.history.back();</script>";
            exit();
        }

        // Prevent Jld.1 - first JLD must start from Jld.2
        if (preg_match('/\s+Jld\.1$/i', $code)) {
            echo "<script>alert('Jilid pertama tidak boleh menggunakan Jld.1. Sila guna kod asas tanpa Jld atau mulakan dari Jld.2.'); window.history.back();</script>";
            exit();
        }

        $jilid_info = getOfficeFolderJilidInfo($conn, $code);

        if ($jilid_info['status'] === 'active') {
            echo "<script>alert(" . json_encode($jilid_info['message']) . "); window.history.back();</script>";
            exit();
        }

        if ($jilid_info['status'] === 'suggested' && !empty($jilid_info['suggested_code'])) {
            $code = $jilid_info['suggested_code'];
        }

        if (!empty($jilid_info['has_official_name']) && !empty($jilid_info['official_name'])) {
            $name = $jilid_info['official_name'];
        }
    }

    $check = mysqli_prepare($conn, "SELECT id FROM folders WHERE folder_code = ?");
    mysqli_stmt_bind_param($check, "s", $code);
    mysqli_stmt_execute($check);
    mysqli_stmt_store_result($check);

    if (mysqli_stmt_num_rows($check) > 0) {
        if (isset($_SESSION['user_id'])) {
            logActivity($conn, $_SESSION['user_id'], 'create_folder_failed', "Attempt create duplicate fail code: $code");
        }
        echo "<script>alert('Kod fail ini ($code) sudah wujud dalam sistem!'); window.history.back();</script>";
        exit();
    }

    if (!isSameDepartmentDb($conn, $department, $user_department)) {
        echo "<script>alert('Anda tidak boleh menambah fail untuk bahagian lain.'); window.history.back();</script>";
        exit();
    }

    $insert = mysqli_prepare($conn, "INSERT INTO folders (folder_code, folder_name, department, folder_type, file_number_start, custom_data, created_at) VALUES (?, ?, ?, ?, ?, NULL, NOW())");
    mysqli_stmt_bind_param($insert, "ssssi", $code, $name, $department, $folder_type, $file_number_start);

    try {
        if (mysqli_stmt_execute($insert)) {
            $new_folder_id = mysqli_insert_id($conn);
            saveCustomData($conn, 'folder', $new_folder_id);

            if (isset($_SESSION['user_id'])) {
                logActivity($conn, $_SESSION['user_id'], 'create_folder', "Create folder: $code - $name (Bahagian: $department, Jenis: $folder_type, No rujukan mula: $file_number_start)");
            }

            echo "<script>alert('Fail berjaya didaftarkan!'); window.location='list_folder.php';</script>";
        } else {
            if (isset($_SESSION['user_id'])) {
                logActivity($conn, $_SESSION['user_id'], 'create_folder_failed', "Failed to create folder: $code - " . mysqli_error($conn));
            }

            echo "<script>alert('Ralat: " . mysqli_error($conn) . "'); window.history.back();</script>";
        }
    } catch (mysqli_sql_exception $e) {
        if (isset($_SESSION['user_id'])) {
            logActivity($conn, $_SESSION['user_id'], 'create_folder_failed', "Failed to create folder: $code - " . $e->getMessage());
        }
        echo "<script>alert('Kod fail (" . htmlspecialchars($code) . ") sudah wujud dalam sistem!'); window.history.back();</script>";
        exit();
    }
}
elseif ($action === 'delete' && isset($_GET['id'])) {
    $id = intval($_GET['id']);

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

    $check = mysqli_prepare($conn, "SELECT COUNT(*) as total FROM documents WHERE folder_id = ? AND deleted_at IS NULL");
    mysqli_stmt_bind_param($check, "i", $id);
    mysqli_stmt_execute($check);
    $result = mysqli_stmt_get_result($check);
    $row = mysqli_fetch_assoc($result);

    if (($row['total'] ?? 0) > 0) {
        if (isset($_SESSION['user_id'])) {
            logActivity($conn, $_SESSION['user_id'], 'delete_folder_blocked', "Delete blocked - fail ID $id still has {$row['total']} documents");
        }
        echo "<script>alert('Fail TIDAK boleh dipadam kerana masih mempunyai {$row['total']} fail di dalamnya.\\n\\nSila pindahkan atau padam fail dahulu.'); window.location='list_folder.php';</script>";
        exit();
    }

    $folder_info = mysqli_prepare($conn, "SELECT folder_code, folder_name, department FROM folders WHERE id = ? AND deleted_at IS NULL");
    mysqli_stmt_bind_param($folder_info, "i", $id);
    mysqli_stmt_execute($folder_info);
    $folder_data = mysqli_fetch_assoc(mysqli_stmt_get_result($folder_info));

    if (!$folder_data) {
        echo "<script>alert('Fail tidak dijumpai atau telah dipadam.'); window.location='list_folder.php';</script>";
        exit();
    }

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

    $folder_code = $folder_data['folder_code'] ?? 'Unknown';
    $folder_name = $folder_data['folder_name'] ?? 'Unknown';
    $deleted_by = $_SESSION['user_id'] ?? null;

    $delete = mysqli_prepare($conn, "UPDATE folders SET deleted_at = NOW(), deleted_by = ? WHERE id = ? AND deleted_at IS NULL");
    mysqli_stmt_bind_param($delete, "ii", $deleted_by, $id);

    if (mysqli_stmt_execute($delete)) {
        if ($deleted_by) {
            $log_sql = "INSERT INTO folder_delete_log (folder_id, folder_name, deleted_by, deleted_at) VALUES (?, ?, ?, NOW())";
            $log_stmt = mysqli_prepare($conn, $log_sql);
            mysqli_stmt_bind_param($log_stmt, "isi", $id, $folder_name, $deleted_by);
            mysqli_stmt_execute($log_stmt);
        }
        if (isset($_SESSION['user_id'])) {
            logActivity($conn, $_SESSION['user_id'], 'delete_folder', "Delete folder: $folder_code - $folder_name (ID: $id)");
        }
        echo "<script>alert('Fail berjaya dipadam!'); window.location='list_folder.php';</script>";
    } else {
        if (isset($_SESSION['user_id'])) {
            logActivity($conn, $_SESSION['user_id'], 'delete_folder_failed', "Failed to delete fail ID $id: " . mysqli_error($conn));
        }
        echo "<script>alert('Ralat memadam fail.'); window.history.back();</script>";
    }
}
elseif ($action === 'close' && isset($_GET['id'])) {
    $id = intval($_GET['id']);

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

    $folder_info = mysqli_prepare($conn, "SELECT folder_code, folder_name, department, closed_at FROM folders WHERE id = ? AND deleted_at IS NULL");
    mysqli_stmt_bind_param($folder_info, "i", $id);
    mysqli_stmt_execute($folder_info);
    $folder_data = mysqli_fetch_assoc(mysqli_stmt_get_result($folder_info));

    if (!$folder_data) {
        echo "<script>alert('Fail tidak dijumpai atau telah dipadam.'); window.location='list_folder.php';</script>";
        exit();
    }

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

    if (!empty($folder_data['closed_at'])) {
        echo "<script>alert('Fail ini telah ditutup sebelum ini.'); window.location='list_folder.php';</script>";
        exit();
    }

    $closed_by = $_SESSION['user_id'] ?? null;
    $close_stmt = mysqli_prepare($conn, "UPDATE folders SET closed_at = NOW(), closed_by = ? WHERE id = ? AND deleted_at IS NULL AND closed_at IS NULL");
    mysqli_stmt_bind_param($close_stmt, "ii", $closed_by, $id);

    if (mysqli_stmt_execute($close_stmt)) {
        if (isset($_SESSION['user_id'])) {
            logActivity($conn, $_SESSION['user_id'], 'close_folder', "Close folder: {$folder_data['folder_code']} - {$folder_data['folder_name']} (ID: $id)");
        }
        echo "<script>alert('Fail berjaya ditutup!'); window.location='list_folder.php';</script>";
    } else {
        if (isset($_SESSION['user_id'])) {
            logActivity($conn, $_SESSION['user_id'], 'close_folder_failed', "Failed to close fail ID $id: " . mysqli_error($conn));
        }
        echo "<script>alert('Ralat menutup fail.'); window.history.back();</script>";
    }
}
elseif ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = intval($_POST['folder_id'] ?? 0);

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

    $code = trim($_POST['folder_code'] ?? '');
    $name = trim($_POST['folder_name'] ?? '');
    $department = trim($_POST['department'] ?? '');
    $folder_type = strtolower(trim($_POST['folder_type'] ?? ''));
    $allowed_folder_types = getFolderTypeList();

    if (empty($department)) {
        echo "<script>alert('Sila pilih Bahagian/Unit!'); window.history.back();</script>";
        exit();
    }

    $current_folder_stmt = mysqli_prepare($conn, "SELECT department FROM folders WHERE id = ? AND deleted_at IS NULL");
    mysqli_stmt_bind_param($current_folder_stmt, "i", $id);
    mysqli_stmt_execute($current_folder_stmt);
    $current_folder = mysqli_fetch_assoc(mysqli_stmt_get_result($current_folder_stmt));

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

    if (!isSameDepartmentDb($conn, $department, $user_department)) {
        echo "<script>alert('Anda tidak boleh memindahkan fail ke bahagian lain.'); window.history.back();</script>";
        exit();
    }

    if (!in_array($folder_type, $allowed_folder_types, true)) {
        echo "<script>alert('Sila pilih jenis fail yang sah!'); window.history.back();</script>";
        exit();
    }

    if ($folder_type === 'office' && !isValidOfficeFolderCode($code)) {
        echo "<script>alert('Kod fail untuk jenis office mesti ikut format rasmi, contoh: MAINPP/BTM.500-6/2/1 atau MAINPP/BTM.500-6/2/1 JLD.2'); window.history.back();</script>";
        exit();
    }

    $old_info = mysqli_prepare($conn, "SELECT folder_code, folder_name, department, folder_type FROM folders WHERE id = ? AND deleted_at IS NULL");
    mysqli_stmt_bind_param($old_info, "i", $id);
    mysqli_stmt_execute($old_info);
    $old_data = mysqli_fetch_assoc(mysqli_stmt_get_result($old_info));

    $update = mysqli_prepare($conn, "UPDATE folders SET folder_code = ?, folder_name = ?, department = ?, folder_type = ? WHERE id = ? AND deleted_at IS NULL");
    mysqli_stmt_bind_param($update, "ssssi", $code, $name, $department, $folder_type, $id);

    if (mysqli_stmt_execute($update)) {
        saveCustomData($conn, 'folder', $id);

        if (isset($_SESSION['user_id'])) {
            $changes = [];
            if ($old_data && $old_data['folder_code'] !== $code) $changes[] = "code: {$old_data['folder_code']} -> $code";
            if ($old_data && $old_data['folder_name'] !== $name) $changes[] = "name: {$old_data['folder_name']} -> $name";
            if ($old_data && $old_data['department'] !== $department) $changes[] = "dept: {$old_data['department']} -> $department";
            if ($old_data && ($old_data['folder_type'] ?? '') !== $folder_type) $changes[] = "type: " . ($old_data['folder_type'] ?: '-') . " -> $folder_type";
            $change_desc = implode(', ', $changes) ?: 'minor updates';

            logActivity($conn, $_SESSION['user_id'], 'update_folder', "Update fail ID $id: $change_desc");
        }

        echo "<script>alert('Fail berjaya dikemaskini!'); window.location='list_folder.php';</script>";
    } else {
        if (isset($_SESSION['user_id'])) {
            logActivity($conn, $_SESSION['user_id'], 'update_folder_failed', "Failed to update fail ID $id: " . mysqli_error($conn));
        }
        echo "<script>alert('Ralat mengemaskini fail.'); window.history.back();</script>";
    }
}
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();
    }

    $id = intval($_GET['id']);
    $folder_info = mysqli_prepare($conn, "SELECT folder_code, folder_name, department FROM folders WHERE id = ? AND deleted_at IS NOT NULL");
    mysqli_stmt_bind_param($folder_info, "i", $id);
    mysqli_stmt_execute($folder_info);
    $folder_data = mysqli_fetch_assoc(mysqli_stmt_get_result($folder_info));

    if (!$folder_data) {
        echo "<script>alert('Fail dipadam tidak dijumpai.'); window.location='deleted_items.php?error=restore_failed';</script>";
        exit();
    }

    if ($role !== 'superadmin' && !isSameDepartmentDb($conn, $folder_data['department'] ?? '', $user_department)) {
        echo "<script>alert('Anda tidak mempunyai kebenaran untuk memulihkan fail bahagian lain.'); window.location='deleted_items.php?error=restore_failed';</script>";
        exit();
    }

    $restore = mysqli_prepare($conn, "UPDATE folders SET deleted_at = NULL, deleted_by = NULL WHERE id = ? AND deleted_at IS NOT NULL");
    mysqli_stmt_bind_param($restore, "i", $id);

    if (mysqli_stmt_execute($restore)) {
        logActivity(
            $conn,
            (int) ($_SESSION['user_id'] ?? 0),
            'restore_folder',
            'Pulihkan fail: ' . ($folder_data['folder_code'] ?? '') . ' - ' . ($folder_data['folder_name'] ?? '') . ' (ID: ' . $id . ')'
        );
        echo "<script>alert('Fail berjaya dipulihkan!'); window.location='deleted_items.php?success=folder_restored';</script>";
    } else {
        echo "<script>alert('Gagal memulihkan fail.'); window.location='deleted_items.php?error=restore_failed';</script>";
    }
    exit();
}

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

