<?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);

$workspace_type = $_SESSION['workspace_type'] ?? 'personal';
$active_company_id = isset($_SESSION['active_company_id']) && $_SESSION['active_company_id'] !== ''
    ? (int) $_SESSION['active_company_id']
    : null;

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

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];
    $originalHeight = (int) $imageInfo[1];

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

    switch ($mime) {
        case 'image/jpeg':
            $sourceImage = imagecreatefromjpeg($tmpPath);
            break;
        case 'image/png':
            $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);
    }

    imagecopyresampled(
        $resizedImage,
        $sourceImage,
        0,
        0,
        0,
        0,
        $newWidth,
        $newHeight,
        $originalWidth,
        $originalHeight
    );

    $saved = false;

    if ($mime === 'image/jpeg' || in_array(strtolower($extension), ['jpg', 'jpeg'], true)) {
        $saved = imagejpeg($resizedImage, $destinationPath, $jpgQuality);
    } elseif ($mime === 'image/png' || strtolower($extension) === 'png') {
        $saved = imagepng($resizedImage, $destinationPath, 7);
    }

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

    return $saved;
}

$message = "";
$message_color = "green";

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $form['category'] = trim($_POST['category'] ?? '');
    $form['document_name'] = trim($_POST['document_name'] ?? '');
    $form['document_number'] = trim($_POST['document_number'] ?? '');
    $form['issue_date'] = trim($_POST['issue_date'] ?? '');
    $form['expiry_date'] = trim($_POST['expiry_date'] ?? '');
    $form['issuer'] = trim($_POST['issuer'] ?? '');
    $form['status'] = trim($_POST['status'] ?? 'active');
    $form['note'] = trim($_POST['note'] ?? '');

    $category = $form['category'];
    $document_name = $form['document_name'];
    $document_number = $form['document_number'];
    $issuer = $form['issuer'];
    $status = strtolower($form['status']);
    $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 === '') {
        $message = "Please select 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_OK;

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

        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) {
                            error_log("Compression failed, fallback to normal upload: " . $original_file_name);
                            $save_success = move_uploaded_file($tmp_name, $full_file_path);
                        }

                        if (!$save_success) {
                            error_log("Image upload failed completely: " . $original_file_name);
                            $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) {
                            error_log("File upload failed: " . $original_file_name);
                            $message = "File upload failed.";
                            $message_color = "red";
                        }
                    }

                    if ($save_success) {
                        $size = filesize($full_file_path);
                        $final_file_size = ($size !== false) ? (int) $size : 0;
                    }
                }
            }
        }

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

            $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
            $stmt->bindValue(':car_id', null, PDO::PARAM_NULL);
            $stmt->bindValue(':folder_id', null, PDO::PARAM_NULL);

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

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

            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 ($issuer === '') {
                $stmt->bindValue(':issuer', null, PDO::PARAM_NULL);
            } else {
                $stmt->bindValue(':issuer', $issuer, PDO::PARAM_STR);
            }

            if ($status === '') {
                $stmt->bindValue(':status', 'active', PDO::PARAM_STR);
            } else {
                $stmt->bindValue(':status', $status, PDO::PARAM_STR);
            }

            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 ($note === '') {
                $stmt->bindValue(':note', null, PDO::PARAM_NULL);
            } else {
                $stmt->bindValue(':note', $note, PDO::PARAM_STR);
            }

            if ($stmt->execute()) {
                $message = "Document saved successfully.";
                $message_color = "green";

                $form = [
                    'category' => '',
                    'document_name' => '',
                    'document_number' => '',
                    'issue_date' => '',
                    'expiry_date' => '',
                    'issuer' => '',
                    'status' => 'active',
                    'note' => ''
                ];
            } else {
                if ($full_file_path !== null && file_exists($full_file_path)) {
                    unlink($full_file_path);
                }

                $message = "Database save failed.";
                $message_color = "red";
            }
        }
    }
}
?>
<!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-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;
        }

        .form-vertical {
            display: flex;
            flex-direction: column;
            gap: 18px;
            max-width: 700px;
        }
    </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 with or without a file.</p>
                    <div class="workspace-badge">
                        Viewing: <?php echo $is_company_workspace ? 'Company Workspace' : 'Personal Workspace'; ?>
                    </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">
                <div class="form-vertical">

                    <div class="form-group">
                        <label for="category">Category</label>
                        <select name="category" id="category" required>
                            <option value="">Select Category</option>
                            <option value="License" <?php echo ($form['category'] === 'License') ? 'selected' : ''; ?>>License</option>
                            <option value="Certificate" <?php echo ($form['category'] === 'Certificate') ? 'selected' : ''; ?>>Certificate</option>
                            <option value="Contract" <?php echo ($form['category'] === 'Contract') ? 'selected' : ''; ?>>Contract</option>
                            <option value="Legal Document" <?php echo ($form['category'] === 'Legal Document') ? 'selected' : ''; ?>>Legal Document</option>
                            <option value="Other" <?php echo ($form['category'] === 'Other') ? 'selected' : ''; ?>>Other</option>
                        </select>
                    </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>

                </div>

                <div class="page-actions">
                    <button type="submit" class="btn btn-primary">Upload Document</button>
                    <a href="documents.php" class="btn btn-secondary">Documents</a>
                    <a href="dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
                </div>
            </form>
        </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>