<?php
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'] ?? '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'] ?? ''));
    }
}

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

$message = '';
$message_color = 'green';

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid document ID.");
}

$id = (int)$_GET['id'];

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);
    if ($dt) {
        return $dt->format('d/m/Y');
    }

    return '';
}

function formatDateForDisplay(?string $date): string
{
    return formatDateForInput($date);
}

function formatFileSize($bytes): string
{
    $bytes = (int)$bytes;

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

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

    return $bytes . ' B';
}

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 saveUploadedFile(array $file, string $uploadDir): array
{
    $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)) {
        return ['ok' => false, 'error' => 'Invalid file type.'];
    }

    $new_file_name = time() . "_" . uniqid() . "." . $ext;
    $full_file_path = $uploadDir . $new_file_name;
    $db_file_path = "uploads/" . $new_file_name;

    $success = false;

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

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

        if (!$success) {
            return ['ok' => false, 'error' => 'Image upload failed.'];
        }
    } else {
        $success = move_uploaded_file($tmp_name, $full_file_path);

        if (!$success) {
            return ['ok' => false, 'error' => 'File upload failed.'];
        }
    }

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

    return [
        'ok' => true,
        'file_name' => $new_file_name,
        'original_file_name' => $original_file_name,
        'file_path' => $db_file_path,
        'file_type' => $ext,
        'file_size' => $final_file_size,
        'full_path' => $full_file_path
    ];
}

