<?= $this->extend('layout/app') ?>

<?= $this->section('title') ?>Upload Document<?= $this->endSection() ?>
<?= $this->section('pageTitle') ?>Upload Document<?= $this->endSection() ?>

<?= $this->section('content') ?>

<?php if (isset($errors) && count($errors) > 0): ?>
    <div class="mb-6 fade-in max-w-3xl mx-auto">
        <div class="glass rounded-xl border border-red-200/70 bg-red-50/50 px-5 py-4">
            <div class="flex items-start gap-3">
                <div class="w-8 h-8 rounded-lg bg-red-100 flex items-center justify-center flex-shrink-0">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg>
                </div>
                <div class="flex-1">
                    <p class="text-sm font-semibold text-red-800 mb-1">Please fix the following errors:</p>
                    <ul class="text-sm text-red-700 space-y-0.5 list-disc list-inside">
                        <?php foreach ($errors as $error): ?>
                            <li><?= esc($error) ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<div class="max-w-3xl mx-auto">
    <div class="glass rounded-2xl border border-slate-200/70 shadow-sm p-8">
        <div class="mb-7 flex items-start gap-4">
            <div class="w-12 h-12 rounded-2xl bg-gradient-to-br from-emerald-500 to-teal-600 flex items-center justify-center shadow-lg shadow-emerald-500/25 flex-shrink-0">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" /></svg>
            </div>
            <div>
                <h3 class="font-bold text-slate-800 text-xl">Add New Document</h3>
                <p class="text-sm text-slate-500 mt-1">Upload a file or link content to your knowledge base. Text documents will be automatically processed for AI search.</p>
            </div>
        </div>

        <?= form_open_multipart(site_url('/admin/documents/store'), ['class' => 'space-y-5', 'id' => 'uploadForm']) ?>
        <?= csrf_field() ?>

        <div>
            <label class="block text-sm font-semibold text-slate-700 mb-1.5">
                Title <span class="text-red-500">*</span>
            </label>
            <div class="relative">
                <span class="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>
                </span>
                <input type="text" name="title" value="<?= old('title') ?>" placeholder="e.g. Product Pricing Guide 2026" class="w-full pl-10 pr-4 py-2.5 rounded-xl border border-slate-200 bg-white/70 focus:outline-none focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 text-sm transition">
            </div>
        </div>

        <div>
            <label class="block text-sm font-semibold text-slate-700 mb-1.5">Description</label>
            <textarea name="description" rows="3" placeholder="Brief summary of what this document contains..." class="w-full px-4 py-2.5 rounded-xl border border-slate-200 bg-white/70 focus:outline-none focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 text-sm transition resize-none"><?= old('description') ?></textarea>
        </div>

        <div>
            <label class="block text-sm font-semibold text-slate-700 mb-1.5">
                Category <span class="text-red-500">*</span>
            </label>
            <div class="relative">
                <span class="absolute left-3.5 top-[14px] text-slate-400 pointer-events-none">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" /></svg>
                </span>
                <select name="category_id" class="w-full pl-10 pr-4 py-2.5 rounded-xl border border-slate-200 bg-white/70 focus:outline-none focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 text-sm transition appearance-none cursor-pointer">
                    <option value="">Select a category...</option>
                    <?php foreach ($categories ?? [] as $cat): ?>
                        <option value="<?= esc($cat['id']) ?>" <?= old('category_id') == $cat['id'] ? 'selected' : '' ?>>
                            <?= esc($cat['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <span class="absolute right-3.5 top-[14px] text-slate-400 pointer-events-none">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" /></svg>
                </span>
            </div>
        </div>

        <div>
            <label class="block text-sm font-semibold text-slate-700 mb-3">
                Document Type <span class="text-red-500">*</span>
            </label>
            <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2.5" id="typeSelector">

                <label class="type-option cursor-pointer relative group">
                    <input type="radio" name="type" value="pdf" class="peer sr-only" <?= old('type') === 'pdf' ? 'checked' : '' ?>>
                    <div class="p-3.5 rounded-xl border-2 border-slate-200 bg-white/70 hover:border-red-300 hover:bg-red-50/50 transition-all text-center peer-checked:border-red-500 peer-checked:bg-red-50 peer-checked:shadow-md peer-checked:shadow-red-500/10">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 mx-auto text-red-500 mb-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" /></svg>
                        <span class="text-xs font-bold uppercase tracking-wide text-slate-700 peer-checked:text-red-700">PDF</span>
                    </div>
                </label>

                <label class="type-option cursor-pointer relative group">
                    <input type="radio" name="type" value="docx" class="peer sr-only" <?= old('type') === 'docx' ? 'checked' : '' ?>>
                    <div class="p-3.5 rounded-xl border-2 border-slate-200 bg-white/70 hover:border-blue-300 hover:bg-blue-50/50 transition-all text-center peer-checked:border-blue-500 peer-checked:bg-blue-50 peer-checked:shadow-md peer-checked:shadow-blue-500/10">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 mx-auto text-blue-500 mb-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>
                        <span class="text-xs font-bold uppercase tracking-wide text-slate-700 peer-checked:text-blue-700">DOCX</span>
                    </div>
                </label>

                <label class="type-option cursor-pointer relative group">
                    <input type="radio" name="type" value="txt" class="peer sr-only" <?= old('type') === 'txt' ? 'checked' : '' ?>>
                    <div class="p-3.5 rounded-xl border-2 border-slate-200 bg-white/70 hover:border-slate-400 hover:bg-slate-50/50 transition-all text-center peer-checked:border-slate-600 peer-checked:bg-slate-50 peer-checked:shadow-md peer-checked:shadow-slate-500/10">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 mx-auto text-slate-600 mb-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h7" /></svg>
                        <span class="text-xs font-bold uppercase tracking-wide text-slate-700 peer-checked:text-slate-800">TXT</span>
                    </div>
                </label>

                <label class="type-option cursor-pointer relative group">
                    <input type="radio" name="type" value="image" class="peer sr-only" <?= old('type') === 'image' ? 'checked' : '' ?>>
                    <div class="p-3.5 rounded-xl border-2 border-slate-200 bg-white/70 hover:border-pink-300 hover:bg-pink-50/50 transition-all text-center peer-checked:border-pink-500 peer-checked:bg-pink-50 peer-checked:shadow-md peer-checked:shadow-pink-500/10">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 mx-auto text-pink-500 mb-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" /></svg>
                        <span class="text-xs font-bold uppercase tracking-wide text-slate-700 peer-checked:text-pink-700">IMAGE</span>
                    </div>
                </label>

                <label class="type-option cursor-pointer relative group">
                    <input type="radio" name="type" value="video" class="peer sr-only" <?= old('type') === 'video' ? 'checked' : '' ?>>
                    <div class="p-3.5 rounded-xl border-2 border-slate-200 bg-white/70 hover:border-purple-300 hover:bg-purple-50/50 transition-all text-center peer-checked:border-purple-500 peer-checked:bg-purple-50 peer-checked:shadow-md peer-checked:shadow-purple-500/10">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 mx-auto text-purple-500 mb-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" /></svg>
                        <span class="text-xs font-bold uppercase tracking-wide text-slate-700 peer-checked:text-purple-700">VIDEO</span>
                    </div>
                </label>

                <label class="type-option cursor-pointer relative group">
                    <input type="radio" name="type" value="link" class="peer sr-only" <?= old('type') === 'link' ? 'checked' : '' ?>>
                    <div class="p-3.5 rounded-xl border-2 border-slate-200 bg-white/70 hover:border-amber-300 hover:bg-amber-50/50 transition-all text-center peer-checked:border-amber-500 peer-checked:bg-amber-50 peer-checked:shadow-md peer-checked:shadow-amber-500/10">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 mx-auto text-amber-500 mb-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" /></svg>
                        <span class="text-xs font-bold uppercase tracking-wide text-slate-700 peer-checked:text-amber-700">LINK</span>
                    </div>
                </label>

            </div>
        </div>

        <div id="urlField" class="hidden">
            <label class="block text-sm font-semibold text-slate-700 mb-1.5">
                URL <span class="text-red-500">*</span>
                <span class="text-xs font-normal text-slate-400 ml-1">(Image URL, Video URL, or Web Link)</span>
            </label>
            <div class="relative">
                <span class="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" /></svg>
                </span>
                <input type="url" name="url" id="urlInput" value="<?= old('url') ?>" placeholder="https://..." class="w-full pl-10 pr-4 py-2.5 rounded-xl border border-slate-200 bg-white/70 focus:outline-none focus:ring-2 focus:ring-amber-500/30 focus:border-amber-500 text-sm transition">
            </div>
        </div>

        <div id="fileField">
            <label class="block text-sm font-semibold text-slate-700 mb-1.5">
                File Upload <span class="text-red-500">*</span>
                <span class="text-xs font-normal text-slate-400 ml-1">(PDF, DOC, DOCX, TXT, Images, Video — Max 10MB)</span>
            </label>
            <label id="dropzone" class="flex flex-col items-center justify-center px-6 py-10 rounded-xl border-2 border-dashed border-slate-300 bg-white/50 hover:border-emerald-400 hover:bg-emerald-50/50 cursor-pointer transition-all group">
                <div class="w-14 h-14 rounded-2xl bg-emerald-50 group-hover:bg-emerald-100 flex items-center justify-center mb-3 transition">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-7 h-7 text-emerald-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" /></svg>
                </div>
                <p class="text-sm font-semibold text-slate-700 group-hover:text-emerald-700">Click to choose a file</p>
                <p class="text-xs text-slate-500 mt-1">or drag and drop. Max 10 MB per file.</p>
                <input type="file" name="document" id="fileInput" class="hidden" accept=".pdf,.doc,.docx,.txt,.csv,.png,.jpg,.jpeg,.gif,.webp,.mp4,.mov,.webm,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain,image/*,video/*">
            </label>
            <div id="fileNameDisplay" class="hidden mt-3 px-4 py-3 rounded-xl border border-slate-200 bg-white/70 flex items-center gap-3">
                <div class="w-8 h-8 rounded-lg bg-emerald-100 flex items-center justify-center flex-shrink-0">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-emerald-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" /></svg>
                </div>
                <div class="flex-1 min-w-0">
                    <p id="fileName" class="text-sm font-semibold text-slate-800 truncate"></p>
                    <p id="fileSize" class="text-xs text-slate-500"></p>
                </div>
                <button type="button" id="removeFileBtn" class="w-8 h-8 rounded-lg bg-slate-100 hover:bg-red-100 text-slate-600 hover:text-red-600 flex items-center justify-center transition">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" /></svg>
                </button>
            </div>
        </div>

        <div class="pt-5 flex flex-col sm:flex-row items-center gap-3 border-t border-slate-200/70">
            <button type="submit" class="w-full sm:w-auto px-8 py-2.5 rounded-xl bg-gradient-to-br from-emerald-500 to-teal-600 text-white text-sm font-semibold shadow-lg shadow-emerald-500/25 hover:shadow-xl hover:shadow-emerald-500/30 hover:-translate-y-0.5 active:translate-y-0 transition flex items-center justify-center gap-2">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.2"><path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" /></svg>
                Upload Document
            </button>
            <a href="<?= site_url('/admin/documents') ?>" class="w-full sm:w-auto px-6 py-2.5 rounded-xl border border-slate-200 bg-white/70 text-slate-700 text-sm font-semibold hover:bg-slate-50 transition flex items-center justify-center gap-2">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M10 19l-7-7m0 0l7-7m-7 7h18" /></svg>
                Cancel
            </a>
        </div>

        <?= form_close() ?>
    </div>
</div>

<script>
(function() {
    const typeRadios = document.querySelectorAll('input[name="type"]');
    const urlField = document.getElementById('urlField');
    const fileField = document.getElementById('fileField');
    const urlInput = document.getElementById('urlInput');
    const fileInput = document.getElementById('fileInput');
    const dropzone = document.getElementById('dropzone');
    const fileNameDisplay = document.getElementById('fileNameDisplay');
    const fileName = document.getElementById('fileName');
    const fileSize = document.getElementById('fileSize');
    const removeFileBtn = document.getElementById('removeFileBtn');
    const uploadForm = document.getElementById('uploadForm');

    function getSelectedType() {
        const checked = document.querySelector('input[name="type"]:checked');
        return checked ? checked.value : null;
    }

    function updateFields() {
        const type = getSelectedType();
        const urlTypes = ['image', 'video', 'link'];
        const fileTypes = ['pdf', 'docx', 'txt'];

        if (urlTypes.includes(type)) {
            urlField.classList.remove('hidden');
            fileField.classList.add('hidden');
            fileInput.value = '';
            fileNameDisplay.classList.add('hidden');
        } else if (fileTypes.includes(type)) {
            urlField.classList.add('hidden');
            fileField.classList.remove('hidden');
            if (urlInput) urlInput.value = '';
        } else {
            urlField.classList.add('hidden');
            fileField.classList.add('hidden');
        }
    }

    function formatSize(bytes) {
        if (bytes < 1024) return bytes + ' B';
        if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
        return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
    }

    typeRadios.forEach(r => r.addEventListener('change', updateFields));
    updateFields();

    dropzone.addEventListener('click', function(e) {
        if (e.target.tagName !== 'INPUT') fileInput.click();
    });

    dropzone.addEventListener('dragover', function(e) {
        e.preventDefault();
        dropzone.classList.add('border-emerald-500', 'bg-emerald-100/50');
    });

    dropzone.addEventListener('dragleave', function(e) {
        e.preventDefault();
        dropzone.classList.remove('border-emerald-500', 'bg-emerald-100/50');
    });

    dropzone.addEventListener('drop', function(e) {
        e.preventDefault();
        dropzone.classList.remove('border-emerald-500', 'bg-emerald-100/50');
        if (e.dataTransfer.files.length > 0) {
            fileInput.files = e.dataTransfer.files;
            showFile();
        }
    });

    fileInput.addEventListener('change', showFile);

    function showFile() {
        if (fileInput.files.length > 0) {
            const f = fileInput.files[0];
            fileName.textContent = f.name;
            fileSize.textContent = formatSize(f.size);
            fileNameDisplay.classList.remove('hidden');
        } else {
            fileNameDisplay.classList.add('hidden');
        }
    }

    removeFileBtn.addEventListener('click', function(e) {
        e.preventDefault();
        fileInput.value = '';
        fileNameDisplay.classList.add('hidden');
    });

    uploadForm.addEventListener('submit', function(e) {
        const type = getSelectedType();
        const fileTypes = ['pdf', 'docx', 'txt'];
        const urlTypes = ['image', 'video', 'link'];

        if (fileTypes.includes(type) && (fileInput.files.length === 0 || !fileInput.files[0])) {
            e.preventDefault();
            alert('Please select a file to upload for the chosen document type.');
            return;
        }

        if (urlTypes.includes(type)) {
            const url = urlInput.value.trim();
            if (!url) {
                e.preventDefault();
                alert('Please provide a URL for the chosen document type.');
                return;
            }
        }
    });
})();
</script>

<?= $this->endSection() ?>
