<?php
session_start();
require_once "config/database.php";

if (!isset($_SESSION['user_id']) || !isset($_SESSION['role'])) {
    header("Location: login.php");
    exit;
}

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.");
}

$user_id = (int)($_SESSION['user_id'] ?? 0);
$full_name = trim($_SESSION['full_name'] ?? 'User');

$workspace = $_GET['workspace'] ?? 'personal';
$scope = $_GET['scope'] ?? $workspace;
$folder_id = (int)($_GET['id'] ?? 0);
$requested_company_id = (int)($_GET['company_id'] ?? 0);

$active_company_id = null;
$company_name = '';
$hasCompanyWorkspace = false;
$message = '';
$error = '';

const MAX_UPLOAD_BYTES = 20971520; // 20 MB
const UPLOAD_DIR_RELATIVE = 'uploads/documents/';

function bytesToHuman(int $bytes): string
{
    if ($bytes >= 1048576) {
        return round($bytes / 1048576, 2) . ' MB';
    }

    if ($bytes >= 1024) {
        return round($bytes / 1024, 2) . ' KB';
    }

    return $bytes . ' bytes';
}

function getPhpUploadLimitBytes(): int
{
    $uploadMax = parseSizeToBytes((string)ini_get('upload_max_filesize'));
    $postMax = parseSizeToBytes((string)ini_get('post_max_size'));

    if ($uploadMax <= 0) return $postMax;
    if ($postMax <= 0) return $uploadMax;

    return min($uploadMax, $postMax);
}

function parseSizeToBytes(string $size): int
{
    $size = trim($size);
    if ($size === '') return 0;

    $unit = strtolower(substr($size, -1));
    $number = (float)$size;

    switch ($unit) {
        case 'g':
            return (int)($number * 1024 * 1024 * 1024);
        case 'm':
            return (int)($number * 1024 * 1024);
        case 'k':
            return (int)($number * 1024);
        default:
            return (int)$number;
    }
}

function getUploadErrorMessage(array $file): string
{
    $errorCode = (int)($file['error'] ?? UPLOAD_ERR_NO_FILE);

    switch ($errorCode) {
        case UPLOAD_ERR_OK:
            return '';
        case UPLOAD_ERR_INI_SIZE:
            return 'The file is larger than the server upload limit. Please increase upload_max_filesize and post_max_size in your hosting PHP settings.';
        case UPLOAD_ERR_FORM_SIZE:
            return 'The file is larger than this page allows. Maximum allowed file size is ' . bytesToHuman(MAX_UPLOAD_BYTES) . '.';
        case UPLOAD_ERR_PARTIAL:
            return 'The file was only partially uploaded. Please try again with a stable internet connection.';
        case UPLOAD_ERR_NO_FILE:
            return 'Please choose a file to upload.';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'Server upload temporary folder is missing. Please contact your hosting provider.';
        case UPLOAD_ERR_CANT_WRITE:
            return 'Server could not write the uploaded file. Please check folder permissions or contact your hosting provider.';
        case UPLOAD_ERR_EXTENSION:
            return 'A server PHP extension stopped the upload. Please contact your hosting provider.';
        default:
            return 'Upload failed. Error code: ' . $errorCode;
    }
}

function isAllowedDocumentFile(array $file): bool
{
    $originalFileName = (string)($file['name'] ?? '');
    $extension = strtolower(pathinfo($originalFileName, PATHINFO_EXTENSION));

    $allowedExtensions = [
        'pdf', 'jpg', 'jpeg', 'png', 'webp',
        'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx',
        'txt', 'csv'
    ];

    return in_array($extension, $allowedExtensions, true);
}