function documentHasMainFile(PDO $db, int $documentId): bool
{
    $stmt = $db->prepare("
        SELECT id
        FROM document_files
        WHERE document_id = :document_id AND is_main = 1
        LIMIT 1
    ");
    $stmt->bindValue(':document_id', $documentId, PDO::PARAM_INT);
    $stmt->execute();

    return (bool)$stmt->fetch(PDO::FETCH_ASSOC);
}

function syncLegacyMainFileColumns(PDO $db, int $documentId): void
{
    $stmt = $db->prepare("
        SELECT file_name, original_file_name, file_path, file_type, file_size
        FROM document_files
        WHERE document_id = :document_id AND is_main = 1
        ORDER BY id DESC
        LIMIT 1
    ");
    $stmt->bindValue(':document_id', $documentId, PDO::PARAM_INT);
    $stmt->execute();

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

    $update = $db->prepare("
        UPDATE documents SET
            file_name = :file_name,
            original_file_name = :original_file_name,
            file_path = :file_path,
            file_type = :file_type,
            file_size = :file_size
        WHERE id = :id
    ");
    $update->bindValue(':id', $documentId, PDO::PARAM_INT);

    if ($main) {
        $update->bindValue(':file_name', $main['file_name'], PDO::PARAM_STR);
        $update->bindValue(':original_file_name', $main['original_file_name'], PDO::PARAM_STR);
        $update->bindValue(':file_path', $main['file_path'], PDO::PARAM_STR);
        $update->bindValue(':file_type', $main['file_type'], PDO::PARAM_STR);
        $update->bindValue(':file_size', (int)$main['file_size'], PDO::PARAM_INT);
    } else {
        $update->bindValue(':file_name', null, PDO::PARAM_NULL);
        $update->bindValue(':original_file_name', null, PDO::PARAM_NULL);
        $update->bindValue(':file_path', null, PDO::PARAM_NULL);
        $update->bindValue(':file_type', null, PDO::PARAM_NULL);
        $update->bindValue(':file_size', 0, PDO::PARAM_INT);
    }

    $update->execute();
}

function validateCarOwnership(PDO $db, ?int $carId, bool $isCompanyWorkspace, ?int $activeCompanyId, int $userId): bool
{
    if ($carId === null) {
        return true;
    }

    if ($isCompanyWorkspace) {
        $stmt = $db->prepare("
            SELECT id
            FROM cars
            WHERE id = :car_id
              AND company_id = :company_id
            LIMIT 1
        ");
        $stmt->bindValue(':car_id', $carId, PDO::PARAM_INT);
        $stmt->bindValue(':company_id', $activeCompanyId, PDO::PARAM_INT);
    } else {
        $stmt = $db->prepare("
            SELECT id
            FROM cars
            WHERE id = :car_id
              AND user_id = :user_id
              AND company_id IS NULL
            LIMIT 1
        ");
        $stmt->bindValue(':car_id', $carId, PDO::PARAM_INT);
        $stmt->bindValue(':user_id', $userId, PDO::PARAM_INT);
    }

    $stmt->execute();
    return (bool)$stmt->fetch(PDO::FETCH_ASSOC);
}

/*
|--------------------------------------------------------------------------
| Load document by active workspace
|--------------------------------------------------------------------------
*/
if ($is_company_workspace) {
    $stmt = $db->prepare("
        SELECT *
        FROM documents
        WHERE id = :id
          AND company_id = :company_id
        LIMIT 1
    ");
    $stmt->bindValue(':id', $id, PDO::PARAM_INT);
    $stmt->bindValue(':company_id', $active_company_id, PDO::PARAM_INT);
} else {
    $stmt = $db->prepare("
        SELECT *
        FROM documents
        WHERE id = :id
          AND user_id = :user_id
          AND company_id IS NULL
        LIMIT 1
    ");
    $stmt->bindValue(':id', $id, PDO::PARAM_INT);
    $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
}
$stmt->execute();
$document = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$document) {
    die("Document not found.");
}

/*
|--------------------------------------------------------------------------
| Load cars from current workspace
|--------------------------------------------------------------------------
*/
if ($is_company_workspace) {
    $carsStmt = $db->prepare("
        SELECT id, car_name, plate_number
        FROM cars
        WHERE company_id = :company_id
        ORDER BY car_name ASC
    ");
    $carsStmt->bindValue(':company_id', $active_company_id, PDO::PARAM_INT);
} else {
    $carsStmt = $db->prepare("
        SELECT id, car_name, plate_number
        FROM cars
        WHERE user_id = :user_id
          AND company_id IS NULL
        ORDER BY car_name ASC
    ");
    $carsStmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
}
$carsStmt->execute();
$cars = $carsStmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| Load categories
|--------------------------------------------------------------------------
*/
$categoriesStmt = $db->prepare("
    SELECT id, name
    FROM document_categories
    ORDER BY name ASC
");
$categoriesStmt->execute();
$categories = $categoriesStmt->fetchAll(PDO::FETCH_ASSOC);

$upload_dir = __DIR__ . "/uploads/";
if (!is_dir($upload_dir)) {
    die("Upload folder does not exist.");
}
if (!is_writable($upload_dir)) {
    die("Upload folder is not writable.");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'update_info';

    if ($action === 'update_info') {
        $category = trim($_POST['category'] ?? '');
        $new_category = trim($_POST['new_category'] ?? '');
        $car_id_raw = trim($_POST['car_id'] ?? '');
        $custom_name = trim($_POST['custom_name'] ?? '');
        $document_number = trim($_POST['document_number'] ?? '');
        $issuer = trim($_POST['issuer'] ?? '');
        $status = trim($_POST['status'] ?? 'active');
        $entity_type = trim($_POST['entity_type'] ?? '');
        $issue_date_raw = trim($_POST['issue_date'] ?? '');
        $expiry_date_raw = trim($_POST['expiry_date'] ?? '');
        $note = trim($_POST['note'] ?? '');

        if ($new_category !== '') {
            $category = $new_category;

            $checkCategory = $db->prepare("
                SELECT id
                FROM document_categories
                WHERE name = :name
                LIMIT 1
            ");
            $checkCategory->bindValue(':name', $category, PDO::PARAM_STR);
            $checkCategory->execute();

            if (!$checkCategory->fetch(PDO::FETCH_ASSOC)) {
                $insertCategory = $db->prepare("
                    INSERT INTO document_categories (name)
                    VALUES (:name)
                ");
                $insertCategory->bindValue(':name', $category, PDO::PARAM_STR);
                $insertCategory->execute();
            }
        }

        $car_id = ($car_id_raw !== '') ? (int)$car_id_raw : null;
        $issue_date = convertToSqlDate($issue_date_raw);
        $expiry_date = convertToSqlDate($expiry_date_raw);

        if ($category === '') {
            $message = "Category is required.";
            $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";
        } elseif (!validateCarOwnership($db, $car_id, $is_company_workspace, $active_company_id, $user_id)) {
            $message = "Selected car is not available in this workspace.";
            $message_color = "red";
        } else {
            if ($is_company_workspace) {
                $update = $db->prepare("
                    UPDATE documents SET
                        category = :category,
                        car_id = :car_id,
                        custom_name = :custom_name,
                        document_number = :document_number,
                        issuer = :issuer,
                        status = :status,
                        entity_type = :entity_type,
                        issue_date = :issue_date,
                        expiry_date = :expiry_date,
                        note = :note,
                        updated_by = :updated_by
                    WHERE id = :id
                      AND company_id = :company_id
                ");
                $update->bindValue(':company_id', $active_company_id, PDO::PARAM_INT);
            } else {
                $update = $db->prepare("
                    UPDATE documents SET
                        category = :category,
                        car_id = :car_id,
                        custom_name = :custom_name,
                        document_number = :document_number,
                        issuer = :issuer,
                        status = :status,
                        entity_type = :entity_type,
                        issue_date = :issue_date,
                        expiry_date = :expiry_date,
                        note = :note,
                        updated_by = :updated_by
                    WHERE id = :id
                      AND user_id = :user_id
                      AND company_id IS NULL
                ");
                $update->bindValue(':user_id', $user_id, PDO::PARAM_INT);
            }

            $update->bindValue(':category', $category, PDO::PARAM_STR);

            if ($car_id === null) {
                $update->bindValue(':car_id', null, PDO::PARAM_NULL);
            } else {
                $update->bindValue(':car_id', $car_id, PDO::PARAM_INT);
            }

            $update->bindValue(':custom_name', $custom_name !== '' ? $custom_name : null, $custom_name !== '' ? PDO::PARAM_STR : PDO::PARAM_NULL);
            $update->bindValue(':document_number', $document_number !== '' ? $document_number : null, $document_number !== '' ? PDO::PARAM_STR : PDO::PARAM_NULL);
            $update->bindValue(':issuer', $issuer !== '' ? $issuer : null, $issuer !== '' ? PDO::PARAM_STR : PDO::PARAM_NULL);
            $update->bindValue(':status', $status !== '' ? $status : 'active', PDO::PARAM_STR);
            $update->bindValue(':entity_type', $entity_type !== '' ? $entity_type : null, $entity_type !== '' ? PDO::PARAM_STR : PDO::PARAM_NULL);

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

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

            $update->bindValue(':note', $note !== '' ? $note : null, $note !== '' ? PDO::PARAM_STR : PDO::PARAM_NULL);
            $update->bindValue(':updated_by', $user_id, PDO::PARAM_INT);
            $update->bindValue(':id', $id, PDO::PARAM_INT);

            if ($update->execute()) {
                $message = "Document info updated successfully.";
                $message_color = "green";
            } else {
                $message = "Update failed.";
                $message_color = "red";
            }
        }
    }

    if ($action === 'upload_files') {
        if (!isset($_FILES['document_files'])) {
            $message = "Please choose file(s).";
            $message_color = "red";
        } else {
            $addedCount = 0;
            $failedCount = 0;

            $names = $_FILES['document_files']['name'] ?? [];
            $tmpNames = $_FILES['document_files']['tmp_name'] ?? [];
            $errors = $_FILES['document_files']['error'] ?? [];
            $sizes = $_FILES['document_files']['size'] ?? [];

            $hasMain = documentHasMainFile($db, $id);

            for ($i = 0; $i < count($names); $i++) {
                if (($errors[$i] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
                    $failedCount++;
                    continue;
                }

                $singleFile = [
                    'name' => $names[$i],
                    'tmp_name' => $tmpNames[$i],
                    'error' => $errors[$i],
                    'size' => $sizes[$i] ?? 0
                ];

                $saved = saveUploadedFile($singleFile, $upload_dir);

                if (!$saved['ok']) {
                    $failedCount++;
                    continue;
                }

                $isMain = $hasMain ? 0 : 1;

                $insertFile = $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,
                        :is_main
                    )
                ");

                $insertFile->bindValue(':document_id', $id, PDO::PARAM_INT);
                $insertFile->bindValue(':file_name', $saved['file_name'], PDO::PARAM_STR);
                $insertFile->bindValue(':original_file_name', $saved['original_file_name'], PDO::PARAM_STR);
                $insertFile->bindValue(':file_path', $saved['file_path'], PDO::PARAM_STR);
                $insertFile->bindValue(':file_type', $saved['file_type'], PDO::PARAM_STR);
                $insertFile->bindValue(':file_size', $saved['file_size'], PDO::PARAM_INT);
                $insertFile->bindValue(':is_main', $isMain, PDO::PARAM_INT);

                if ($insertFile->execute()) {
                    $addedCount++;
                    if (!$hasMain) {
                        $hasMain = true;
                    }
                } else {
                    if (is_file($saved['full_path'])) {
                        @unlink($saved['full_path']);
                    }
                    $failedCount++;
                }
            }

            syncLegacyMainFileColumns($db, $id);

            if ($addedCount > 0) {
                $message = "Uploaded {$addedCount} file(s)." . ($failedCount > 0 ? " Failed: {$failedCount}." : "");
                $message_color = "green";
            } else {
                $message = "No files were uploaded.";
                $message_color = "red";
            }
        }
    }

    if ($action === 'set_main_file') {
        $fileId = (int)($_POST['file_id'] ?? 0);

        $check = $db->prepare("
            SELECT *
            FROM document_files
            WHERE id = :file_id AND document_id = :document_id
            LIMIT 1
        ");
        $check->bindValue(':file_id', $fileId, PDO::PARAM_INT);
        $check->bindValue(':document_id', $id, PDO::PARAM_INT);
        $check->execute();

        $selectedFile = $check->fetch(PDO::FETCH_ASSOC);

        if (!$selectedFile) {
            $message = "File not found.";
            $message_color = "red";
        } else {
            $db->beginTransaction();

            try {
                $reset = $db->prepare("
                    UPDATE document_files
                    SET is_main = 0
                    WHERE document_id = :document_id
                ");
                $reset->bindValue(':document_id', $id, PDO::PARAM_INT);
                $reset->execute();

                $setMain = $db->prepare("
                    UPDATE document_files
                    SET is_main = 1
                    WHERE id = :file_id AND document_id = :document_id
                ");
                $setMain->bindValue(':file_id', $fileId, PDO::PARAM_INT);
                $setMain->bindValue(':document_id', $id, PDO::PARAM_INT);
                $setMain->execute();

                syncLegacyMainFileColumns($db, $id);

                $db->commit();
                $message = "Main file updated successfully.";
                $message_color = "green";
            } catch (Exception $e) {
                $db->rollBack();
                $message = "Failed to set main file.";
                $message_color = "red";
            }
        }
    }

    if ($action === 'delete_file') {
        $fileId = (int)($_POST['file_id'] ?? 0);

        $check = $db->prepare("
            SELECT *
            FROM document_files
            WHERE id = :file_id AND document_id = :document_id
            LIMIT 1
        ");
        $check->bindValue(':file_id', $fileId, PDO::PARAM_INT);
        $check->bindValue(':document_id', $id, PDO::PARAM_INT);
        $check->execute();

        $selectedFile = $check->fetch(PDO::FETCH_ASSOC);

        if (!$selectedFile) {
            $message = "File not found.";
            $message_color = "red";
        } else {
            $db->beginTransaction();

            try {
                $delete = $db->prepare("
                    DELETE FROM document_files
                    WHERE id = :file_id AND document_id = :document_id
                ");
                $delete->bindValue(':file_id', $fileId, PDO::PARAM_INT);
                $delete->bindValue(':document_id', $id, PDO::PARAM_INT);
                $delete->execute();

                if ((int)$selectedFile['is_main'] === 1) {
                    $promote = $db->prepare("
                        UPDATE document_files
                        SET is_main = 1
                        WHERE id = (
                            SELECT temp.id FROM (
                                SELECT id
                                FROM document_files
                                WHERE document_id = :document_id
                                ORDER BY id ASC
                                LIMIT 1
                            ) AS temp
                        )
                    ");
                    $promote->bindValue(':document_id', $id, PDO::PARAM_INT);
                    $promote->execute();
                }

                syncLegacyMainFileColumns($db, $id);

                $db->commit();

                if (!empty($selectedFile['file_path'])) {
                    $oldFullPath = __DIR__ . "/" . $selectedFile['file_path'];
                    if (is_file($oldFullPath)) {
                        @unlink($oldFullPath);
                    }
                }

                $message = "File deleted successfully.";
                $message_color = "green";
            } catch (Exception $e) {
                $db->rollBack();
                $message = "Delete failed.";
                $message_color = "red";
            }
        }
    }

    /*
    |--------------------------------------------------------------------------
    | Reload document after update
    |--------------------------------------------------------------------------
    */
    if ($is_company_workspace) {
        $stmt = $db->prepare("
            SELECT *
            FROM documents
            WHERE id = :id
              AND company_id = :company_id
            LIMIT 1
        ");
        $stmt->bindValue(':id', $id, PDO::PARAM_INT);
        $stmt->bindValue(':company_id', $active_company_id, PDO::PARAM_INT);
    } else {
        $stmt = $db->prepare("
            SELECT *
            FROM documents
            WHERE id = :id
              AND user_id = :user_id
              AND company_id IS NULL
            LIMIT 1
        ");
        $stmt->bindValue(':id', $id, PDO::PARAM_INT);
        $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
    }

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

$filesStmt = $db->prepare("
    SELECT *
    FROM document_files
    WHERE document_id = :document_id
    ORDER BY is_main DESC, id DESC
");
$filesStmt->bindValue(':document_id', $id, PDO::PARAM_INT);
$filesStmt->execute();
$documentFiles = $filesStmt->fetchAll(PDO::FETCH_ASSOC);

$issue_date_value = formatDateForInput($document['issue_date'] ?? '');
$expiry_date_value = formatDateForInput($document['expiry_date'] ?? '');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit 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-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
        gap: 16px;
        width: 100%;
    }

    .form-group {
        display: flex;
        flex-direction: column;
        width: 100%;
        min-width: 0;
    }

    .form-group.full {
        grid-column: 1 / -1;
    }

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

    .form-group input,
    .form-group select,
    .form-group textarea {
        width: 100%;
        max-width: 100%;
        min-width: 0;
        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;
    }

    .info-strip {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        margin-top: 14px;
    }

    .info-chip {
        padding: 8px 12px;
        border-radius: 999px;
        background: #f2f4f7;
        color: #344054;
        font-size: 13px;
    }

    .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;
    }

    .table-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
    }

    .inline-form {
        display: inline-block;
        margin: 0;
    }

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

    .file-main-badge {
        display: inline-block;
        padding: 6px 10px;
        border-radius: 999px;
        background: #ecfdf3;
        color: #027a48;
        font-weight: 700;
        font-size: 12px;
    }

    .file-extra-badge {
        display: inline-block;
        padding: 6px 10px;
        border-radius: 999px;
        background: #f2f4f7;
        color: #475467;
        font-weight: 700;
        font-size: 12px;
    }

    .current-file-box {
        padding: 14px;
        border: 1px solid #eaecf0;
        border-radius: 14px;
        background: #f9fafb;
        margin-bottom: 18px;
        overflow-wrap: anywhere;
    }

    .main,
    .card,
    .hero,
    .table-wrap {
        min-width: 0;
    }

    .table-wrap {
        width: 100%;
        overflow-x: auto;
    }

    .admin-table {
        width: 100%;
        min-width: 900px;
    }

    @media (max-width: 768px) {
        .table-actions,
        .page-actions {
            flex-direction: column;
            align-items: stretch;
        }

        .table-actions .btn,
        .table-actions form,
        .page-actions .btn {
            width: 100%;
        }
    }
    </style>
</head>
<body>
<div class="layout">
    <?php include 'nav.php'; ?>

    <main class="main">
        <div class="hero">
            <div class="hero-top">
                <div>
                    <h1>Edit Document</h1>
                    <p>Update document details, manage files, and choose the main file.</p>
                    <div class="workspace-badge">
                        Editing in: <?php echo htmlspecialchars($workspace_label); ?>
                    </div>
                </div>
                <div class="welcome-badge">
                    #<?php echo (int)$document['id']; ?>
                </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">Update Document Info</div>
            <div class="section-subtext">
                Edit the main information for this document record.
            </div>

            <form method="POST">
                <input type="hidden" name="action" value="update_info">
                <input type="hidden" name="workspace" value="<?php echo htmlspecialchars($scope); ?>">
                <input type="hidden" name="scope" value="<?php echo htmlspecialchars($scope); ?>">

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

                        <input
                            type="text"
                            name="new_category"
                            id="new_category"
                            value=""
                            placeholder="Or type a new category"
                            style="margin-top:10px;"
                        >
                        <div class="hint">Select a category or type a new one</div>
                    </div>

                    <div class="form-group">
                        <label for="car_id">Attach to Car (optional)</label>
                        <select name="car_id" id="car_id">
                            <option value="">-- No Car --</option>
                            <?php foreach ($cars as $car): ?>
                                <option value="<?php echo (int)$car['id']; ?>"
                                    <?php echo ((string)($document['car_id'] ?? '') === (string)$car['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($car['car_name'] . (!empty($car['plate_number']) ? ' (' . $car['plate_number'] . ')' : '')); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="custom_name">Custom Name</label>
                        <input type="text" name="custom_name" id="custom_name"
                            value="<?php echo htmlspecialchars($document['custom_name'] ?? ''); ?>">
                    </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($document['document_number'] ?? ''); ?>">
                    </div>

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

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

                    <div class="form-group">
                        <label for="entity_type">Entity Type</label>
                        <select name="entity_type" id="entity_type">
                            <?php $currentEntityType = trim((string)($document['entity_type'] ?? '')); ?>
                            <option value="">-- None --</option>
                            <option value="personal" <?php echo $currentEntityType === 'personal' ? 'selected' : ''; ?>>Personal</option>
                            <option value="car" <?php echo $currentEntityType === 'car' ? 'selected' : ''; ?>>Car</option>
                            <option value="company" <?php echo $currentEntityType === 'company' ? 'selected' : ''; ?>>Company</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="issue_date">Issue Date</label>
                        <input type="text" id="issue_date" name="issue_date"
                            value="<?php echo htmlspecialchars($issue_date_value); ?>"
                            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" id="expiry_date" name="expiry_date"
                            value="<?php echo htmlspecialchars($expiry_date_value); ?>"
                            placeholder="dd/mm/yyyy">
                        <div class="hint">Use Laos format: dd/mm/yyyy</div>
                    </div>

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

                <div class="page-actions" style="margin-top:18px;">
                    <button type="submit" class="btn btn-primary">Update Document</button>
                    href="my_documents.php?workspace=<?php echo htmlspecialchars($scope); ?>&scope=<?php echo htmlspecialchars($scope); ?><?php echo ($is_company_workspace && !empty($active_company_id)) ? '&company_id=' . (int)$active_company_id : ''; ?>"
                    class="btn btn-secondary">Back to My Documents</a>
                </div>
            </form>

            <div class="info-strip">
                <div class="info-chip">Issue Date: <?php echo htmlspecialchars(formatDateForDisplay($document['issue_date'] ?? '')); ?></div>
                <div class="info-chip">Expiry Date: <?php echo htmlspecialchars(formatDateForDisplay($document['expiry_date'] ?? '')); ?></div>
            </div>
        </div>

        <div class="card">
            <div class="section-title">Document Files</div>
            <div class="section-subtext">Upload new files, set the main file, or delete extras.</div>

            <?php if (!empty($document['file_path'])): ?>
                <div class="current-file-box">
                    <strong>Current main file:</strong>
                    <a href="<?php echo htmlspecialchars($document['file_path']); ?>" target="_blank">
                        <?php echo htmlspecialchars($document['original_file_name'] ?? 'Open file'); ?>
                    </a>
                    <span class="muted">(<?php echo htmlspecialchars(formatFileSize($document['file_size'] ?? 0)); ?>)</span>
                </div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="upload_files">
                <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-grid">
                    <div class="form-group full">
                        <label for="document_files">Choose File(s)</label>
                        <input type="file" name="document_files[]" id="document_files" multiple required>
                        <div class="hint">Images try compression first. If compression fails, normal upload is used.</div>
                    </div>
                </div>

                <button type="submit" class="btn btn-primary">Upload Files</button>
            </form>
        </div>

        <div class="card">
            <div class="section-title">File List</div>
            <div class="section-subtext">Manage all files attached to this document.</div>

            <div class="table-wrap">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Type</th>
                            <th>File Name</th>
                            <th>File Type</th>
                            <th>Size</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($documentFiles) > 0): ?>
                            <?php foreach ($documentFiles as $file): ?>
                                <tr>
                                    <td><span class="chip">#<?php echo (int)$file['id']; ?></span></td>
                                    <td>
                                        <?php if ((int)($file['is_main'] ?? 0) === 1): ?>
                                            <span class="file-main-badge">Main</span>
                                        <?php else: ?>
                                            <span class="file-extra-badge">Extra</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($file['original_file_name']); ?></td>
                                    <td><?php echo htmlspecialchars(strtoupper($file['file_type'])); ?></td>
                                    <td><?php echo htmlspecialchars(formatFileSize($file['file_size'] ?? 0)); ?></td>
                                    <td>
                                        <div class="table-actions">
                                            <a class="btn btn-secondary btn-sm" href="<?php echo htmlspecialchars($file['file_path']); ?>" target="_blank">View</a>

                                            <?php if ((int)($file['is_main'] ?? 0) !== 1): ?>
                                                <form method="POST" class="inline-form">
                                                    <input type="hidden" name="action" value="set_main_file">
                                                    <input type="hidden" name="workspace" value="<?php echo htmlspecialchars($scope); ?>">
                                                    <input type="hidden" name="scope" value="<?php echo htmlspecialchars($scope); ?>">
                                                    <input type="hidden" name="file_id" value="<?php echo (int)$file['id']; ?>">
                                                    <button type="submit" class="btn btn-success btn-sm">Set Main</button>
                                                </form>
                                            <?php endif; ?>

                                            <form method="POST" class="inline-form" onsubmit="return confirm('Delete this file?');">
                                                <input type="hidden" name="action" value="delete_file">
                                                <input type="hidden" name="workspace" value="<?php echo htmlspecialchars($scope); ?>">
                                                <input type="hidden" name="scope" value="<?php echo htmlspecialchars($scope); ?>">
                                                <input type="hidden" name="file_id" value="<?php echo (int)$file['id']; ?>">
                                                <button type="submit" class="btn btn-danger btn-sm">Delete</button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6">
                                    <div class="empty-state">No files uploaded yet.</div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>

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

    flatpickr("#expiry_date", {
        dateFormat: "d/m/Y",
        allowInput: true
    });
});
</script>
</body>
</html>