<?php
// components/forms/documents.php
$existingDocs = $existingDocs ?? []; // Fallback array if no records exist
$baseUploadPath = '../'; // Step out of the subfolder directory to hit project root
?>
<div class="bg-white border border-slate-300/80 rounded-xl shadow-sm overflow-hidden">
    <div class="px-4 py-3 bg-stone-50/50 border-b border-slate-300/80 flex items-center justify-between">
        <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">5. Compliance & Verification Documents</h3>
        <button type="button" onclick="addDocumentRow()" class="bg-white hover:bg-stone-100 border border-slate-300 text-slate-700 font-black text-[10px] px-3 py-1 rounded uppercase tracking-wider transition shadow-xs">
            ＋ Add Another Document
        </button>
    </div>

    <!-- Hidden tracking stack for engine deletions -->
    <div id="deletion-tracking-registry"></div>

    <div class="p-4 sm:p-5">
        <div id="document-repeater-container" class="space-y-4">
            
            <!-- Existing DB Records Section -->
            <?php foreach ($existingDocs as $doc): 
                $rawPath = ltrim($doc['file_path'], '/');
                
                // Prepend ../ if path isn't already formatted
                if (strpos($rawPath, '../') === 0) {
                    $fileUrl = htmlspecialchars($rawPath);
                } else {
                    $fileUrl = htmlspecialchars($baseUploadPath . $rawPath);
                }
                
                $isPdf = strtolower(pathinfo($fileUrl, PATHINFO_EXTENSION)) === 'pdf';
            ?>
                <div class="document-row grid grid-cols-1 md:grid-cols-3 gap-4 bg-stone-50/50 p-4 border border-slate-300 rounded relative items-start shadow-2xs" data-doc-id="<?= $doc['id'] ?>">
                    <div class="space-y-1.5">
                        <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Document Title / Type</label>
                        <input type="text" name="existing_docs[<?= $doc['id'] ?>][title]" value="<?= htmlspecialchars($doc['title']) ?>" class="w-full bg-white border border-slate-300 p-2 rounded text-xs font-bold text-slate-950 focus:outline-none focus:border-indigo-700 transition">
                    </div>
                    <div class="space-y-1.5">
                        <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Active Server Asset</label>
                        
                        <div class="preview-container relative w-fit border border-slate-300 bg-white p-1 rounded shadow-2xs">
                            <div class="relative inline-block group">
                                <a href="<?= $fileUrl ?>" target="_blank" class="block" title="Click to view file">
                                    <?php if ($isPdf): ?>
                                        <div class="w-16 h-16 flex flex-col items-center justify-center bg-stone-100 border border-slate-200 rounded text-center p-1 hover:bg-stone-200 transition">
                                            <span class="text-[9px] font-black text-rose-600 tracking-tighter uppercase">PDF</span>
                                            <span class="text-[7px] text-slate-500 font-medium truncate w-14 block">View file</span>
                                        </div>
                                    <?php else: ?>
                                        <img src="<?= $fileUrl ?>" class="w-16 h-16 object-cover rounded border border-slate-200 hover:opacity-80 transition">
                                    <?php endif; ?>
                                </a>
                            </div>
                        </div>
                    </div>
                    <div class="flex gap-2 items-start">
                        <div class="flex-1 space-y-1.5">
                            <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Expiry Date</label>
                            <input type="date" name="existing_docs[<?= $doc['id'] ?>][expiry]" value="<?= !empty($doc['expiry_date']) ? date('Y-m-d', strtotime($doc['expiry_date'])) : '' ?>" class="w-full bg-white border border-slate-300 p-2 rounded text-xs font-bold text-slate-950 focus:outline-none focus:border-indigo-700 transition">
                        </div>
                        <button type="button" onclick="removeExistingDocumentRow(this, <?= $doc['id'] ?>)" class="bg-white hover:bg-stone-50 border border-slate-300 text-rose-600 font-black text-[10px] p-2 rounded transition uppercase tracking-wider h-[34px] mt-5 flex items-center justify-center aspect-square" title="Delete Permanent Asset">
                            ✕
                        </button>
                    </div>
                </div>
            <?php endforeach; ?>

            <!-- Fallback: Standard empty placeholder row when no existing documents are present -->
            <?php if (empty($existingDocs)): ?>
                <div class="document-row grid grid-cols-1 md:grid-cols-3 gap-4 bg-stone-50/30 p-4 border border-slate-300 rounded relative items-start">
                    <div class="space-y-1.5">
                        <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Document Title / Type</label>
                        <input type="text" name="new_docs[0][title]" placeholder="e.g., NIN, Driver License, Contract" class="w-full bg-white border border-slate-300 p-2 rounded text-xs font-bold text-slate-950 focus:outline-none focus:border-indigo-700 transition">
                    </div>
                    <div class="space-y-1.5">
                        <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">File Upload (.pdf, images)</label>
                        <input type="file" name="new_doc_files[]" accept=".pdf,image/*" onchange="handleFilePreview(this)" class="w-full text-xs text-slate-500 file:mr-2 file:py-1 file:px-2.5 file:rounded file:border file:border-slate-300 file:text-[10px] file:font-black file:uppercase file:tracking-wider file:bg-white file:text-slate-700 hover:file:bg-stone-100 cursor-pointer pt-1 focus:outline-none">
                        <div class="preview-container mt-2 hidden relative w-fit border border-slate-300 bg-white p-1 rounded shadow-2xs"></div>
                    </div>
                    <div class="space-y-1.5">
                        <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Expiry Date <span class="text-slate-400 font-semibold lowercase tracking-normal">(optional)</span></label>
                        <input type="date" name="new_docs[0][expiry]" class="w-full bg-white border border-slate-300 p-2 rounded text-xs font-bold text-slate-950 focus:outline-none focus:border-indigo-700 transition">
                    </div>
                </div>
            <?php endif; ?>

        </div>
    </div>
