<?php $errors = session()->getFlashdata('errors') ?? []; ?>
<div class="space-y-6 max-w-4xl">
    <div class="flex items-center gap-3">
        <a href="<?= site_url('/admin/documents') ?>" class="p-2 rounded-xl bg-white border border-slate-200 text-slate-500 hover:text-slate-800 hover:bg-slate-50 transition">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" /></svg>
        </a>
        <div>
            <h3 class="text-lg font-bold text-slate-800">Upload Document</h3>
            <p class="text-sm text-slate-500">Add a new document to the knowledge base</p>
        </div>
    </div>

    <?php if (!empty($errors)): ?>
        <div class="glass rounded-2xl border border-red-200/70 bg-red-50/50 p-5">
            <ul class="list-disc list-inside text-sm text-red-700 space-y-0.5">
                <?php foreach ($errors as $e): ?><li><?= esc($e) ?></li><?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <div class="glass rounded-2xl p-6 sm:p-8 shadow-sm border border-slate-200/60">
        <?= form_open_multipart(site_url('/admin/documents/store'), ['class' => 'space-y-6', 'id' => 'uploadForm']) ?>
        <?= csrf_field() ?>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
            <div class="md:col-span-2">
                <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Title *</label>
                <input type="text" name="title" value="<?= old('title') ?>" class="w-full px-4 py-2.5 rounded-xl bg-white border border-slate-200 text-sm text-slate-800 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition" placeholder="e.g. Product Pricing Guide 2026">
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Category *</label>
                <div class="relative">
                    <select name="category_id" class="appearance-none w-full px-4 pr-10 py-2.5 rounded-xl bg-white border border-slate-200 text-sm text-slate-800 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition">
                        <option value="">Select Category</option>
                        <?php foreach ($categories ?? [] as $c): ?>
                            <option value="<?= esc($c['id']) ?>" <?= old('category_id') == $c['id'] ? 'selected' : '' ?>><?= esc($c['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-slate-500 absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none" 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>
                </div>
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Description</label>
                <input type="text" name="description" value="<?= old('description') ?>" class="w-full px-4 py-2.5 rounded-xl bg-white border border-slate-200 text-sm text-slate-800 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition" placeholder="Optional brief summary">
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Visibility</label>
                <div class="relative">
                    <select name="visibility" class="appearance-none w-full px-4 pr-10 py-2.5 rounded-xl bg-white border border-slate-200 text-sm text-slate-800 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition">
                        <option value="agents" <?= (old('visibility') ?? 'agents') === 'agents' ? 'selected' : '' ?>>Visible to Agents &amp; Admin</option>
                        <option value="private" <?= (old('visibility') ?? '') === 'private' ? 'selected' : '' ?>>Admin Only (Private)</option>
                    </select>
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-slate-500 absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none" 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>
                </div>
                <p class="mt-1.5 text-[11px] text-slate-400 leading-relaxed">
                    <span class="font-semibold">Agents</span> = agents can read &amp; chat with this document.
                    <span class="font-semibold ml-2">Admin Only</span> = hidden from agents entirely.
                </p>
            </div>
        </div>

        <div>
            <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-3">
                Document Type *
                <span class="font-normal normal-case tracking-normal text-slate-400 ml-2">auto-detected for URLs like YouTube / Vimeo / Imgur / MP4</span>
            </label>

            <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-3" id="typeSelector">

                <label class="relative group cursor-pointer select-none">
                    <input type="radio" name="type" value="pdf" class="peer sr-only" <?= old('type') === 'pdf' ? 'checked' : '' ?>>
                    <div class="h-full p-4 rounded-xl border-2 border-slate-200 bg-white hover:border-red-300 hover:bg-red-50/60 transition-all peer-checked:border-red-500 peer-checked:bg-red-50 peer-checked:shadow-md peer-checked:shadow-red-500/10 text-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-7 h-7 mx-auto text-red-500 mb-2" 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="relative group cursor-pointer select-none">
                    <input type="radio" name="type" value="docx" class="peer sr-only" <?= old('type') === 'docx' ? 'checked' : '' ?>>
                    <div class="h-full p-4 rounded-xl border-2 border-slate-200 bg-white hover:border-blue-300 hover:bg-blue-50/60 transition-all peer-checked:border-blue-500 peer-checked:bg-blue-50 peer-checked:shadow-md peer-checked:shadow-blue-500/10 text-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-7 h-7 mx-auto text-blue-500 mb-2" 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="relative group cursor-pointer select-none">
                    <input type="radio" name="type" value="txt" class="peer sr-only" <?= old('type') === 'txt' ? 'checked' : '' ?>>
                    <div class="h-full p-4 rounded-xl border-2 border-slate-200 bg-white hover:border-slate-400 hover:bg-slate-50/60 transition-all peer-checked:border-slate-600 peer-checked:bg-slate-50 peer-checked:shadow-md peer-checked:shadow-slate-500/10 text-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-7 h-7 mx-auto text-slate-600 mb-2" 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="relative group cursor-pointer select-none">
                    <input type="radio" name="type" value="image" class="peer sr-only" <?= old('type') === 'image' ? 'checked' : '' ?>>
                    <div class="h-full p-4 rounded-xl border-2 border-slate-200 bg-white hover:border-pink-300 hover:bg-pink-50/60 transition-all peer-checked:border-pink-500 peer-checked:bg-pink-50 peer-checked:shadow-md peer-checked:shadow-pink-500/10 text-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-7 h-7 mx-auto text-pink-500 mb-2" 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="relative group cursor-pointer select-none">
                    <input type="radio" name="type" value="video" class="peer sr-only" <?= old('type') === 'video' ? 'checked' : '' ?>>
                    <div class="h-full p-4 rounded-xl border-2 border-slate-200 bg-white hover:border-purple-300 hover:bg-purple-50/60 transition-all peer-checked:border-purple-500 peer-checked:bg-purple-50 peer-checked:shadow-md peer-checked:shadow-purple-500/10 text-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-7 h-7 mx-auto text-purple-500 mb-2" 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="relative group cursor-pointer select-none">
                    <input type="radio" name="type" value="link" class="peer sr-only" <?= old('type') === 'link' ? 'checked' : '' ?>>
                    <div class="h-full p-4 rounded-xl border-2 border-slate-200 bg-white hover:border-amber-300 hover:bg-amber-50/60 transition-all peer-checked:border-amber-500 peer-checked:bg-amber-50 peer-checked:shadow-md peer-checked:shadow-amber-500/10 text-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-7 h-7 mx-auto text-amber-500 mb-2" 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-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">
                URL *
                <span class="font-normal normal-case tracking-normal text-slate-400 ml-2">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-500 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="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://youtube.com/watch?v=...  or  https://example.com/article" class="w-full pl-10 pr-4 py-2.5 rounded-xl bg-white border border-slate-200 text-sm text-slate-800 focus:outline-none focus:ring-2 focus:ring-amber-500/30 focus:border-amber-500 transition">
            </div>
        </div>

        <div id="fileField">
            <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">
                Document File *
                <span class="font-normal normal-case tracking-normal text-slate-400 ml-2">PDF, DOC, DOCX, TXT, CSV, Images, Video — Max 10 MB</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-slate-50/50 hover:border-emerald-400 hover:bg-emerald-50/60 cursor-pointer transition-all group">
                <div class="w-14 h-14 rounded-2xl bg-white group-hover:bg-emerald-100 flex items-center justify-center mb-3 transition shadow-sm">
                    <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 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="flex items-center justify-end gap-3 pt-2">
            <a href="<?= site_url('/admin/documents') ?>" class="px-6 py-2.5 text-sm font-semibold text-slate-600 bg-white border border-slate-200 rounded-xl hover:bg-slate-50 transition">Cancel</a>
            <button type="submit" class="inline-flex items-center gap-2 px-7 py-2.5 bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-sm font-semibold rounded-xl shadow-md shadow-indigo-500/20 hover:shadow-lg hover:shadow-indigo-500/25 hover:-translate-y-0.5 active:translate-y-0 transition-all">
                <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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" /></svg>
                Upload Document
            </button>
        </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 c = document.querySelector('input[name="type"]:checked');
        return c ? c.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';
    }

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

    typeRadios.forEach(function(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);
    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;
            }
        }
    });

    urlInput && urlInput.addEventListener('input', function() {
        const raw = (urlInput.value || '').trim().toLowerCase();
        if (!raw) return;
        const imgExt  = ['jpg','jpeg','png','gif','webp','svg','bmp'];
        const vidExt  = ['mp4','mov','webm','avi','mkv','wmv'];
        const vidHosts = ['youtube.com','youtu.be','vimeo.com','dailymotion.com','tiktok.com'];
        const imgHosts = ['imgur.com','ibb.co','flickr.com','unsplash.com','pexels.com','pixabay.com'];
        let picked = null;
        try {
            const u = new URL(raw.startsWith('http') ? raw : 'https://' + raw);
            const host = u.hostname.replace(/^www\./, '');
            const lastDot = u.pathname.lastIndexOf('.');
            const ext = lastDot >= 0 ? u.pathname.substring(lastDot + 1) : '';
            if (vidHosts.some(function(h) { return host.includes(h); }) || vidExt.includes(ext)) picked = 'video';
            else if (imgHosts.some(function(h) { return host.includes(h); }) || imgExt.includes(ext)) picked = 'image';
        } catch (e) {}
        if (picked) {
            const target = document.querySelector('input[name="type"][value="' + picked + '"]');
            if (target && !target.checked) {
                target.checked = true;
                updateFields();
            }
        }
    });
})();
</script>
