<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

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

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

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

$user_id = (int)($_SESSION['user_id'] ?? 0);
$requested_company_id = (int)($_GET['company_id'] ?? $_POST['company_id'] ?? 0);
$workspace_type = $_GET['workspace'] ?? $_POST['workspace'] ?? ($_SESSION['workspace_type'] ?? 'personal');

$active_company_id = null;
$company_name = '';
$is_company_workspace = false;

if ($workspace_type === '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) {
        $is_company_workspace = true;
        $active_company_id = (int)$companyRow['id'];
        $company_name = trim((string)($companyRow['company_name'] ?? ''));
        $_SESSION['workspace_type'] = 'company';
    } else {
        $_SESSION['workspace_type'] = 'personal';
    }
} else {
    $_SESSION['workspace_type'] = 'personal';
}

$scope = $is_company_workspace ? 'company' : 'personal';
$workspace_label = $is_company_workspace
    ? ($company_name !== '' ? $company_name . ' (Company Workspace)' : 'Company Workspace')
    : 'Personal Workspace';

/*
|--------------------------------------------------------------------------
| Helpers
|--------------------------------------------------------------------------
*/
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 processAndSaveImage(
    string $tmpPath,
    string $destinationPath,
    string $extension,
    int $maxWidth = 1600,
    int $maxHeight = 1600,
    int $jpgQuality = 75
): bool {
    $imageInfo = @getimagesize($tmpPath);
    if (!$imageInfo) {
        return false;
    }

    $mime = $imageInfo['mime'] ?? '';
    $originalWidth = (int)($imageInfo[0] ?? 0);
    $originalHeight = (int)($imageInfo[1] ?? 0);

    if ($originalWidth <= 0 || $originalHeight <= 0) {
        return false;
    }

    $sourceImage = null;

    switch ($mime) {
        case 'image/jpeg':
            if (function_exists('imagecreatefromjpeg')) {
                $sourceImage = @imagecreatefromjpeg($tmpPath);
            }
            break;
        case 'image/png':
            if (function_exists('imagecreatefrompng')) {
                $sourceImage = @imagecreatefrompng($tmpPath);
            }
            break;
        default:
            return false;
    }

    if (!$sourceImage) {
        return false;
    }

    $scale = min($maxWidth / $originalWidth, $maxHeight / $originalHeight, 1);
    $newWidth = max(1, (int)round($originalWidth * $scale));
    $newHeight = max(1, (int)round($originalHeight * $scale));

    $resizedImage = imagecreatetruecolor($newWidth, $newHeight);
    if (!$resizedImage) {
        imagedestroy($sourceImage);
        return false;
    }

    if ($mime === 'image/png') {
        imagealphablending($resizedImage, false);
        imagesavealpha($resizedImage, true);
        $transparent = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127);
        imagefilledrectangle($resizedImage, 0, 0, $newWidth, $newHeight, $transparent);
    }

    if (!imagecopyresampled(
        $resizedImage,
        $sourceImage,
        0,
        0,
        0,
        0,
        $newWidth,
        $newHeight,
        $originalWidth,
        $originalHeight
    )) {
        imagedestroy($sourceImage);
        imagedestroy($resizedImage);
        return false;
    }

    $saved = false;
    $extension = strtolower($extension);

    if (in_array($extension, ['jpg', 'jpeg'], true) && function_exists('imagejpeg')) {
        $saved = @imagejpeg($resizedImage, $destinationPath, $jpgQuality);
    } elseif ($extension === 'png' && function_exists('imagepng')) {
        $saved = @imagepng($resizedImage, $destinationPath, 7);
    }

    imagedestroy($sourceImage);
    imagedestroy($resizedImage);

    return $saved && file_exists($destinationPath);
}

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 getCategoryNameById(PDO $db, int $category_id): ?string
{
    $stmt = $db->prepare("
        SELECT name
        FROM document_categories
        WHERE id = :id
        LIMIT 1
    ");
    $stmt->bindValue(':id', $category_id, PDO::PARAM_INT);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    return $row ? trim((string)$row['name']) : null;
}

function getCategoryIdByName(PDO $db, string $name): ?int
{
    $stmt = $db->prepare("
        SELECT id
        FROM document_categories
        WHERE name = :name
        LIMIT 1
    ");
    $stmt->bindValue(':name', $name, PDO::PARAM_STR);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    return $row ? (int)$row['id'] : null;
}

/*
|--------------------------------------------------------------------------
| Page state
|--------------------------------------------------------------------------
*/
$message = '';
$message_color = 'green';
$open_category_modal = false;

$form = [
    'category_id' => '',
    'document_name' => '',
    'document_number' => '',
    'issuer' => '',
    'status' => 'active',
    'issue_date' => '',
    'expiry_date' => '',
    'note' => ''
];

$modal_manage_category_id = '';
$modal_new_category = '';
$modal_edit_category_name = '';

/*
|--------------------------------------------------------------------------
| Handle category actions
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim($_POST['action'] ?? '');

    if (in_array($action, ['add_category', 'edit_category', 'delete_category'], true)) {
        $open_category_modal = true;
        $modal_manage_category_id = trim($_POST['manage_category_id'] ?? '');
        $modal_new_category = trim($_POST['new_category'] ?? '');
        $modal_edit_category_name = trim($_POST['edit_category_name'] ?? '');

        if ($action === 'add_category') {
            $new_category = $modal_new_category;

            if ($new_category === '') {
                $message = 'Please enter a category name.';
                $message_color = 'red';
            } else {
                $check = $db->prepare("
                    SELECT id
                    FROM document_categories
                    WHERE name = :name
                    LIMIT 1
                ");
                $check->bindValue(':name', $new_category, PDO::PARAM_STR);
                $check->execute();

                if ($check->fetch(PDO::FETCH_ASSOC)) {
                    $message = 'Category already exists.';
                    $message_color = 'red';
                } else {
                    $insert = $db->prepare("
                        INSERT INTO document_categories (name)
                        VALUES (:name)
                    ");
                    $insert->bindValue(':name', $new_category, PDO::PARAM_STR);

                    if ($insert->execute()) {
                        $message = 'Category added successfully.';
                        $message_color = 'green';

                        $newId = getCategoryIdByName($db, $new_category);
                        if ($newId !== null) {
                            $modal_manage_category_id = (string)$newId;
                            if ($form['category_id'] === '') {
                                $form['category_id'] = (string)$newId;
                            }
                        }

                        $modal_new_category = '';
                    } else {
                        $message = 'Failed to add category.';
                        $message_color = 'red';
                    }
                }
            }
        }

        if ($action === 'edit_category') {
            $category_id = (int)$modal_manage_category_id;
            $edit_category_name = $modal_edit_category_name;

            if ($category_id <= 0) {
                $message = 'Please select a category to rename.';
                $message_color = 'red';
            } elseif ($edit_category_name === '') {
                $message = 'Please enter a new category name.';
                $message_color = 'red';
            } else {
                $check = $db->prepare("
                    SELECT id
                    FROM document_categories
                    WHERE name = :name
                      AND id != :id
                    LIMIT 1
                ");
                $check->bindValue(':name', $edit_category_name, PDO::PARAM_STR);
                $check->bindValue(':id', $category_id, PDO::PARAM_INT);
                $check->execute();

                if ($check->fetch(PDO::FETCH_ASSOC)) {
                    $message = 'Another category with this name already exists.';
                    $message_color = 'red';
                } else {
                    $oldStmt = $db->prepare("
                        SELECT name
                        FROM document_categories
                        WHERE id = :id
                        LIMIT 1
                    ");
                    $oldStmt->bindValue(':id', $category_id, PDO::PARAM_INT);
                    $oldStmt->execute();
                    $oldRow = $oldStmt->fetch(PDO::FETCH_ASSOC);

                    if (!$oldRow) {
                        $message = 'Category not found.';
                        $message_color = 'red';
                    } else {
                        $old_name = trim((string)$oldRow['name']);

                        $db->beginTransaction();

                        try {
                            $updateCategory = $db->prepare("
                                UPDATE document_categories
                                SET name = :new_name
                                WHERE id = :id
                            ");
                            $updateCategory->bindValue(':new_name', $edit_category_name, PDO::PARAM_STR);
                            $updateCategory->bindValue(':id', $category_id, PDO::PARAM_INT);
                            $updateCategory->execute();

                            $updateDocuments = $db->prepare("
                                UPDATE documents
                                SET category = :new_name
                                WHERE category = :old_name
                            ");
                            $updateDocuments->bindValue(':new_name', $edit_category_name, PDO::PARAM_STR);
                            $updateDocuments->bindValue(':old_name', $old_name, PDO::PARAM_STR);
                            $updateDocuments->execute();

                            $db->commit();

                            $message = 'Category renamed successfully.';
                            $message_color = 'green';
                            $modal_edit_category_name = $edit_category_name;

                            if ($form['category_id'] === (string)$category_id) {
                                $form['category_id'] = (string)$category_id;
                            }
                        } catch (Exception $e) {
                            $db->rollBack();
                            $message = 'Failed to rename category.';
                            $message_color = 'red';
                        }
                    }
                }
            }
        }

        if ($action === 'delete_category') {
            $category_id = (int)$modal_manage_category_id;

            if ($category_id <= 0) {
                $message = 'Please select a category to delete.';
                $message_color = 'red';
            } else {
                $nameStmt = $db->prepare("
                    SELECT name
                    FROM document_categories
                    WHERE id = :id
                    LIMIT 1
                ");
                $nameStmt->bindValue(':id', $category_id, PDO::PARAM_INT);
                $nameStmt->execute();
                $categoryRow = $nameStmt->fetch(PDO::FETCH_ASSOC);

                if (!$categoryRow) {
                    $message = 'Category not found.';
                    $message_color = 'red';
                } else {
                    $category_name = trim((string)$categoryRow['name']);

                    $usageStmt = $db->prepare("
                        SELECT COUNT(*) AS total
                        FROM documents
                        WHERE category = :category
                    ");
                    $usageStmt->bindValue(':category', $category_name, PDO::PARAM_STR);
                    $usageStmt->execute();
                    $usage = (int)($usageStmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0);

                    if ($usage > 0) {
                        $message = 'Cannot delete this category because it is already used in documents.';
                        $message_color = 'red';
                    } else {
                        $deleteStmt = $db->prepare("
                            DELETE FROM document_categories
                            WHERE id = :id
                        ");
                        $deleteStmt->bindValue(':id', $category_id, PDO::PARAM_INT);

                        if ($deleteStmt->execute()) {
                            $message = 'Category deleted successfully.';
                            $message_color = 'green';

                            if ($form['category_id'] === (string)$category_id) {
                                $form['category_id'] = '';
                            }

                            $modal_manage_category_id = '';
                            $modal_edit_category_name = '';
                        } else {
                            $message = 'Failed to delete category.';
                            $message_color = 'red';
                        }
                    }
                }
            }
        }
    }
}

/*
|--------------------------------------------------------------------------
| Handle document upload
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim($_POST['action'] ?? '');

    if ($action === 'upload_document') {
        $form['category_id'] = trim($_POST['category_id'] ?? '');
        $form['document_name'] = trim($_POST['document_name'] ?? '');
        $form['document_number'] = trim($_POST['document_number'] ?? '');
        $form['issuer'] = trim($_POST['issuer'] ?? '');
        $form['status'] = trim($_POST['status'] ?? 'active');
        $form['issue_date'] = trim($_POST['issue_date'] ?? '');
        $form['expiry_date'] = trim($_POST['expiry_date'] ?? '');
        $form['note'] = trim($_POST['note'] ?? '');

        $category_id = (int)$form['category_id'];
        $category = $category_id > 0 ? getCategoryNameById($db, $category_id) : null;

        $document_name = $form['document_name'];
        $document_number = $form['document_number'];
        $issuer = $form['issuer'];
        $status = $form['status'] !== '' ? strtolower($form['status']) : 'active';
        $note = $form['note'];

        $issue_date_raw = $form['issue_date'];
        $expiry_date_raw = $form['expiry_date'];

        $issue_date = convertToSqlDate($issue_date_raw);
        $expiry_date = convertToSqlDate($expiry_date_raw);

        if ($category === null || $category === '') {
            $message = 'Please select a category.';
            $message_color = 'red';
        } elseif ($document_name === '') {
            $message = 'Please enter document name.';
            $message_color = 'red';
        } elseif ($issue_date_raw !== '' && $issue_date === null) {
            $message = 'Issue date is invalid. Please use dd/mm/yyyy.';
            $message_color = 'red';
        } elseif ($expiry_date_raw !== '' && $expiry_date === null) {
            $message = 'Expiry date is invalid. Please use dd/mm/yyyy.';
            $message_color = 'red';
        } else {
            $file = $_FILES['document_file'] ?? null;
            $hasFile = $file && ($file['name'] ?? '') !== '' && ($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_OK;

            $new_file_name = null;
            $original_file_name = null;
            $db_file_path = null;
            $ext = null;
            $final_file_size = 0;
            $full_file_path = null;
            $save_success = true;

            if ($hasFile) {
                $original_file_name = $file['name'] ?? '';
                $tmp_name = $file['tmp_name'] ?? '';

                $ext = strtolower(pathinfo($original_file_name, PATHINFO_EXTENSION));
                $allowed = ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx', 'xls', 'xlsx'];

                if (!in_array($ext, $allowed, true)) {
                    $message = 'Invalid file type. Only PDF, JPG, JPEG, PNG, DOC, DOCX, XLS, XLSX allowed.';
                    $message_color = 'red';
                    $save_success = false;
                } else {
                    $upload_dir = __DIR__ . '/uploads/';

                    if (!is_dir($upload_dir)) {
                        $message = 'Upload folder does not exist.';
                        $message_color = 'red';
                        $save_success = false;
                    } elseif (!is_writable($upload_dir)) {
                        $message = 'Upload folder is not writable.';
                        $message_color = 'red';
                        $save_success = false;
                    } else {
                        $new_file_name = time() . '_' . uniqid('', true) . '.' . $ext;
                        $full_file_path = $upload_dir . $new_file_name;
                        $db_file_path = 'uploads/' . $new_file_name;

                        if (in_array($ext, ['jpg', 'jpeg', 'png'], true)) {
                            $save_success = processAndSaveImage($tmp_name, $full_file_path, $ext, 1600, 1600, 75);

                            if (!$save_success) {
                                $save_success = move_uploaded_file($tmp_name, $full_file_path);
                            }

                            if (!$save_success) {
                                $message = 'Image upload failed. Please try another file.';
                                $message_color = 'red';
                            }
                        } else {
                            $save_success = move_uploaded_file($tmp_name, $full_file_path);

                            if (!$save_success) {
                                $message = 'File upload failed.';
                                $message_color = 'red';
                            }
                        }

                        if ($save_success) {
                            $final_file_size = filesize($full_file_path);
                            if ($final_file_size === false) {
                                $final_file_size = 0;
                            }
                        }
                    }
                }
            }

            if ($save_success) {
                $save_company_id = $is_company_workspace ? $active_company_id : null;

                $db->beginTransaction();

                try {
                    $stmt = $db->prepare("
                        INSERT INTO documents
(
    user_id,
    company_id,
    created_by,
    updated_by,
    car_id,
    category_id,
    category,
    custom_name,
    issuer,
    status,
    entity_type,
    file_name,
    original_file_name,
    file_path,
    file_type,
    file_size,
    document_number,
    issue_date,
    expiry_date,
    note
)
VALUES
(
    :user_id,
    :company_id,
    :created_by,
    :updated_by,
    :car_id,
    :category_id,
    :category,
    :custom_name,
    :issuer,
    :status,
    :entity_type,
    :file_name,
    :original_file_name,
    :file_path,
    :file_type,
    :file_size,
    :document_number,
    :issue_date,
    :expiry_date,
    :note
)
                    ");

                    $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);

                    if ($save_company_id === null) {
                        $stmt->bindValue(':company_id', null, PDO::PARAM_NULL);
                    } else {
                        $stmt->bindValue(':company_id', $save_company_id, PDO::PARAM_INT);
                    }

                    $stmt->bindValue(':created_by', $user_id, PDO::PARAM_INT);
                    $stmt->bindValue(':updated_by', $user_id, PDO::PARAM_INT);

                    $stmt->bindValue(':car_id', null, PDO::PARAM_NULL);
                    $stmt->bindValue(':category_id', $category_id, PDO::PARAM_INT);
                    $stmt->bindValue(':category', $category, PDO::PARAM_STR);
                    $stmt->bindValue(':custom_name', $document_name, PDO::PARAM_STR);

                    if ($issuer === '') {
                        $stmt->bindValue(':issuer', null, PDO::PARAM_NULL);
                    } else {
                        $stmt->bindValue(':issuer', $issuer, PDO::PARAM_STR);
                    }

                    $stmt->bindValue(':status', $status, PDO::PARAM_STR);
                    $stmt->bindValue(':entity_type', null, PDO::PARAM_NULL);

                    if ($new_file_name === null) {
                        $stmt->bindValue(':file_name', null, PDO::PARAM_NULL);
                    } else {
                        $stmt->bindValue(':file_name', $new_file_name, PDO::PARAM_STR);
                    }

                    if ($original_file_name === null) {
                        $stmt->bindValue(':original_file_name', null, PDO::PARAM_NULL);
                    } else {
                        $stmt->bindValue(':original_file_name', $original_file_name, PDO::PARAM_STR);
                    }

                    if ($db_file_path === null) {
                        $stmt->bindValue(':file_path', null, PDO::PARAM_NULL);
                    } else {
                        $stmt->bindValue(':file_path', $db_file_path, PDO::PARAM_STR);
                    }

                    if ($ext === null) {
                        $stmt->bindValue(':file_type', null, PDO::PARAM_NULL);
                    } else {
                        $stmt->bindValue(':file_type', $ext, PDO::PARAM_STR);
                    }

                    $stmt->bindValue(':file_size', $final_file_size, PDO::PARAM_INT);

                    if ($document_number === '') {
                        $stmt->bindValue(':document_number', null, PDO::PARAM_NULL);
                    } else {
                        $stmt->bindValue(':document_number', $document_number, PDO::PARAM_STR);
                    }

                    if ($issue_date === null) {
                        $stmt->bindValue(':issue_date', null, PDO::PARAM_NULL);
                    } else {
                        $stmt->bindValue(':issue_date', $issue_date, PDO::PARAM_STR);
                    }

                    if ($expiry_date === null) {
                        $stmt->bindValue(':expiry_date', null, PDO::PARAM_NULL);
                    } else {
                        $stmt->bindValue(':expiry_date', $expiry_date, PDO::PARAM_STR);
                    }

                    if ($note === '') {
                        $stmt->bindValue(':note', null, PDO::PARAM_NULL);
                    } else {
                        $stmt->bindValue(':note', $note, PDO::PARAM_STR);
                    }

                    $stmt->execute();

                    $document_id = (int)$db->lastInsertId();

                    if ($new_file_name !== null && $original_file_name !== null && $db_file_path !== null) {
                        $fileStmt = $db->prepare("
                            INSERT INTO document_files
                            (
                                document_id,
                                file_name,
                                original_file_name,
                                file_path,
                                file_type,
                                file_size,
                                is_main
                            )
                            VALUES
                            (
                                :document_id,
                                :file_name,
                                :original_file_name,
                                :file_path,
                                :file_type,
                                :file_size,
                                1
                            )
                        ");
                        $fileStmt->bindValue(':document_id', $document_id, PDO::PARAM_INT);
                        $fileStmt->bindValue(':file_name', $new_file_name, PDO::PARAM_STR);
                        $fileStmt->bindValue(':original_file_name', $original_file_name, PDO::PARAM_STR);
                        $fileStmt->bindValue(':file_path', $db_file_path, PDO::PARAM_STR);

                        if ($ext === null) {
                            $fileStmt->bindValue(':file_type', null, PDO::PARAM_NULL);
                        } else {
                            $fileStmt->bindValue(':file_type', $ext, PDO::PARAM_STR);
                        }

                        $fileStmt->bindValue(':file_size', $final_file_size, PDO::PARAM_INT);
                        $fileStmt->execute();
                    }

                    $db->commit();

                    $message = $is_company_workspace
                        ? 'Document uploaded to company workspace successfully.'
                        : 'Document uploaded to personal workspace successfully.';
                    $message_color = 'green';

                    $form = [
                        'category_id' => '',
                        'document_name' => '',
                        'document_number' => '',
                        'issuer' => '',
                        'status' => 'active',
                        'issue_date' => '',
                        'expiry_date' => '',
                        'note' => ''
                    ];
                }
                    catch (Exception $e) {
                        $db->rollBack();

                        if ($full_file_path !== null && file_exists($full_file_path)) {
                            @unlink($full_file_path);
                        }

                        $message = 'Database save failed: ' . $e->getMessage();
                        $message_color = 'red';
                    }
                                }
                        }
                    }
                    }

$categories = getCategories($db);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Document</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>
        .form-vertical {
            display: flex;
            flex-direction: column;
            gap: 18px;
            max-width: 700px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group label {
            font-weight: 600;
            margin-bottom: 8px;
            color: #344054;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px 14px;
            border: 1px solid #d0d5dd;
            border-radius: 12px;
            font-size: 14px;
            background: #fff;
            box-sizing: border-box;
        }

        .form-group textarea {
            min-height: 120px;
            resize: vertical;
        }

        .hint {
            color: #667085;
            font-size: 13px;
            margin-top: 6px;
        }

        .alert-box {
            padding: 14px 16px;
            border-radius: 14px;
            margin-bottom: 18px;
            font-weight: 600;
        }

        .alert-success {
            background: #ecfdf3;
            color: #027a48;
        }

        .alert-danger {
            background: #fef3f2;
            color: #b42318;
        }

        .page-actions {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 18px;
        }

        .workspace-badge {
            display: inline-flex;
            align-items: center;
            padding: 8px 12px;
            border-radius: 999px;
            font-size: 13px;
            font-weight: 700;
            background: #eff8ff;
            color: #175cd3;
            border: 1px solid #b2ddff;
            margin-top: 12px;
        }

        .category-inline {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .category-inline select {
            flex: 1;
        }

        .icon-btn {
            width: 44px;
            min-width: 44px;
            height: 44px;
            padding: 0;
            border-radius: 12px;
            font-size: 22px;
            line-height: 1;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }

        .modal-backdrop {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(15, 23, 42, 0.45);
            z-index: 999;
            padding: 20px;
        }

        .modal-backdrop.active {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-box {
            width: 100%;
            max-width: 560px;
            background: #fff;
            border-radius: 20px;
            padding: 24px;
            box-shadow: 0 24px 60px rgba(0, 0, 0, 0.18);
        }

        .modal-header {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            gap: 16px;
            margin-bottom: 20px;
        }

        .modal-title {
            font-size: 20px;
            font-weight: 700;
            margin: 0;
            color: #101828;
        }

        .modal-subtitle {
            margin: 6px 0 0;
            color: #667085;
            font-size: 14px;
        }

        .modal-close {
            width: 40px;
            min-width: 40px;
            height: 40px;
            border-radius: 10px;
            border: 1px solid #d0d5dd;
            background: #fff;
            font-size: 20px;
            cursor: pointer;
        }

        .modal-section {
            padding: 16px;
            border: 1px solid #eaecf0;
            border-radius: 16px;
            margin-bottom: 14px;
            background: #fcfcfd;
        }

        .modal-section label {
            display: block;
            font-weight: 600;
            color: #344054;
            margin-bottom: 8px;
        }

        .modal-actions-row {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 10px;
        }

        .modal-actions-row input {
            flex: 1;
            min-width: 220px;
        }

        .modal-footer {
            margin-top: 18px;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .danger-row {
            justify-content: space-between;
            align-items: center;
        }

        @media (max-width: 640px) {
            .category-inline {
                align-items: stretch;
            }

            .modal-box {
                padding: 18px;
            }

            .modal-actions-row {
                flex-direction: column;
            }

            .modal-actions-row input,
            .modal-actions-row button {
                width: 100%;
            }
        }
    </style>
</head>
<body>
<div class="layout">
    <?php include 'nav.php'; ?>

    <main class="main">
        <div class="hero">
            <div class="hero-top">
                <div>
                    <h1>Upload Document</h1>
                    <p>Add a new company document.</p>
                    <div class="workspace-badge">
                        Saving to: <?php echo htmlspecialchars($workspace_label); ?>
                    </div>
                </div>
                <div class="welcome-badge">
                    <?php echo htmlspecialchars($_SESSION['full_name'] ?? 'User'); ?>
                </div>
            </div>
        </div>

        <?php if ($message !== ''): ?>
            <div class="alert-box <?php echo $message_color === 'green' ? 'alert-success' : 'alert-danger'; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <div class="card">
            <div class="section-title">New Document</div>
            <div class="section-subtext">Fill in the details below. File upload is optional.</div>

            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="upload_document">
                <input type="hidden" name="workspace" value="<?php echo htmlspecialchars($scope); ?>">
                <input type="hidden" name="scope" value="<?php echo htmlspecialchars($scope); ?>">
                <?php if ($is_company_workspace && !empty($active_company_id)): ?>
                    <input type="hidden" name="company_id" value="<?php echo (int)$active_company_id; ?>">
                <?php endif; ?>

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

                            <button
                                type="button"
                                class="btn btn-secondary icon-btn"
                                id="openCategoryManager"
                                aria-label="Manage categories"
                                title="Manage categories"
                            >
                                ⋯
                            </button>
                        </div>
                        <div class="hint">Use the menu button to add, rename, or delete categories.</div>
                    </div>

                    <div class="form-group">
                        <label for="document_name">Document Name</label>
                        <input
                            type="text"
                            name="document_name"
                            id="document_name"
                            value="<?php echo htmlspecialchars($form['document_name']); ?>"
                            placeholder="Enter document name"
                            required
                        >
                    </div>

                    <div class="form-group">
                        <label for="document_number">Document Number</label>
                        <input
                            type="text"
                            name="document_number"
                            id="document_number"
                            value="<?php echo htmlspecialchars($form['document_number']); ?>"
                            placeholder="Enter document number"
                        >
                    </div>

                    <div class="form-group">
                        <label for="issue_date">Issue Date</label>
                        <input
                            type="text"
                            name="issue_date"
                            id="issue_date"
                            value="<?php echo htmlspecialchars($form['issue_date']); ?>"
                            placeholder="dd/mm/yyyy"
                        >
                        <div class="hint">Use Laos format: dd/mm/yyyy</div>
                    </div>

                    <div class="form-group">
                        <label for="expiry_date">Expiry Date</label>
                        <input
                            type="text"
                            name="expiry_date"
                            id="expiry_date"
                            value="<?php echo htmlspecialchars($form['expiry_date']); ?>"
                            placeholder="dd/mm/yyyy"
                        >
                        <div class="hint">Use Laos format: dd/mm/yyyy</div>
                    </div>

                    <div class="form-group">
                        <label for="issuer">Issuer</label>
                        <input
                            type="text"
                            name="issuer"
                            id="issuer"
                            value="<?php echo htmlspecialchars($form['issuer']); ?>"
                            placeholder="Enter issuer name"
                        >
                    </div>

                    <div class="form-group">
                        <label for="status">Status</label>
                        <select name="status" id="status">
                            <option value="active" <?php echo $form['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="pending" <?php echo $form['status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="expired" <?php echo $form['status'] === 'expired' ? 'selected' : ''; ?>>Expired</option>
                            <option value="cancelled" <?php echo $form['status'] === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="note">Note</label>
                        <textarea name="note" id="note"><?php echo htmlspecialchars($form['note']); ?></textarea>
                    </div>

                    <div class="form-group">
                        <label for="document_file">Select File</label>
                        <input type="file" name="document_file" id="document_file">
                        <div class="hint">Images are auto-resized and compressed before saving.</div>
                    </div>
                </div>

                <div class="page-actions">
                    <button type="submit" class="btn btn-primary">Upload Document</button>
                    <a href="my_documents.php?workspace=<?php echo htmlspecialchars($scope); ?>&scope=<?php echo htmlspecialchars($scope); ?>" class="btn btn-secondary">My Documents</a>
                    
                </div>
            </form>
        </div>
    </main>
</div>

<div class="modal-backdrop <?php echo $open_category_modal ? 'active' : ''; ?>" id="categoryModal">
    <div class="modal-box" role="dialog" aria-modal="true" aria-labelledby="categoryModalTitle">
        <div class="modal-header">
            <div>
                <h2 class="modal-title" id="categoryModalTitle">Manage Categories</h2>
                <p class="modal-subtitle">Add a new category, rename an existing one, or remove an unused category.</p>
            </div>
            <button type="button" class="modal-close" id="closeCategoryManager" aria-label="Close modal">×</button>
        </div>

        <form method="POST">
            <input type="hidden" name="workspace" value="<?php echo htmlspecialchars($scope); ?>">
            <input type="hidden" name="scope" value="<?php echo htmlspecialchars($scope); ?>">
            <?php if ($is_company_workspace && !empty($active_company_id)): ?>
                <input type="hidden" name="company_id" value="<?php echo (int)$active_company_id; ?>">
            <?php endif; ?>

            <div class="modal-section">
                <label for="manage_category_id">Selected Category</label>
                <select name="manage_category_id" id="manage_category_id">
                    <option value="">-- Select Category --</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo (int)$cat['id']; ?>"
                            <?php echo ((string)$modal_manage_category_id === (string)$cat['id']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($cat['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="modal-section">
                <label for="new_category">Add New Category</label>
                <div class="modal-actions-row">
                    <input
                        type="text"
                        name="new_category"
                        id="new_category"
                        value="<?php echo htmlspecialchars($modal_new_category); ?>"
                        placeholder="Type new category name"
                    >
                    <button type="submit" name="action" value="add_category" class="btn btn-secondary">
                        Add
                    </button>
                </div>
            </div>

            <div class="modal-section">
                <label for="edit_category_name">Rename Selected Category</label>
                <div class="modal-actions-row">
                    <input
                        type="text"
                        name="edit_category_name"
                        id="edit_category_name"
                        value="<?php echo htmlspecialchars($modal_edit_category_name); ?>"
                        placeholder="Type new category name"
                    >
                    <button type="submit" name="action" value="edit_category" class="btn btn-primary">
                        Rename
                    </button>
                </div>
            </div>

            <div class="modal-section">
                <label>Delete Selected Category</label>
                <div class="modal-actions-row danger-row">
                    <div class="hint" style="margin-top:0;">
                        Delete works only if no documents are using that category.
                    </div>
                    <button
                        type="submit"
                        name="action"
                        value="delete_category"
                        class="btn btn-danger"
                        onclick="return confirm('Are you sure you want to delete this category?');"
                    >
                        Delete
                    </button>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="closeCategoryManagerFooter">Close</button>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
    flatpickr("#issue_date", {
        dateFormat: "d/m/Y",
        allowInput: true
    });

    flatpickr("#expiry_date", {
        dateFormat: "d/m/Y",
        allowInput: true
    });

    const modal = document.getElementById("categoryModal");
    const openBtn = document.getElementById("openCategoryManager");
    const closeBtn = document.getElementById("closeCategoryManager");
    const closeBtnFooter = document.getElementById("closeCategoryManagerFooter");

    const uploadCategory = document.getElementById("category_id");
    const manageCategory = document.getElementById("manage_category_id");
    const renameInput = document.getElementById("edit_category_name");

    function openModal() {
        if (!modal) return;
        modal.classList.add("active");

        if (uploadCategory && manageCategory && !manageCategory.value) {
            manageCategory.value = uploadCategory.value;
        }

        if (manageCategory && renameInput && manageCategory.value) {
            const selectedText = manageCategory.options[manageCategory.selectedIndex]?.text || '';
            if (!renameInput.value) {
                renameInput.value = selectedText;
            }
        }
    }

    function closeModal() {
        if (!modal) return;
        modal.classList.remove("active");
    }

    if (openBtn) {
        openBtn.addEventListener("click", function () {
            if (uploadCategory && manageCategory) {
                manageCategory.value = uploadCategory.value;
                const selectedText = uploadCategory.options[uploadCategory.selectedIndex]?.text || '';
                if (renameInput) {
                    renameInput.value = selectedText && uploadCategory.value !== '' ? selectedText : '';
                }
            }
            openModal();
        });
    }

    if (closeBtn) {
        closeBtn.addEventListener("click", closeModal);
    }

    if (closeBtnFooter) {
        closeBtnFooter.addEventListener("click", closeModal);
    }

    if (modal) {
        modal.addEventListener("click", function (e) {
            if (e.target === modal) {
                closeModal();
            }
        });
    }

    if (manageCategory) {
        manageCategory.addEventListener("change", function () {
            const selectedText = this.options[this.selectedIndex]?.text || '';
            if (renameInput) {
                renameInput.value = this.value !== '' ? selectedText : '';
            }
        });
    }
});
</script>
</body>
</html>