</div>

<script>
let docIndex = <?= empty($existingDocs) ? 1 : 0 ?>;

function addDocumentRow() {
    const container = document.getElementById('document-repeater-container');
    const row = document.createElement('div');
    row.className = "document-row grid grid-cols-1 md:grid-cols-3 gap-4 bg-stone-50/30 p-4 border border-slate-300 rounded relative items-start transition-all duration-200 shadow-2xs";
    
    row.innerHTML = `
        <div class="space-y-1.5">
            <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Document Title / Type</label>
            <input type="text" name="new_docs[${docIndex}][title]" placeholder="e.g., Medical Certificate" class="w-full bg-white border border-slate-300 p-2 rounded text-xs font-bold text-slate-950 focus:outline-none focus:border-indigo-700 transition">
        </div>
        <div class="space-y-1.5">
            <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">File Upload (.pdf, images)</label>
            <input type="file" name="new_doc_files[]" accept=".pdf,image/*" onchange="handleFilePreview(this)" class="w-full text-xs text-slate-500 file:mr-2 file:py-1 file:px-2.5 file:rounded file:border file:border-slate-300 file:text-[10px] file:font-black file:uppercase file:tracking-wider file:bg-white file:text-slate-700 hover:file:bg-stone-100 cursor-pointer pt-1 focus:outline-none">
            <div class="preview-container mt-2 hidden relative w-fit border border-slate-300 bg-white p-1 rounded shadow-2xs"></div>
        </div>
        <div class="flex gap-2 items-start">
            <div class="flex-1 space-y-1.5">
                <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Expiry Date</label>
                <input type="date" name="new_docs[${docIndex}][expiry]" class="w-full bg-white border border-slate-300 p-2 rounded text-xs font-bold text-slate-950 focus:outline-none focus:border-indigo-700 transition">
            </div>
            <button type="button" onclick="this.closest('.document-row').remove()" class="bg-white hover:bg-stone-100 border border-slate-300 text-rose-600 font-black text-[10px] p-2 rounded transition uppercase tracking-wider h-[34px] mt-5 flex items-center justify-center aspect-square" title="Remove Document Row">
                ✕
            </button>
        </div>
    `;
    
    container.appendChild(row);
    docIndex++;
}

function handleFilePreview(input) {
    const container = input.nextElementSibling;
    if (!container) return;

    container.innerHTML = '';
    const file = input.files[0];

    if (!file) {
        container.classList.add('hidden');
        return;
    }

    container.classList.remove('hidden');
    const wrapper = document.createElement('div');
    wrapper.className = "relative inline-block group";

    if (file.type.startsWith('image/')) {
        const reader = new FileReader();
        reader.onload = function(e) {
            wrapper.innerHTML = `
                <img src="${e.target.result}" class="w-16 h-16 object-cover rounded border border-slate-200">
                <button type="button" onclick="clearSelectedFile(this)" class="absolute -top-1.5 -right-1.5 bg-rose-600 text-white font-black text-[8px] w-4 h-4 rounded-full flex items-center justify-center border border-white hover:bg-rose-700 shadow transition-all" title="Clear file">✕</button>
            `;
        }
        reader.readAsDataURL(file);
    } else if (file.type === 'application/pdf') {
        wrapper.innerHTML = `
            <div class="w-16 h-16 flex flex-col items-center justify-center bg-stone-100 border border-slate-200 rounded text-center p-1">
                <span class="text-[9px] font-black text-rose-600 tracking-tighter uppercase">PDF</span>
                <span class="text-[7px] text-slate-500 font-medium truncate w-14 block" title="${file.name}">${file.name}</span>
            </div>
            <button type="button" onclick="clearSelectedFile(this)" class="absolute -top-1.5 -right-1.5 bg-rose-600 text-white font-black text-[8px] w-4 h-4 rounded-full flex items-center justify-center border border-white hover:bg-rose-700 shadow transition-all" title="Clear file">✕</button>
        `;
    } else {
        container.classList.add('hidden');
    }
    container.appendChild(wrapper);
}

function clearSelectedFile(button) {
    const container = button.closest('.preview-container');
    const input = container.previousElementSibling;
    if (input && input.type === 'file') input.value = '';
    container.innerHTML = '';
    container.classList.add('hidden');
}

function removeExistingDocumentRow(button, docId) {
    if (confirm("Are you sure you want to delete this document from the file records permanently?")) {
        const targetContainer = document.getElementById('deletion-tracking-registry');
        
        const trackingInput = document.createElement('input');
        trackingInput.type = "hidden";
        trackingInput.name = "deleted_docs[]";
        trackingInput.value = docId;
        targetContainer.appendChild(trackingInput);
        
        button.closest('.document-row').remove();
    }
}
</script>