@extends('admin.layouts.app')

@section('title', 'Custom Fields Library')

@section('content')
<div class="content-header">
    <div>
        <h2 class="content-title">Custom Fields Library</h2>
        <p class="text-muted">Create and manage a central library of custom fields. Link these to subcategories later.</p>
    </div>
    <div>
        <button onclick="showAddFieldModal()" class="btn btn-primary">
            <i class="fas fa-plus"></i> Create New Field
        </button>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Field Name</th>
                        <th>Type</th>
                        <th>Options</th>
                        <th>Icon</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="fieldsTableBody">
                    <tr><td colspan="5" class="text-center">Loading library...</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add/Edit Field Modal -->
<div id="fieldModal" class="modal" style="display: none;">
    <div class="modal-content" style="max-width: 500px;">
        <div class="modal-header">
            <h3 id="modalTitle">Create New Field</h3>
            <span onclick="hideFieldModal()" style="cursor: pointer; font-size: 1.5rem;">&times;</span>
        </div>
        <div class="modal-body">
            <form id="fieldForm">
                <input type="hidden" id="fieldId" name="field_id">
                
                <div class="form-group">
                    <label>Field Name</label>
                    <input type="text" name="name" class="form-control" placeholder="e.g. Fuel Type" required>
                </div>

                <div class="form-group">
                    <label>Field Type</label>
                    <select name="type" class="form-control" onchange="toggleOptions(this.value)" required>
                        <option value="text">Text Input</option>
                        <option value="number">Number Input</option>
                        <option value="dropdown">Dropdown Selection</option>
                        <option value="radio">Radio Buttons</option>
                        <option value="checkbox">Checkbox (Multiple)</option>
                        <option value="date">Date Picker</option>
                    </select>
                </div>

                <div class="form-group" id="optionsContainer" style="display: none;">
                    <label>Options (Comma separated)</label>
                    <textarea name="options" class="form-control" placeholder="e.g. Petrol, Diesel, Electric"></textarea>
                    <small class="text-muted">Required for Dropdown, Radio, and Checkbox.</small>
                </div>

                <div class="form-group">
                    <label>Icon (Optional)</label>
                    <input type="text" name="icon" class="form-control" placeholder="e.g. ⛽ OR fa-gas-pump">
                </div>

                <div class="form-actions" style="margin-top: 20px; text-align: right;">
                    <button type="button" onclick="hideFieldModal()" class="btn btn-secondary">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Definition</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    let definitions = [];

    document.addEventListener('DOMContentLoaded', loadLibrary);

    async function loadLibrary() {
        try {
            const res = await fetch("{{ route('admin.global_fields.list') }}");
            definitions = await res.json();
            renderTable();
        } catch (e) {
            console.error(e);
            document.getElementById('fieldsTableBody').innerHTML = '<tr><td colspan="5" class="text-center text-danger">Failed to load library</td></tr>';
        }
    }

    function renderTable() {
        const tbody = document.getElementById('fieldsTableBody');
        tbody.innerHTML = '';
        
        if (definitions.length === 0) {
            tbody.innerHTML = '<tr><td colspan="5" class="text-center">No fields defined yet. Create one!</td></tr>';
            return;
        }

        definitions.forEach(field => {
            let optionsCount = '-';
            if (['dropdown', 'radio', 'checkbox'].includes(field.type) && field.options) {
                try {
                    const opts = JSON.parse(field.options);
                    optionsCount = Array.isArray(opts) ? opts.join(', ') : field.options;
                } catch(e) { optionsCount = field.options; }
            }

            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <span style="font-size: 1.2em;">${field.icon || '📝'}</span>
                        <strong>${field.name}</strong>
                    </div>
                </td>
                <td><span class="badge bg-info text-dark">${field.type.toUpperCase()}</span></td>
                <td><div style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${optionsCount}</div></td>
                <td>${field.icon || '-'}</td>
                <td>
                    <button onclick="editField(${field.id})" class="btn btn-sm btn-info text-white">Edit</button>
                    <button onclick="deleteField(${field.id})" class="btn btn-sm btn-danger">Delete</button>
                </td>
            `;
            tbody.appendChild(tr);
        });
    }

    function showAddFieldModal() {
        document.getElementById('fieldForm').reset();
        document.getElementById('fieldId').value = '';
        document.getElementById('modalTitle').textContent = 'Create New Field';
        document.getElementById('optionsContainer').style.display = 'none';
        document.getElementById('fieldModal').style.display = 'flex';
    }

    function hideFieldModal() {
        document.getElementById('fieldModal').style.display = 'none';
    }

    function toggleOptions(type) {
        document.getElementById('optionsContainer').style.display = 
            ['dropdown', 'radio', 'checkbox'].includes(type) ? 'block' : 'none';
    }

    function editField(id) {
        const field = definitions.find(d => d.id === id);
        if(!field) return;

        document.getElementById('fieldId').value = field.id;
        const form = document.getElementById('fieldForm');
        form.elements['name'].value = field.name;
        form.elements['type'].value = field.type;
        form.elements['icon'].value = field.icon || '';
        
        // Options
        toggleOptions(field.type);
        if (field.options) {
             try {
                const opts = JSON.parse(field.options);
                form.elements['options'].value = Array.isArray(opts) ? opts.join(', ') : field.options;
             } catch(e) {
                form.elements['options'].value = field.options;
             }
        }
        
        document.getElementById('modalTitle').textContent = 'Edit Field Definition';
        document.getElementById('fieldModal').style.display = 'flex';
    }

    document.getElementById('fieldForm').onsubmit = async function(e) {
        e.preventDefault();
        const id = document.getElementById('fieldId').value;
        const formData = new FormData(this);
        
        // Parse options to array if needed
        const type = formData.get('type');
        if(['dropdown', 'radio', 'checkbox'].includes(type)) {
            const rawOpts = formData.get('options');
            const optsArray = rawOpts.split(',').map(s => s.trim()).filter(s => s);
            // Append as array? Laravel expects array or we send JSON string?
            // FormData usually sends strings. Let's send index keys to simulate array
            formData.delete('options');
            optsArray.forEach((opt, i) => formData.append(`options[${i}]`, opt));
        } else {
            formData.delete('options'); // Clear options for non-option types
        }

        // Method spoofing
        if(id) formData.append('_method', 'PUT');

        const url = id ? `/admin/global-fields/${id}` : "{{ route('admin.global-fields.store') }}";
        
        try {
            const res = await fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json'
                },
                body: formData
            });
            
            if(res.ok) {
                hideFieldModal();
                loadLibrary();
                // alert('Saved!');
            } else {
                const json = await res.json();
                alert('Error: ' + (json.message || 'Failed'));
            }
        } catch(e) {
            console.error(e);
            alert('Error saving');
        }
    };

    async function deleteField(id) {
        if(!confirm('Delete this field definition? This will NOT remove it from existing ads but will un-link it.')) return;
        
        try {
            const res = await fetch(`/admin/global-fields/${id}`, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json'
                }
            });
            if(res.ok) loadLibrary();
        } catch(e) { alert('Delete failed'); }
    }
    
    // Auto-close modal on outside click
    window.onclick = function(e) {
        if (e.target == document.getElementById('fieldModal')) hideFieldModal();
    }
</script>

<style>
    .modal {
        position: fixed; top:0; left:0; width:100%; height:100%;
        background: rgba(0,0,0,0.5); z-index: 1000;
        align-items: center; justify-content: center;
    }
    .modal-content {
        background: white; padding: 20px; border-radius: 8px; width: 90%;
        animation: slideDown 0.3s;
    }
    @keyframes slideDown { from {transform: translateY(-20px); opacity:0;} to {transform: translateY(0); opacity:1;} }
    .form-group { margin-bottom: 15px; }
    .form-control { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
</style>
@endsection