function ensureCustomFieldTables(PDO $db): void
{
    $db->exec("
        CREATE TABLE IF NOT EXISTS document_custom_fields (
            id INT AUTO_INCREMENT PRIMARY KEY,
            folder_id INT NOT NULL,
            field_name VARCHAR(255) NOT NULL,
            field_type VARCHAR(50) DEFAULT 'text',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_folder_id (folder_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    $db->exec("
        CREATE TABLE IF NOT EXISTS document_custom_values (
            id INT AUTO_INCREMENT PRIMARY KEY,
            document_id INT NOT NULL,
            field_id INT NOT NULL,
            field_value TEXT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY unique_document_field (document_id, field_id),
            INDEX idx_document_id (document_id),
            INDEX idx_field_id (field_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    $db->exec("
        CREATE TABLE IF NOT EXISTS document_default_field_labels (
            id INT AUTO_INCREMENT PRIMARY KEY,
            folder_id INT NOT NULL,
            field_key VARCHAR(100) NOT NULL,
            field_label VARCHAR(255) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY unique_folder_field_key (folder_id, field_key),
            INDEX idx_folder_id (folder_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
}

function convertToSqlDate(?string $date): ?string
{
    $date = trim((string)$date);
    if ($date === '') return null;

    $dt = DateTime::createFromFormat('d/m/Y', $date);
    if ($dt && $dt->format('d/m/Y') === $date) {
        return $dt->format('Y-m-d');
    }

    return null;
}

function formatDateForInput(?string $date): string
{
    $date = trim((string)$date);
    if ($date === '') return '';

    $dt = DateTime::createFromFormat('Y-m-d', $date);
    return $dt ? $dt->format('d/m/Y') : '';
}

function formatDateForDisplay(?string $date): string
{
    $formatted = formatDateForInput($date);
    return $formatted !== '' ? $formatted : '-';
}

function getReminderMonths(?string $category): int
{
    $category = strtolower(trim((string)$category));
    return $category === 'passport' ? 10 : 3;
}

function getReminderDate(?string $expiryDate, ?string $category): ?DateTime
{
    $expiryDate = trim((string)$expiryDate);
    if ($expiryDate === '') return null;

    $dt = DateTime::createFromFormat('Y-m-d', $expiryDate);
    if (!$dt) return null;

    $dt->modify('-' . getReminderMonths($category) . ' months');
    return $dt;
}

function getReminderStatus(?string $expiryDate, ?string $category): string
{
    $reminderDate = getReminderDate($expiryDate, $category);
    if (!$reminderDate) return '-';

    $today = new DateTime('today');
    return $today >= $reminderDate ? 'Remind now' : 'Waiting';
}

function getDaysLeft(?string $expiryDate): ?int
{
    $expiryDate = trim((string)$expiryDate);
    if ($expiryDate === '') return null;

    $expiry = DateTime::createFromFormat('Y-m-d', $expiryDate);
    if (!$expiry) return null;

    $today = new DateTime('today');
    $interval = $today->diff($expiry);

    return $expiry < $today ? -((int)$interval->days) : (int)$interval->days;
}

function formatDaysLeft(?string $expiryDate): string
{
    $daysLeft = getDaysLeft($expiryDate);

    if ($daysLeft === null) return '-';
    if ($daysLeft < 0) return 'Expired ' . abs($daysLeft) . ' day(s) ago';
    if ($daysLeft === 0) return 'Expires today';

    return $daysLeft . ' day(s)';
}

function getDaysLeftClass(?string $expiryDate): string
{
    $daysLeft = getDaysLeft($expiryDate);

    if ($daysLeft === null) return 'days-muted';
    if ($daysLeft < 0) return 'days-expired';
    if ($daysLeft <= 30) return 'days-danger';
    if ($daysLeft <= 90) return 'days-warning';
    return 'days-safe';
}

function folderUrl(int $folderId, string $workspace, string $scope, ?int $companyId = null): string
{
    $url = 'folder_view.php?id=' . $folderId .
        '&workspace=' . urlencode($workspace) .
        '&scope=' . urlencode($scope);

    if ($workspace === 'company' && !empty($companyId)) {
        $url .= '&company_id=' . (int)$companyId;
    }

    return $url;
}

function backToDocumentsUrl(string $workspace, string $scope, ?int $companyId = null): string
{
    $url = "my_documents.php?workspace=" . urlencode($workspace) . "&scope=" . urlencode($scope);
    if ($workspace === 'company' && !empty($companyId)) {
        $url .= "&company_id=" . (int)$companyId;
    }
    return $url;
}

function collectDescendantFolderIds(PDO $db, int $folderId, bool $isCompany, ?int $companyId, int $userId): array
{
    $allIds = [$folderId];
    $queue = [$folderId];

    while (!empty($queue)) {
        $currentParentId = array_shift($queue);

        if ($isCompany) {
            $stmt = $db->prepare("
                SELECT id
                FROM folders
                WHERE parent_folder_id = :parent_folder_id
                  AND company_id = :company_id
            ");
            $stmt->bindValue(':company_id', $companyId, PDO::PARAM_INT);
        } else {
            $stmt = $db->prepare("
                SELECT id
                FROM folders
                WHERE parent_folder_id = :parent_folder_id
                  AND user_id = :user_id
                  AND company_id IS NULL
            ");
            $stmt->bindValue(':user_id', $userId, PDO::PARAM_INT);
        }

        $stmt->bindValue(':parent_folder_id', $currentParentId, PDO::PARAM_INT);
        $stmt->execute();
        $children = $stmt->fetchAll(PDO::FETCH_COLUMN);

        foreach ($children as $childId) {
            $childId = (int)$childId;
            if ($childId > 0 && !in_array($childId, $allIds, true)) {
                $allIds[] = $childId;
                $queue[] = $childId;
            }
        }
    }

    return $allIds;
}

function buildFolderBreadcrumb(PDO $db, int $folderId, bool $isCompany, ?int $companyId, int $userId): array
{
    $items = [];
    $currentId = $folderId;

    while ($currentId > 0) {
        if ($isCompany) {
            $stmt = $db->prepare("
                SELECT id, folder_name, parent_folder_id
                FROM folders
                WHERE id = :id
                  AND company_id = :company_id
                LIMIT 1
            ");
            $stmt->bindValue(':company_id', $companyId, PDO::PARAM_INT);
        } else {
            $stmt = $db->prepare("
                SELECT id, folder_name, parent_folder_id
                FROM folders
                WHERE id = :id
                  AND user_id = :user_id
                  AND company_id IS NULL
                LIMIT 1
            ");
            $stmt->bindValue(':user_id', $userId, PDO::PARAM_INT);
        }

        $stmt->bindValue(':id', $currentId, PDO::PARAM_INT);
        $stmt->execute();
        $folder = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$folder) break;

        $items[] = $folder;
        $currentId = isset($folder['parent_folder_id']) ? (int)$folder['parent_folder_id'] : 0;
    }

    return array_reverse($items);
}

function getCategories(PDO $db): array
{
    $stmt = $db->prepare("
        SELECT id, name
        FROM document_categories
        ORDER BY name ASC
    ");
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function getCategoryById(PDO $db, int $categoryId): ?array
{
    if ($categoryId <= 0) return null;

    $stmt = $db->prepare("
        SELECT id, name
        FROM document_categories
        WHERE id = :id
        LIMIT 1
    ");
    $stmt->bindValue(':id', $categoryId, PDO::PARAM_INT);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    return $row ?: null;
}

function canUseDocument(PDO $db, int $documentId, int $folderId, bool $isCompany, ?int $companyId, int $userId): ?array
{
    if ($isCompany) {
        $stmt = $db->prepare("
            SELECT *
            FROM documents
            WHERE id = :id
              AND folder_id = :folder_id
              AND company_id = :company_id
            LIMIT 1
        ");
        $stmt->bindValue(':company_id', $companyId, PDO::PARAM_INT);
    } else {
        $stmt = $db->prepare("
            SELECT *
            FROM documents
            WHERE id = :id
              AND folder_id = :folder_id
              AND user_id = :user_id
              AND company_id IS NULL
            LIMIT 1
        ");
        $stmt->bindValue(':user_id', $userId, PDO::PARAM_INT);
    }

    $stmt->bindValue(':id', $documentId, PDO::PARAM_INT);
    $stmt->bindValue(':folder_id', $folderId, PDO::PARAM_INT);
    $stmt->execute();

    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ?: null;
}

function saveUploadedDocumentFile(array $file, string &$uploadError = ''): ?array
{
    $uploadError = '';

    if (!isset($file['error'])) {
        $uploadError = 'No file received by server.';
        return null;
    }

    $phpUploadError = getUploadErrorMessage($file);
    if ($phpUploadError !== '') {
        $uploadError = $phpUploadError;
        return null;
    }

    $fileSize = isset($file['size']) ? (int)$file['size'] : 0;
    if ($fileSize <= 0) {
        $uploadError = 'The uploaded file is empty.';
        return null;
    }

    if ($fileSize > MAX_UPLOAD_BYTES) {
        $uploadError = 'The file is too large. Maximum allowed file size is ' . bytesToHuman(MAX_UPLOAD_BYTES) . '.';
        return null;
    }

    if (!isAllowedDocumentFile($file)) {
        $uploadError = 'This file type is not allowed. Please upload PDF, image, Office, text, or CSV files.';
        return null;
    }

    $tmpFile = (string)($file['tmp_name'] ?? '');
    if ($tmpFile === '' || !is_uploaded_file($tmpFile)) {
        $uploadError = 'Invalid upload. Please choose the file again and retry.';
        return null;
    }

    $uploadDir = __DIR__ . '/' . UPLOAD_DIR_RELATIVE;
    if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true)) {
        $uploadError = 'Upload folder could not be created.';
        return null;
    }

    if (!is_writable($uploadDir)) {
        $uploadError = 'Upload folder is not writable. Please check permissions for ' . UPLOAD_DIR_RELATIVE;
        return null;
    }

    $originalFileName = (string)$file['name'];
    $fileType = $file['type'] ?? null;

    $extension = strtolower(pathinfo($originalFileName, PATHINFO_EXTENSION));
    $safeFileName = uniqid('doc_', true) . ($extension ? '.' . $extension : '');
    $targetPath = $uploadDir . $safeFileName;
    $dbFilePath = UPLOAD_DIR_RELATIVE . $safeFileName;

    if (!move_uploaded_file($tmpFile, $targetPath)) {
        $uploadError = 'Failed to move uploaded file. Please check upload folder permissions.';
        return null;
    }

    return [
        'file_name' => $safeFileName,
        'original_file_name' => $originalFileName,
        'file_path' => $dbFilePath,
        'absolute_path' => $targetPath,
        'file_type' => $fileType,
        'file_size' => $fileSize,
    ];
}

function getDefaultFieldLabels(PDO $db, int $folderId): array
{
    $stmt = $db->prepare("
        SELECT field_key, field_label
        FROM document_default_field_labels
        WHERE folder_id = :folder_id
    ");
    $stmt->bindValue(':folder_id', $folderId, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
}

function getCustomFields(PDO $db, int $folderId): array
{
    $stmt = $db->prepare("
        SELECT id, folder_id, field_name, field_type, created_at
        FROM document_custom_fields
        WHERE folder_id = :folder_id
        ORDER BY id ASC
    ");
    $stmt->bindValue(':folder_id', $folderId, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function getCustomFieldById(PDO $db, int $fieldId, int $folderId): ?array
{
    $stmt = $db->prepare("
        SELECT id, folder_id, field_name, field_type
        FROM document_custom_fields
        WHERE id = :id
          AND folder_id = :folder_id
        LIMIT 1
    ");
    $stmt->bindValue(':id', $fieldId, PDO::PARAM_INT);
    $stmt->bindValue(':folder_id', $folderId, PDO::PARAM_INT);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ?: null;
}

function saveCustomFieldValues(PDO $db, int $documentId, array $customValues, array $customFields): void
{
    if ($documentId <= 0 || empty($customFields)) return;

    $allowedFieldIds = array_map(static fn($field) => (int)$field['id'], $customFields);

    $stmt = $db->prepare("
        INSERT INTO document_custom_values (document_id, field_id, field_value)
        VALUES (:document_id, :field_id, :field_value)
        ON DUPLICATE KEY UPDATE field_value = VALUES(field_value)
    ");

    foreach ($allowedFieldIds as $fieldId) {
        $value = trim((string)($customValues[$fieldId] ?? ''));
        $stmt->bindValue(':document_id', $documentId, PDO::PARAM_INT);
        $stmt->bindValue(':field_id', $fieldId, PDO::PARAM_INT);
        $stmt->bindValue(':field_value', $value !== '' ? $value : null, $value !== '' ? PDO::PARAM_STR : PDO::PARAM_NULL);
        $stmt->execute();
    }
}

function loadCustomValues(PDO $db, array $files): array
{
    if (empty($files)) return [];

    $documentIds = array_map(static fn($file) => (int)$file['id'], $files);
    $documentIds = array_values(array_filter($documentIds));

    if (empty($documentIds)) return [];

    $placeholders = implode(',', array_fill(0, count($documentIds), '?'));
    $stmt = $db->prepare("
        SELECT document_id, field_id, field_value
        FROM document_custom_values
        WHERE document_id IN ($placeholders)
    ");

    foreach ($documentIds as $index => $documentId) {
        $stmt->bindValue($index + 1, $documentId, PDO::PARAM_INT);
    }

    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $values = [];

    foreach ($rows as $row) {
        $values[(int)$row['document_id']][(int)$row['field_id']] = (string)($row['field_value'] ?? '');
    }

    return $values;
}

function insertDocument(PDO $db, array $savedFile, array $data, bool $isCompany, ?int $companyId, int $userId, int $folderId): int
{
    if ($isCompany) {
        $stmt = $db->prepare("
            INSERT INTO documents (
                user_id, custom_name, file_name, original_file_name, file_path,
                file_type, file_size, expiry_date, company_id, folder_id,
                category_id, category, note, created_by, updated_by, created_at
            ) VALUES (
                :user_id, :custom_name, :file_name, :original_file_name, :file_path,
                :file_type, :file_size, :expiry_date, :company_id, :folder_id,
                :category_id, :category, :note, :created_by, :updated_by, NOW()
            )
        ");
        $stmt->bindValue(':company_id', $companyId, PDO::PARAM_INT);
    } else {
        $stmt = $db->prepare("
            INSERT INTO documents (
                user_id, custom_name, file_name, original_file_name, file_path,
                file_type, file_size, expiry_date, company_id, folder_id,
                category_id, category, note, created_by, updated_by, created_at
            ) VALUES (
                :user_id, :custom_name, :file_name, :original_file_name, :file_path,
                :file_type, :file_size, :expiry_date, NULL, :folder_id,
                :category_id, :category, :note, :created_by, :updated_by, NOW()
            )
        ");
    }

    $stmt->bindValue(':user_id', $userId, PDO::PARAM_INT);
    $stmt->bindValue(':custom_name', $data['document_name'], PDO::PARAM_STR);
    $stmt->bindValue(':file_name', $savedFile['file_name'], PDO::PARAM_STR);
    $stmt->bindValue(':original_file_name', $savedFile['original_file_name'], PDO::PARAM_STR);
    $stmt->bindValue(':file_path', $savedFile['file_path'], PDO::PARAM_STR);
    $stmt->bindValue(':folder_id', $folderId, PDO::PARAM_INT);
    $stmt->bindValue(':category_id', (int)$data['category_id'], PDO::PARAM_INT);
    $stmt->bindValue(':category', (string)$data['category_name'], PDO::PARAM_STR);
    $stmt->bindValue(':note', $data['note'] !== '' ? $data['note'] : null, $data['note'] !== '' ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':created_by', $userId, PDO::PARAM_INT);
    $stmt->bindValue(':updated_by', $userId, PDO::PARAM_INT);
    $stmt->bindValue(':file_type', !empty($savedFile['file_type']) ? $savedFile['file_type'] : null, !empty($savedFile['file_type']) ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':file_size', $savedFile['file_size'] ?? null, isset($savedFile['file_size']) ? PDO::PARAM_INT : PDO::PARAM_NULL);
    $stmt->bindValue(':expiry_date', $data['expiry_date'] !== null ? $data['expiry_date'] : null, $data['expiry_date'] !== null ? PDO::PARAM_STR : PDO::PARAM_NULL);

    $stmt->execute();
    return (int)$db->lastInsertId();
}

ensureCustomFieldTables($db);

$stmtCompanies = $db->prepare("
    SELECT c.id, c.company_name
    FROM company_users cu
    INNER JOIN companies c ON c.id = cu.company_id
    WHERE cu.user_id = :user_id
    ORDER BY c.company_name ASC
");
$stmtCompanies->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$stmtCompanies->execute();
$userCompanies = $stmtCompanies->fetchAll(PDO::FETCH_ASSOC);

if ($workspace === 'company' && $requested_company_id > 0) {
    $stmtCompany = $db->prepare("
        SELECT c.id, c.company_name
        FROM company_users cu
        INNER JOIN companies c ON c.id = cu.company_id
        WHERE cu.user_id = :user_id
          AND cu.company_id = :company_id
        LIMIT 1
    ");
    $stmtCompany->bindValue(':user_id', $user_id, PDO::PARAM_INT);
    $stmtCompany->bindValue(':company_id', $requested_company_id, PDO::PARAM_INT);
    $stmtCompany->execute();

    $companyRow = $stmtCompany->fetch(PDO::FETCH_ASSOC);

    if ($companyRow) {
        $hasCompanyWorkspace = true;
        $active_company_id = (int)$companyRow['id'];
        $company_name = trim((string)($companyRow['company_name'] ?? ''));
    }
}

if ($workspace !== 'company' || !$hasCompanyWorkspace) {
    $workspace = 'personal';
}
if ($scope !== 'company' || !$hasCompanyWorkspace) {
    $scope = 'personal';
}

$is_company_workspace = (
    $workspace === 'company' &&
    $scope === 'company' &&
    $active_company_id !== null
);

if ($folder_id <= 0) {
    header("Location: " . backToDocumentsUrl($workspace, $scope, $active_company_id));
    exit;
}

if ($is_company_workspace) {
    $stmt = $db->prepare("
        SELECT id, folder_name, parent_folder_id, created_at
        FROM folders
        WHERE id = :id
          AND company_id = :company_id
        LIMIT 1
    ");
    $stmt->bindValue(':id', $folder_id, PDO::PARAM_INT);
    $stmt->bindValue(':company_id', $active_company_id, PDO::PARAM_INT);
} else {
    $stmt = $db->prepare("
        SELECT id, folder_name, parent_folder_id, created_at
        FROM folders
        WHERE id = :id
          AND user_id = :user_id
          AND company_id IS NULL
        LIMIT 1
    ");
    $stmt->bindValue(':id', $folder_id, PDO::PARAM_INT);
    $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
}

$stmt->execute();
$currentFolder = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$currentFolder) {
    die("Folder not found or access denied.");
}

$currentFolderId = (int)$currentFolder['id'];
$currentFolderName = trim((string)$currentFolder['folder_name']);
$currentParentFolderId = isset($currentFolder['parent_folder_id']) ? (int)$currentFolder['parent_folder_id'] : 0;
$pageTitle = $currentFolderName;

$breadcrumbFolders = buildFolderBreadcrumb($db, $currentFolderId, $is_company_workspace, $active_company_id, $user_id);
$categories = getCategories($db);
$customFields = getCustomFields($db, $currentFolderId);
$defaultFieldLabels = getDefaultFieldLabels($db, $currentFolderId);
$defaultDocumentFields = [
    ['field_key' => 'no', 'default_label' => 'No', 'field_type' => 'Default'],
    ['field_key' => 'name', 'default_label' => 'Name', 'field_type' => 'Default'],
    ['field_key' => 'category', 'default_label' => 'Category', 'field_type' => 'Default'],
    ['field_key' => 'expiry_date', 'default_label' => 'Expiry Date', 'field_type' => 'Default'],
    ['field_key' => 'days', 'default_label' => 'Days', 'field_type' => 'Default'],
    ['field_key' => 'reminder', 'default_label' => 'Reminder', 'field_type' => 'Default'],
    ['field_key' => 'file', 'default_label' => 'File', 'field_type' => 'Default'],
    ['field_key' => 'note', 'default_label' => 'Note', 'field_type' => 'Default'],
];

foreach ($defaultDocumentFields as &$defaultField) {
    $key = $defaultField['field_key'];
    $defaultField['field_name'] = $defaultFieldLabels[$key] ?? $defaultField['default_label'];
}
unset($defaultField);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['rename_folder'])) {
    $new_folder_name = trim($_POST['new_folder_name'] ?? '');

    if ($new_folder_name === '') {
        $error = 'Please enter folder name.';
    } else {
        try {
            if ($is_company_workspace) {
                $stmt = $db->prepare("
                    UPDATE folders
                    SET folder_name = :folder_name
                    WHERE id = :id
                      AND company_id = :company_id
                    LIMIT 1
                ");
                $stmt->bindValue(':company_id', $active_company_id, PDO::PARAM_INT);
            } else {
                $stmt = $db->prepare("
                    UPDATE folders
                    SET folder_name = :folder_name
                    WHERE id = :id
                      AND user_id = :user_id
                      AND company_id IS NULL
                    LIMIT 1
                ");
                $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
            }

            $stmt->bindValue(':folder_name', $new_folder_name, PDO::PARAM_STR);
            $stmt->bindValue(':id', $currentFolderId, PDO::PARAM_INT);
            $stmt->execute();

            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        } catch (PDOException $e) {
            $error = 'Unable to rename folder: ' . $e->getMessage();
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_folder'])) {
    try {
        $folderIdsToDelete = collectDescendantFolderIds($db, $currentFolderId, $is_company_workspace, $active_company_id, $user_id);
        $placeholders = implode(',', array_fill(0, count($folderIdsToDelete), '?'));

        $stmt = $db->prepare("SELECT file_path FROM documents WHERE folder_id IN ($placeholders)");
        foreach ($folderIdsToDelete as $index => $id) {
            $stmt->bindValue($index + 1, $id, PDO::PARAM_INT);
        }
        $stmt->execute();
        $filesToDelete = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($filesToDelete as $fileRow) {
            $absolutePath = __DIR__ . '/' . ltrim((string)$fileRow['file_path'], '/');
            if (!empty($fileRow['file_path']) && file_exists($absolutePath)) {
                @unlink($absolutePath);
            }
        }

        $stmt = $db->prepare("DELETE FROM documents WHERE folder_id IN ($placeholders)");
        foreach ($folderIdsToDelete as $index => $id) {
            $stmt->bindValue($index + 1, $id, PDO::PARAM_INT);
        }
        $stmt->execute();

        rsort($folderIdsToDelete);
        $stmt = $db->prepare("DELETE FROM folders WHERE id = ?");
        foreach ($folderIdsToDelete as $deleteFolderId) {
            $stmt->execute([$deleteFolderId]);
        }

        if ($currentParentFolderId > 0) {
            header("Location: " . folderUrl($currentParentFolderId, $workspace, $scope, $active_company_id));
        } else {
            header("Location: " . backToDocumentsUrl($workspace, $scope, $active_company_id));
        }
        exit;
    } catch (PDOException $e) {
        $error = 'Unable to delete folder: ' . $e->getMessage();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_default_field_key'])) {
    $fieldKey = trim($_POST['edit_default_field_key'] ?? '');
    $fieldLabel = trim($_POST['field_label'] ?? '');
    $allowedDefaultKeys = ['no', 'name', 'category', 'expiry_date', 'days', 'reminder', 'file', 'note'];

    if (!in_array($fieldKey, $allowedDefaultKeys, true)) {
        $error = 'Default field not found.';
    } elseif ($fieldLabel === '') {
        $error = 'Please enter field name.';
    } else {
        try {
            $stmt = $db->prepare("
                INSERT INTO document_default_field_labels (folder_id, field_key, field_label)
                VALUES (:folder_id, :field_key, :field_label)
                ON DUPLICATE KEY UPDATE field_label = VALUES(field_label)
            ");
            $stmt->bindValue(':folder_id', $currentFolderId, PDO::PARAM_INT);
            $stmt->bindValue(':field_key', $fieldKey, PDO::PARAM_STR);
            $stmt->bindValue(':field_label', $fieldLabel, PDO::PARAM_STR);
            $stmt->execute();

            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        } catch (PDOException $e) {
            $error = 'Unable to rename default field: ' . $e->getMessage();
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_custom_field'])) {
    $fieldName = trim($_POST['field_name'] ?? '');
    $fieldType = trim($_POST['field_type'] ?? 'text');
    $allowedTypes = ['text', 'number', 'date'];

    if ($fieldName === '') {
        $error = 'Please enter field name.';
    } elseif (!in_array($fieldType, $allowedTypes, true)) {
        $error = 'Please select a valid field type.';
    } else {
        try {
            $stmt = $db->prepare("
                INSERT INTO document_custom_fields (folder_id, field_name, field_type)
                VALUES (:folder_id, :field_name, :field_type)
            ");
            $stmt->bindValue(':folder_id', $currentFolderId, PDO::PARAM_INT);
            $stmt->bindValue(':field_name', $fieldName, PDO::PARAM_STR);
            $stmt->bindValue(':field_type', $fieldType, PDO::PARAM_STR);
            $stmt->execute();

            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        } catch (PDOException $e) {
            $error = 'Unable to add field: ' . $e->getMessage();
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_custom_field_id'])) {
    $fieldId = (int)($_POST['edit_custom_field_id'] ?? 0);
    $fieldName = trim($_POST['field_name'] ?? '');
    $fieldType = trim($_POST['field_type'] ?? 'text');
    $allowedTypes = ['text', 'number', 'date'];
    $field = getCustomFieldById($db, $fieldId, $currentFolderId);

    if (!$field) {
        $error = 'Field not found.';
    } elseif ($fieldName === '') {
        $error = 'Please enter field name.';
    } elseif (!in_array($fieldType, $allowedTypes, true)) {
        $error = 'Please select a valid field type.';
    } else {
        try {
            $stmt = $db->prepare("
                UPDATE document_custom_fields
                SET field_name = :field_name,
                    field_type = :field_type
                WHERE id = :id
                  AND folder_id = :folder_id
                LIMIT 1
            ");
            $stmt->bindValue(':field_name', $fieldName, PDO::PARAM_STR);
            $stmt->bindValue(':field_type', $fieldType, PDO::PARAM_STR);
            $stmt->bindValue(':id', $fieldId, PDO::PARAM_INT);
            $stmt->bindValue(':folder_id', $currentFolderId, PDO::PARAM_INT);
            $stmt->execute();

            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        } catch (PDOException $e) {
            $error = 'Unable to edit field: ' . $e->getMessage();
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_custom_field_id'])) {
    $fieldId = (int)($_POST['delete_custom_field_id'] ?? 0);
    $field = getCustomFieldById($db, $fieldId, $currentFolderId);

    if (!$field) {
        $error = 'Field not found.';
    } else {
        try {
            $stmt = $db->prepare("DELETE FROM document_custom_values WHERE field_id = :field_id");
            $stmt->bindValue(':field_id', $fieldId, PDO::PARAM_INT);
            $stmt->execute();

            $stmt = $db->prepare("
                DELETE FROM document_custom_fields
                WHERE id = :id
                  AND folder_id = :folder_id
                LIMIT 1
            ");
            $stmt->bindValue(':id', $fieldId, PDO::PARAM_INT);
            $stmt->bindValue(':folder_id', $currentFolderId, PDO::PARAM_INT);
            $stmt->execute();

            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        } catch (PDOException $e) {
            $error = 'Unable to delete field: ' . $e->getMessage();
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_file'])) {
    $category_id = (int)($_POST['category_id'] ?? 0);
    $categoryRow = getCategoryById($db, $category_id);
    $document_name = trim($_POST['document_name'] ?? '');
    $expiry_date_raw = trim($_POST['expiry_date'] ?? '');
    $expiry_date = convertToSqlDate($expiry_date_raw);
    $note = trim($_POST['note'] ?? '');
    $customFieldValues = $_POST['custom_fields'] ?? [];

    if (!$categoryRow) {
        $error = 'Please select a valid category.';
    } elseif ($document_name === '') {
        $error = 'Please enter document name.';
    } elseif ($expiry_date_raw !== '' && $expiry_date === null) {
        $error = 'Expiry date is invalid. Please use dd/mm/yyyy.';
    } elseif (!isset($_FILES['document_file'])) {
        $error = 'No file received by server. If the file is larger than your hosting limit, PHP may remove it before this page can process it.';
    } else {
        $uploadError = '';
        $savedFile = saveUploadedDocumentFile($_FILES['document_file'], $uploadError);

        if (!$savedFile) {
            $error = $uploadError !== '' ? $uploadError : 'Failed to upload file.';
        } else {
            try {
                $newDocumentId = insertDocument($db, $savedFile, [
                    'document_name' => $document_name,
                    'category_id' => (int)$categoryRow['id'],
                    'category_name' => (string)$categoryRow['name'],
                    'expiry_date' => $expiry_date,
                    'note' => $note,
                ], $is_company_workspace, $active_company_id, $user_id, $currentFolderId);

                saveCustomFieldValues($db, $newDocumentId, is_array($customFieldValues) ? $customFieldValues : [], $customFields);

                header("Location: " . $_SERVER['REQUEST_URI']);
                exit;
            } catch (PDOException $e) {
                if (file_exists($savedFile['absolute_path'])) {
                    @unlink($savedFile['absolute_path']);
                }
                $error = 'Database error: ' . $e->getMessage();
            }
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_file_id'])) {
    $file_id = (int)($_POST['edit_file_id'] ?? 0);
    $existingFile = canUseDocument($db, $file_id, $currentFolderId, $is_company_workspace, $active_company_id, $user_id);

    $category_id = (int)($_POST['category_id'] ?? 0);
    $categoryRow = getCategoryById($db, $category_id);
    $document_name = trim($_POST['document_name'] ?? '');
    $expiry_date_raw = trim($_POST['expiry_date'] ?? '');
    $expiry_date = convertToSqlDate($expiry_date_raw);
    $note = trim($_POST['note'] ?? '');
    $customFieldValues = $_POST['custom_fields'] ?? [];

    if (!$existingFile) {
        $error = 'File not found or access denied.';
    } elseif (!$categoryRow) {
        $error = 'Please select a valid category.';
    } elseif ($document_name === '') {
        $error = 'Please enter document name.';
    } elseif ($expiry_date_raw !== '' && $expiry_date === null) {
        $error = 'Expiry date is invalid. Please use dd/mm/yyyy.';
    } else {
        $newFile = null;

        if (isset($_FILES['document_file']) && (int)($_FILES['document_file']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
            $uploadError = '';
            $newFile = saveUploadedDocumentFile($_FILES['document_file'], $uploadError);
            if (!$newFile) {
                $error = $uploadError !== '' ? $uploadError : 'Failed to upload replacement file.';
            }
        }

        if ($error === '') {
            try {
                $sql = "
                    UPDATE documents
                    SET custom_name = :custom_name,
                        category_id = :category_id,
                        category = :category,
                        expiry_date = :expiry_date,
                        note = :note,
                        updated_by = :updated_by
                ";

                if ($newFile) {
                    $sql .= ",
                        file_name = :file_name,
                        original_file_name = :original_file_name,
                        file_path = :file_path,
                        file_type = :file_type,
                        file_size = :file_size
                    ";
                }

                if ($is_company_workspace) {
                    $sql .= "
                        WHERE id = :id
                          AND folder_id = :folder_id
                          AND company_id = :company_id
                        LIMIT 1
                    ";
                } else {
                    $sql .= "
                        WHERE id = :id
                          AND folder_id = :folder_id
                          AND user_id = :user_id
                          AND company_id IS NULL
                        LIMIT 1
                    ";
                }

                $stmt = $db->prepare($sql);
                $stmt->bindValue(':custom_name', $document_name, PDO::PARAM_STR);
                $stmt->bindValue(':category_id', (int)$categoryRow['id'], PDO::PARAM_INT);
                $stmt->bindValue(':category', (string)$categoryRow['name'], PDO::PARAM_STR);
                $stmt->bindValue(':note', $note !== '' ? $note : null, $note !== '' ? PDO::PARAM_STR : PDO::PARAM_NULL);
                $stmt->bindValue(':updated_by', $user_id, PDO::PARAM_INT);
                $stmt->bindValue(':id', $file_id, PDO::PARAM_INT);
                $stmt->bindValue(':folder_id', $currentFolderId, PDO::PARAM_INT);

                if ($is_company_workspace) {
                    $stmt->bindValue(':company_id', $active_company_id, PDO::PARAM_INT);
                } else {
                    $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
                }

                $stmt->bindValue(':expiry_date', $expiry_date !== null ? $expiry_date : null, $expiry_date !== null ? PDO::PARAM_STR : PDO::PARAM_NULL);

                if ($newFile) {
                    $stmt->bindValue(':file_name', $newFile['file_name'], PDO::PARAM_STR);
                    $stmt->bindValue(':original_file_name', $newFile['original_file_name'], PDO::PARAM_STR);
                    $stmt->bindValue(':file_path', $newFile['file_path'], PDO::PARAM_STR);
                    $stmt->bindValue(':file_type', !empty($newFile['file_type']) ? $newFile['file_type'] : null, !empty($newFile['file_type']) ? PDO::PARAM_STR : PDO::PARAM_NULL);
                    $stmt->bindValue(':file_size', $newFile['file_size'] ?? null, isset($newFile['file_size']) ? PDO::PARAM_INT : PDO::PARAM_NULL);
                }

                $stmt->execute();
                saveCustomFieldValues($db, $file_id, is_array($customFieldValues) ? $customFieldValues : [], $customFields);

                if ($newFile && !empty($existingFile['file_path'])) {
                    $oldPath = __DIR__ . '/' . ltrim((string)$existingFile['file_path'], '/');
                    if (file_exists($oldPath)) {
                        @unlink($oldPath);
                    }
                }

                header("Location: " . $_SERVER['REQUEST_URI']);
                exit;
            } catch (PDOException $e) {
                if ($newFile && file_exists($newFile['absolute_path'])) {
                    @unlink($newFile['absolute_path']);
                }
                $error = 'Unable to update document: ' . $e->getMessage();
            }
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_file_id'])) {
    $file_id = (int)($_POST['delete_file_id'] ?? 0);
    $fileToDelete = canUseDocument($db, $file_id, $currentFolderId, $is_company_workspace, $active_company_id, $user_id);

    if (!$fileToDelete) {
        $error = 'File not found or access denied.';
    } else {
        try {
            $absolutePath = __DIR__ . '/' . ltrim((string)$fileToDelete['file_path'], '/');
            if (!empty($fileToDelete['file_path']) && file_exists($absolutePath)) {
                @unlink($absolutePath);
            }

            if ($is_company_workspace) {
                $stmt = $db->prepare("
                    DELETE FROM documents
                    WHERE id = :id
                      AND folder_id = :folder_id
                      AND company_id = :company_id
                    LIMIT 1
                ");
                $stmt->bindValue(':company_id', $active_company_id, PDO::PARAM_INT);
            } else {
                $stmt = $db->prepare("
                    DELETE FROM documents
                    WHERE id = :id
                      AND folder_id = :folder_id
                      AND user_id = :user_id
                      AND company_id IS NULL
                    LIMIT 1
                ");
                $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
            }

            $stmt->bindValue(':id', $file_id, PDO::PARAM_INT);
            $stmt->bindValue(':folder_id', $currentFolderId, PDO::PARAM_INT);
            $stmt->execute();

            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        } catch (PDOException $e) {
            $error = 'Delete failed: ' . $e->getMessage();
        }
    }
}

if ($is_company_workspace) {
    $stmt = $db->prepare("
        SELECT d.*, c.car_name, c.plate_number
        FROM documents d
        LEFT JOIN cars c ON d.car_id = c.id
        WHERE d.folder_id = :folder_id
          AND d.company_id = :company_id
        ORDER BY d.id DESC
    ");
    $stmt->bindValue(':company_id', $active_company_id, PDO::PARAM_INT);
} else {
    $stmt = $db->prepare("
        SELECT d.*, c.car_name, c.plate_number
        FROM documents d
        LEFT JOIN cars c ON d.car_id = c.id
        WHERE d.folder_id = :folder_id
          AND d.user_id = :user_id
          AND d.company_id IS NULL
        ORDER BY d.id DESC
    ");
    $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
}

$stmt->bindValue(':folder_id', $currentFolderId, PDO::PARAM_INT);
$stmt->execute();
$files = $stmt->fetchAll(PDO::FETCH_ASSOC);
$customValuesByDocument = loadCustomValues($db, $files);

$workspaceLabel = $is_company_workspace
    ? ($company_name !== '' ? $company_name : 'Company Workspace')
    : 'Personal Workspace';

$serverUploadLimit = getPhpUploadLimitBytes();
$effectiveUploadLimit = $serverUploadLimit > 0 ? min($serverUploadLimit, MAX_UPLOAD_BYTES) : MAX_UPLOAD_BYTES;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Folder View</title>
    <link rel="stylesheet" href="assets/css/app.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <style>
        html, body { height: auto; overflow-y: auto; }
        body { padding-top: 0; }
        .main { flex: 1; min-width: 0; box-sizing: border-box; padding: 12px; min-height: 100vh; background: #f8fafc; }
        .page-shell { max-width: none; margin: 0; padding-top: 0 !important; margin-top: 0 !important; }
        .content-card { background: #fff; border: 1px solid #e5e7eb; border-radius: 18px; box-shadow: 0 10px 25px rgba(15, 23, 42, 0.04); overflow: hidden; }
        .files-card { padding: 16px; margin-bottom: 14px; }
        .alert-success { background: #ecfdf3; color: #027a48; border: 1px solid #abefc6; padding: 12px 14px; border-radius: 14px; margin-bottom: 14px; }
        .alert-danger { background: #fef3f2; color: #b42318; border: 1px solid #fecdca; padding: 12px 14px; border-radius: 14px; margin-bottom: 14px; }
        .help-box { background: #eff6ff; color: #1e40af; border: 1px solid #bfdbfe; padding: 10px 12px; border-radius: 12px; font-size: 13px; margin: 12px 0; }
        .hidden { display: none !important; }
        .muted { color: #94a3b8; }
        .page-top { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
        .page-title { margin: 0; font-size: 22px; line-height: 1.25; color: #0f172a; }
        .page-subtitle { margin-top: 5px; color: #64748b; font-size: 14px; }
        .breadcrumb { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; margin-top: 10px; font-size: 13px; color: #64748b; }
        .breadcrumb a { color: #2563eb; text-decoration: none; }
        .toolbar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
        .btn { display: inline-flex; align-items: center; justify-content: center; border: 1px solid transparent; border-radius: 12px; padding: 10px 14px; font-size: 14px; font-weight: 700; cursor: pointer; text-decoration: none; min-height: 42px; box-sizing: border-box; }
        .btn-sm { min-height: 36px; padding: 8px 12px; font-size: 13px; }
        .btn-primary { background: #2563eb; color: #fff; border-color: #2563eb; }
        .btn-primary:hover { background: #1d4ed8; border-color: #1d4ed8; }
        .btn-light { background: #fff; color: #334155; border-color: #dbe2ea; }
        .btn-light:hover { background: #f8fafc; }
        .btn-danger { background: #dc2626; color: #fff; border-color: #dc2626; }
        .btn-danger:hover { background: #b91c1c; border-color: #b91c1c; }
        .rename-folder-form { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-top: 12px; }
        .rename-folder-form input { height: 42px; border: 1px solid #dbe2ea; border-radius: 10px; padding: 0 12px; min-width: 260px; }
        .upload-panel { margin-bottom: 14px; }
        .upload-panel-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 14px; }
        .upload-panel-header h2 { margin: 0; font-size: 20px; color: #0f172a; }
        .form-grid { display: grid; grid-template-columns: 1fr; gap: 12px; }
        .form-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
        .form-field label { font-size: 13px; font-weight: 700; color: #334155; }
        .form-field input, .form-field select, .form-field textarea { width: 100%; border: 1px solid #dbe2ea; border-radius: 12px; padding: 0 14px; font-size: 14px; background: #fff; box-sizing: border-box; color: #0f172a; }
        .form-field input, .form-field select { height: 46px; }
        .form-field input[type="file"] { padding: 9px 12px; line-height: normal; }
        .form-field textarea { padding-top: 12px; min-height: 96px; resize: vertical; }
        .form-help { font-size: 12px; color: #64748b; }
        .form-actions { display: flex; gap: 10px; justify-content: flex-end; flex-wrap: wrap; margin-top: 14px; }
        .table-card { overflow-x: auto; overflow-y: hidden; }
        .table-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 14px 16px; border-bottom: 1px solid #e5e7eb; }
        .table-title { margin: 0; font-size: 17px; color: #0f172a; }
        .table-count { font-size: 13px; color: #64748b; }
        .table-wrap { width: 100%; max-width: 100%; overflow-x: auto !important; overflow-y: hidden; -webkit-overflow-scrolling: touch; display: block; }
        .admin-table { width: max-content !important; min-width: 1600px; border-collapse: collapse; table-layout: auto; }
        .admin-table th, .admin-table td { font-size: 14px; padding: 13px 12px; vertical-align: middle; text-align: left; border-bottom: 1px solid #eef2f7; white-space: nowrap; min-width: 180px; }
        .admin-table th:first-child, .admin-table td:first-child { min-width: 70px; }
        .admin-table th:last-child, .admin-table td:last-child { min-width: 90px; position: sticky; right: 0; background: #fff; z-index: 2; }
        .admin-table th:last-child { background: #f8fafc; }
        .admin-table th { font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; color: #64748b; background: #f8fafc; }
        .admin-table tr:last-child td { border-bottom: none; }
        .doc-name { font-weight: 700; color: #0f172a; }
        .chip { display: inline-flex; align-items: center; justify-content: center; min-width: 28px; height: 28px; padding: 0 8px; border-radius: 999px; background: #eff6ff; color: #2563eb; font-size: 12px; font-weight: 800; }
        .badge, .days-badge { display: inline-flex; align-items: center; border-radius: 999px; padding: 5px 9px; font-size: 12px; font-weight: 800; }
        .badge.danger { background: #fef2f2; color: #dc2626; }
        .badge.info { background: #eff6ff; color: #2563eb; }
        .days-muted { background: #f1f5f9; color: #64748b; }
        .days-expired { background: #fef2f2; color: #dc2626; }
        .days-danger { background: #fff1f2; color: #e11d48; }
        .days-warning { background: #fffbeb; color: #d97706; }
        .days-safe { background: #ecfdf5; color: #059669; }
        .link-btn { color: #2563eb; font-weight: 700; text-decoration: none; }
        .link-btn:hover { text-decoration: underline; }
        .empty-state { background: #fff; border: 1px dashed #cbd5e1; border-radius: 16px; padding: 24px; text-align: center; color: #64748b; margin: 12px; }
        .action-menu-wrap { position: relative; overflow: visible; }
        .action-menu-toggle { width: 36px; height: 36px; border: 1px solid #dbe2ea; background: #fff; border-radius: 10px; font-size: 18px; cursor: pointer; }
        .action-menu-toggle:hover { background: #f8fafc; }
        .action-menu { position: absolute; right: 0; top: calc(100% + 6px); background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; box-shadow: 0 12px 24px rgba(15, 23, 42, 0.12); padding: 6px; min-width: 150px; z-index: 50; }
        .action-menu.open-up { top: auto; bottom: calc(100% + 6px); }
        .action-menu button, .action-menu a { display: block; width: 100%; padding: 9px 10px; font-size: 13px; text-align: left; background: none; border: none; color: #334155; text-decoration: none; cursor: pointer; border-radius: 8px; box-sizing: border-box; }
        .action-menu button:hover, .action-menu a:hover { background: #f1f5f9; }
        .action-menu .danger { color: #dc2626; }
        .modal-backdrop { position: fixed; inset: 0; background: rgba(15, 23, 42, 0.5); z-index: 100; display: flex; align-items: center; justify-content: center; padding: 16px; }
        .modal { width: min(720px, 100%); max-height: 90vh; overflow-y: auto; background: #fff; border-radius: 18px; box-shadow: 0 24px 70px rgba(15, 23, 42, 0.25); padding: 18px; }
        .modal-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 14px; }
        .modal-header h2 { margin: 0; font-size: 20px; color: #0f172a; }
        .modal-close { border: none; background: #f1f5f9; color: #334155; border-radius: 999px; width: 34px; height: 34px; cursor: pointer; font-size: 18px; }
        .field-edit-row { display: grid; grid-template-columns: 1fr; gap: 10px; align-items: end; }
        @media (min-width: 700px) { .main { padding: 18px; } .form-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } .form-field-full { grid-column: 1 / -1; } .field-edit-row { grid-template-columns: minmax(220px, 1fr) 160px 220px; } }
        @media (min-width: 1025px) { .main { padding: 22px; overflow-x: hidden; } .table-wrap { overflow-x: auto !important; } .admin-table { width: max-content !important; } .action-menu { top: 50%; right: calc(100% + 8px); transform: translateY(-50%); } }
    </style>
</head>
<body>
<div class="layout">
    <?php include 'nav.php'; ?>

    <main class="main">
        <div class="page-shell">
            <?php if ($message !== ''): ?>
                <div class="alert-success"><?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>

            <?php if ($error !== ''): ?>
                <div class="alert-danger"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>

            <div class="content-card files-card">
                <div class="page-top">
                    <div>
                        <h1 class="page-title">📁 <?php echo htmlspecialchars($pageTitle); ?></h1>
                        <div class="page-subtitle"><?php echo htmlspecialchars($workspaceLabel); ?></div>

                        <?php if (!empty($breadcrumbFolders)): ?>
                            <div class="breadcrumb">
                                <?php foreach ($breadcrumbFolders as $index => $folder): ?>
                                    <?php if ($index > 0): ?><span>/</span><?php endif; ?>
                                    <?php if ((int)$folder['id'] === $currentFolderId): ?>
                                        <strong><?php echo htmlspecialchars($folder['folder_name']); ?></strong>
                                    <?php else: ?>
                                        <a href="<?php echo htmlspecialchars(folderUrl((int)$folder['id'], $workspace, $scope, $active_company_id)); ?>">
                                            <?php echo htmlspecialchars($folder['folder_name']); ?>
                                        </a>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="toolbar">
                        <button type="button" class="btn btn-primary" onclick="showUploadPage()">+ Upload New Documents</button>
                        <button type="button" class="btn btn-light" onclick="openFieldModal()">+ Add Field</button>

                        <div class="action-menu-wrap">
                            <button type="button" class="action-menu-toggle" onclick="toggleFolderTopMenu(event)" aria-label="Folder actions">⋯</button>
                            <div class="action-menu hidden" id="folder-top-action-menu">
                                <button type="button" onclick="toggleRenameFolder(); closeFolderTopMenu();">Rename Folder</button>
                                <form method="POST" onsubmit="return confirm('Delete this folder and all contents?');">
                                    <button type="submit" name="delete_folder" class="danger">Delete Folder</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

                <form method="POST" id="renameFolderForm" class="rename-folder-form hidden">
                    <input type="text" name="new_folder_name" value="<?php echo htmlspecialchars($currentFolderName); ?>" required>
                    <button type="submit" name="rename_folder" class="btn btn-primary btn-sm">Save</button>
                    <button type="button" class="btn btn-light btn-sm" onclick="toggleRenameFolder()">Cancel</button>
                </form>
            </div>

            <div id="uploadPage" class="content-card files-card upload-panel hidden">
                <div class="upload-panel-header">
                    <h2>Upload New Document</h2>
                    <button type="button" class="btn btn-light btn-sm" onclick="hideUploadPage()">Cancel</button>
                </div>

                <div class="help-box">
                    Maximum file size on this page: <?php echo htmlspecialchars(bytesToHuman(MAX_UPLOAD_BYTES)); ?>.
                    Current effective server limit: <?php echo htmlspecialchars(bytesToHuman($effectiveUploadLimit)); ?>.
                    If a file below 20 MB still fails, check cPanel PHP settings for upload_max_filesize and post_max_size.
                </div>

                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_UPLOAD_BYTES; ?>">

                    <div class="form-grid">
                        <div class="form-field">
                            <label for="category_id">Category</label>
                            <select id="category_id" name="category_id" required>
                                <option value="">Select category</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo (int)$cat['id']; ?>">
                                        <?php echo htmlspecialchars($cat['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-field">
                            <label for="document_name">Document Name</label>
                            <input type="text" id="document_name" name="document_name" placeholder="Document name" required>
                        </div>

                        <div class="form-field">
                            <label for="expiry_date">Expiry Date</label>
                            <input type="text" id="expiry_date" name="expiry_date" class="date-input" placeholder="dd/mm/yyyy" inputmode="numeric" autocomplete="off">
                        </div>

                        <div class="form-field">
                            <label for="document_file">File</label>
                            <input type="file" id="document_file" name="document_file" accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv" required>
                            <div class="form-help">Allowed: PDF, images, Office files, TXT, CSV.</div>
                        </div>

                        <div class="form-field form-field-full">
                            <label for="note">Note</label>
                            <textarea id="note" name="note" placeholder="Optional note"></textarea>
                        </div>

                        <?php foreach ($customFields as $field): ?>
                            <div class="form-field">
                                <label><?php echo htmlspecialchars($field['field_name']); ?></label>
                                <input
                                    type="<?php echo $field['field_type'] === 'number' ? 'number' : 'text'; ?>"
                                    class="<?php echo $field['field_type'] === 'date' ? 'date-input' : ''; ?>"
                                    name="custom_fields[<?php echo (int)$field['id']; ?>]"
                                    placeholder="<?php echo htmlspecialchars($field['field_name']); ?>"
                                >
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <div class="form-actions">
                        <button type="button" class="btn btn-light" onclick="hideUploadPage()">Cancel</button>
                        <button type="submit" name="upload_file" class="btn btn-primary">Upload</button>
                    </div>
                </form>
            </div>

            <div class="content-card table-card">
                <div class="table-header">
                    <h2 class="table-title">Documents</h2>
                    <div class="table-count"><?php echo count($files); ?> document(s)</div>
                </div>

                <div class="table-wrap">
                    <table class="admin-table">
                        <thead>
                            <tr>
                                <th style="width:70px;"><?php echo htmlspecialchars($defaultDocumentFields[0]['field_name']); ?></th>
                                <th><?php echo htmlspecialchars($defaultDocumentFields[1]['field_name']); ?></th>
                                <th><?php echo htmlspecialchars($defaultDocumentFields[2]['field_name']); ?></th>
                                <th><?php echo htmlspecialchars($defaultDocumentFields[3]['field_name']); ?></th>
                                <th><?php echo htmlspecialchars($defaultDocumentFields[4]['field_name']); ?></th>
                                <th><?php echo htmlspecialchars($defaultDocumentFields[5]['field_name']); ?></th>
                                <th><?php echo htmlspecialchars($defaultDocumentFields[6]['field_name']); ?></th>
                                <th><?php echo htmlspecialchars($defaultDocumentFields[7]['field_name']); ?></th>
                                <?php foreach ($customFields as $field): ?>
                                    <th><?php echo htmlspecialchars($field['field_name']); ?></th>
                                <?php endforeach; ?>
                                <th style="width:90px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if (!empty($files)): ?>
                            <?php $docNumber = 1; ?>
                            <?php foreach ($files as $file): ?>
                                <?php $reminderStatus = getReminderStatus($file['expiry_date'] ?? '', $file['category'] ?? ''); ?>
                                <tr>
                                    <td><span class="chip"><?php echo $docNumber; ?></span></td>
                                    <td><span class="doc-name"><?php echo htmlspecialchars($file['custom_name'] ?? '-'); ?></span></td>
                                    <td><?php echo htmlspecialchars($file['category'] ?? '-'); ?></td>
                                    <td><?php echo htmlspecialchars(formatDateForDisplay($file['expiry_date'] ?? '')); ?></td>
                                    <td>
                                        <span class="days-badge <?php echo htmlspecialchars(getDaysLeftClass($file['expiry_date'] ?? '')); ?>">
                                            <?php echo htmlspecialchars(formatDaysLeft($file['expiry_date'] ?? '')); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($reminderStatus === 'Remind now'): ?>
                                            <span class="badge danger">Remind now</span>
                                        <?php elseif ($reminderStatus === 'Waiting'): ?>
                                            <span class="badge info">Waiting</span>
                                        <?php else: ?>
                                            <span class="muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if (!empty($file['file_path'])): ?>
                                            <a class="link-btn" href="<?php echo htmlspecialchars($file['file_path']); ?>" target="_blank">View</a>
                                        <?php else: ?>
                                            <span class="muted">No file</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars(($file['note'] ?? '') !== '' ? $file['note'] : '-'); ?></td>
                                    <?php foreach ($customFields as $field): ?>
                                        <?php $customValue = $customValuesByDocument[(int)$file['id']][(int)$field['id']] ?? ''; ?>
                                        <td><?php echo htmlspecialchars($customValue !== '' ? $customValue : '-'); ?></td>
                                    <?php endforeach; ?>
                                    <td>
                                        <div class="action-menu-wrap">
                                            <button type="button" class="action-menu-toggle" onclick="toggleActionMenu(event, <?php echo (int)$file['id']; ?>)">⋯</button>
                                            <div class="action-menu hidden" id="action-menu-<?php echo (int)$file['id']; ?>">
                                                <button type="button" onclick="openEditModal(<?php echo (int)$file['id']; ?>)">Edit</button>

                                                <?php if (!empty($file['file_path'])): ?>
                                                    <a href="<?php echo htmlspecialchars($file['file_path']); ?>" target="_blank">Open</a>
                                                <?php endif; ?>

                                                <form method="POST" onsubmit="return confirm('Delete this file?');">
                                                    <input type="hidden" name="delete_file_id" value="<?php echo (int)$file['id']; ?>">
                                                    <button type="submit" class="danger">Delete</button>
                                                </form>
                                            </div>
                                        </div>

                                        <div class="modal-backdrop hidden" id="edit-modal-<?php echo (int)$file['id']; ?>">
                                            <div class="modal">
                                                <div class="modal-header">
                                                    <h2>Edit Document</h2>
                                                    <button type="button" class="modal-close" onclick="closeEditModal(<?php echo (int)$file['id']; ?>)">×</button>
                                                </div>

                                                <form method="POST" enctype="multipart/form-data">
                                                    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_UPLOAD_BYTES; ?>">
                                                    <input type="hidden" name="edit_file_id" value="<?php echo (int)$file['id']; ?>">

                                                    <div class="form-grid">
                                                        <div class="form-field">
                                                            <label>Category</label>
                                                            <select name="category_id" required>
                                                                <option value="">Select category</option>
                                                                <?php foreach ($categories as $cat): ?>
                                                                    <option value="<?php echo (int)$cat['id']; ?>" <?php echo ((int)($file['category_id'] ?? 0) === (int)$cat['id']) ? 'selected' : ''; ?>>
                                                                        <?php echo htmlspecialchars($cat['name']); ?>
                                                                    </option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        </div>

                                                        <div class="form-field">
                                                            <label>Document Name</label>
                                                            <input type="text" name="document_name" value="<?php echo htmlspecialchars($file['custom_name'] ?? ''); ?>" required>
                                                        </div>

                                                        <div class="form-field">
                                                            <label>Expiry Date</label>
                                                            <input type="text" name="expiry_date" class="date-input" value="<?php echo htmlspecialchars(formatDateForInput($file['expiry_date'] ?? '')); ?>" placeholder="dd/mm/yyyy" inputmode="numeric" autocomplete="off">
                                                        </div>

                                                        <div class="form-field">
                                                            <label>Replace File</label>
                                                            <input type="file" name="document_file" accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv">
                                                            <div class="form-help">Leave empty to keep current file.</div>
                                                        </div>

                                                        <div class="form-field form-field-full">
                                                            <label>Note</label>
                                                            <textarea name="note" placeholder="Optional note"><?php echo htmlspecialchars($file['note'] ?? ''); ?></textarea>
                                                        </div>

                                                        <?php foreach ($customFields as $field): ?>
                                                            <?php $editCustomValue = $customValuesByDocument[(int)$file['id']][(int)$field['id']] ?? ''; ?>
                                                            <div class="form-field">
                                                                <label><?php echo htmlspecialchars($field['field_name']); ?></label>
                                                                <input
                                                                    type="<?php echo $field['field_type'] === 'number' ? 'number' : 'text'; ?>"
                                                                    class="<?php echo $field['field_type'] === 'date' ? 'date-input' : ''; ?>"
                                                                    name="custom_fields[<?php echo (int)$field['id']; ?>]"
                                                                    value="<?php echo htmlspecialchars($editCustomValue); ?>"
                                                                    placeholder="<?php echo htmlspecialchars($field['field_name']); ?>"
                                                                >
                                                            </div>
                                                        <?php endforeach; ?>
                                                    </div>

                                                    <div class="form-actions">
                                                        <button type="button" class="btn btn-light" onclick="closeEditModal(<?php echo (int)$file['id']; ?>)">Cancel</button>
                                                        <button type="submit" class="btn btn-primary">Save Changes</button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <?php $docNumber++; ?>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="<?php echo 9 + count($customFields); ?>">
                                    <div class="empty-state">No files in this folder yet. Click “+ Upload New Documents” to add your first file.</div>
                                </td>
                            </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="modal-backdrop hidden" id="field-modal">
                <div class="modal">
                    <div class="modal-header">
                        <div>
                            <h2>Manage Document Fields</h2>
                            <p style="margin:4px 0 0;color:#64748b;font-size:14px;">View default document columns and add or edit custom fields.</p>
                        </div>
                        <button type="button" class="modal-close" onclick="closeFieldModal()">×</button>
                    </div>

                    <div class="content-card" style="padding:14px;margin-bottom:16px;background:#f8fafc;box-shadow:none;">
                        <h3 style="margin:0 0 12px;font-size:16px;color:#0f172a;">Add New Field</h3>

                        <form method="POST">
                            <div class="form-grid">
                                <div class="form-field">
                                    <label>Field Name</label>
                                    <input type="text" name="field_name" placeholder="Example: Owner" required>
                                </div>

                                <div class="form-field">
                                    <label>Field Type</label>
                                    <select name="field_type">
                                        <option value="text">Text</option>
                                        <option value="number">Number</option>
                                        <option value="date">Date</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-actions">
                                <button type="submit" name="add_custom_field" class="btn btn-primary">Add Field</button>
                            </div>
                        </form>
                    </div>

                    <div style="display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:10px;">
                        <h3 style="margin:0;font-size:16px;color:#0f172a;">Existing Fields</h3>
                        <span class="table-count"><?php echo count($defaultDocumentFields) + count($customFields); ?> field(s)</span>
                    </div>

                    <div class="table-wrap">
                        <table class="admin-table" style="min-width:600px;">
                            <thead>
                                <tr>
                                    <th>Field Name</th>
                                    <th>Type</th>
                                    <th style="width:220px;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($defaultDocumentFields as $field): ?>
                                    <tr>
                                        <td colspan="3">
                                            <form method="POST" class="field-edit-row">
                                                <input type="hidden" name="edit_default_field_key" value="<?php echo htmlspecialchars($field['field_key']); ?>">

                                                <div class="form-field">
                                                    <label>Field Name</label>
                                                    <input type="text" name="field_label" value="<?php echo htmlspecialchars($field['field_name']); ?>" required>
                                                </div>

                                                <div class="form-field">
                                                    <label>Type</label>
                                                    <input type="text" value="Default" disabled>
                                                </div>

                                                <div class="form-actions" style="margin-top:0; justify-content:flex-start;">
                                                    <button type="submit" class="btn btn-primary btn-sm">Save</button>
                                                    <span class="muted" style="align-self:center;">Cannot delete</span>
                                                </div>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>

                                <?php foreach ($customFields as $field): ?>
                                    <tr>
                                        <td colspan="3">
                                            <form method="POST" class="field-edit-row">
                                                <input type="hidden" name="edit_custom_field_id" value="<?php echo (int)$field['id']; ?>">

                                                <div class="form-field">
                                                    <label>Field Name</label>
                                                    <input type="text" name="field_name" value="<?php echo htmlspecialchars($field['field_name']); ?>" required>
                                                </div>

                                                <div class="form-field">
                                                    <label>Type</label>
                                                    <select name="field_type">
                                                        <option value="text" <?php echo $field['field_type'] === 'text' ? 'selected' : ''; ?>>Text</option>
                                                        <option value="number" <?php echo $field['field_type'] === 'number' ? 'selected' : ''; ?>>Number</option>
                                                        <option value="date" <?php echo $field['field_type'] === 'date' ? 'selected' : ''; ?>>Date</option>
                                                    </select>
                                                </div>

                                                <div class="form-actions" style="margin-top:0; justify-content:flex-start;">
                                                    <button type="submit" class="btn btn-primary btn-sm">Save</button>
                                                    <button type="submit" name="delete_custom_field_id" value="<?php echo (int)$field['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Delete this field and all values?');">Delete</button>
                                                </div>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>

                                <?php if (empty($customFields)): ?>
                                    <tr>
                                        <td colspan="3">
                                            <div class="empty-state">No custom fields yet. Add one above.</div>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    flatpickr('.date-input', {
        dateFormat: 'd/m/Y',
        allowInput: true,
        disableMobile: true
    });
});

function openFieldModal() {
    const modal = document.getElementById('field-modal');
    if (modal) modal.classList.remove('hidden');
}

function closeFieldModal() {
    const modal = document.getElementById('field-modal');
    if (modal) modal.classList.add('hidden');
}

function showUploadPage() {
    const uploadPage = document.getElementById('uploadPage');
    if (uploadPage) {
        uploadPage.classList.remove('hidden');
        uploadPage.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
}

function hideUploadPage() {
    const uploadPage = document.getElementById('uploadPage');
    if (uploadPage) uploadPage.classList.add('hidden');
}

function toggleRenameFolder() {
    const form = document.getElementById('renameFolderForm');
    if (form) form.classList.toggle('hidden');
}

function toggleActionMenu(event, fileId) {
    event.stopPropagation();

    document.querySelectorAll('.action-menu').forEach(menu => {
        if (menu.id !== 'action-menu-' + fileId) {
            menu.classList.add('hidden');
            menu.classList.remove('open-up');
        }
    });

    const menu = document.getElementById('action-menu-' + fileId);
    const button = event.currentTarget;

    if (!menu) return;

    const willOpen = menu.classList.contains('hidden');
    menu.classList.toggle('hidden');

    if (willOpen) positionMenuSmart(button, menu);
}

function toggleFolderTopMenu(event) {
    event.stopPropagation();

    const menu = document.getElementById('folder-top-action-menu');
    const button = event.currentTarget;

    document.querySelectorAll('.action-menu').forEach(item => {
        if (item.id !== 'folder-top-action-menu') {
            item.classList.add('hidden');
            item.classList.remove('open-up');
        }
    });

    if (!menu) return;

    const willOpen = menu.classList.contains('hidden');
    menu.classList.toggle('hidden');

    if (willOpen) positionMenuSmart(button, menu);
}

function closeFolderTopMenu() {
    const menu = document.getElementById('folder-top-action-menu');
    if (menu) {
        menu.classList.add('hidden');
        menu.classList.remove('open-up');
    }
}

function positionMenuSmart(toggleBtn, menu) {
    if (!toggleBtn || !menu) return;

    menu.classList.remove('open-up');
    menu.style.top = 'calc(100% + 6px)';
    menu.style.bottom = 'auto';

    const rect = toggleBtn.getBoundingClientRect();
    const viewportHeight = window.innerHeight;
    const estimatedMenuHeight = menu.offsetHeight || 160;
    const spaceBelow = viewportHeight - rect.bottom;
    const spaceAbove = rect.top;

    if (spaceBelow < estimatedMenuHeight && spaceAbove > estimatedMenuHeight) {
        menu.classList.add('open-up');
    }
}

function openEditModal(fileId) {
    const modal = document.getElementById('edit-modal-' + fileId);
    if (modal) modal.classList.remove('hidden');

    const menu = document.getElementById('action-menu-' + fileId);
    if (menu) menu.classList.add('hidden');
}

function closeEditModal(fileId) {
    const modal = document.getElementById('edit-modal-' + fileId);
    if (modal) modal.classList.add('hidden');
}

document.addEventListener('click', function () {
    document.querySelectorAll('.action-menu').forEach(menu => {
        menu.classList.add('hidden');
    });
});

document.addEventListener('keydown', function (event) {
    if (event.key === 'Escape') {
        document.querySelectorAll('.modal-backdrop').forEach(modal => {
            modal.classList.add('hidden');
        });
    }
});
</script>
</body>
</html>
