<?= $this->extend('layouts/admin') ?>

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

<!-- Add / Edit Form -->
<div class="mb-6">

  <!-- Form Card -->
  <div class="bg-white border border-gold/15 rounded-2xl p-5 md:p-6 shadow-sm">
    <h2 class="text-base font-bold text-charcoal mb-5 flex items-center gap-2" id="form-title">
      <i data-lucide="plus-circle" class="w-5 h-5 text-saffron"></i>
      Add New Service
    </h2>
    <form id="service-form" action="<?= base_url('admin/services/save') ?>" method="POST" enctype="multipart/form-data" class="flex flex-col gap-4">
      <input type="hidden" name="id" id="field-id" value="">

      <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div class="sm:col-span-2">
          <label class="block text-[0.75rem] uppercase font-semibold text-charcoal-light mb-1.5 tracking-wider">Service Title <span class="text-red-400">*</span></label>
          <input type="text" name="title" id="field-title" required placeholder="e.g. Premium Brahmin Weddings"
            class="w-full px-4 py-2.5 border border-gold/25 focus:border-saffron rounded-xl outline-none focus:ring-2 focus:ring-saffron/10 text-sm transition-all"/>
        </div>

        <div>
          <label class="block text-[0.75rem] uppercase font-semibold text-charcoal-light mb-1.5 tracking-wider">Subtitle / Category Tag</label>
          <input type="text" name="subtitle" id="field-subtitle" placeholder="e.g. Grand Celebrations"
            class="w-full px-4 py-2.5 border border-gold/25 focus:border-saffron rounded-xl outline-none focus:ring-2 focus:ring-saffron/10 text-sm transition-all"/>
        </div>

        <div>
          <label class="block text-[0.75rem] uppercase font-semibold text-charcoal-light mb-1.5 tracking-wider">Service Image</label>
          <div class="flex items-center gap-3">
            <div id="image-preview-wrapper" class="w-12 h-12 rounded-xl bg-gold-light border border-gold/20 overflow-hidden flex items-center justify-center flex-shrink-0">
              <img id="image-preview" src="" class="w-full h-full object-cover hidden">
              <i id="image-preview-placeholder" data-lucide="image" class="w-5 h-5 text-gold-dark"></i>
            </div>
            <div class="flex-grow">
              <input type="file" name="image" id="field-image" accept="image/*"
                class="w-full px-3 py-1.5 border border-gold/25 focus:border-saffron rounded-xl outline-none text-xs transition-all bg-white file:mr-3 file:py-1 file:px-3 file:rounded-lg file:border-0 file:text-xs file:font-semibold file:bg-saffron/10 file:text-saffron hover:file:bg-saffron/20"/>
              <input type="hidden" name="existing_image" id="field-existing_image" value="">
            </div>
          </div>
          <p class="text-[10px] text-charcoal-muted mt-1">Leaves existing image if empty.</p>
        </div>

        <div class="sm:col-span-2">
          <label class="block text-[0.75rem] uppercase font-semibold text-charcoal-light mb-1.5 tracking-wider">Description <span class="text-red-400">*</span></label>
          <textarea name="description" id="field-description" required rows="4" placeholder="Describe the service in detail..."
            class="w-full px-4 py-2.5 border border-gold/25 focus:border-saffron rounded-xl outline-none focus:ring-2 focus:ring-saffron/10 text-sm transition-all resize-y"></textarea>
        </div>

        <div class="sm:col-span-2">
          <label class="block text-[0.75rem] uppercase font-semibold text-charcoal-light mb-1.5 tracking-wider">Features (one per line)</label>
          <textarea name="features" id="field-features" rows="6"
            placeholder="Complete Muhurtham Setup&#10;Shastri Coordination&#10;Guest Hospitality"
            class="w-full px-4 py-2.5 border border-gold/25 focus:border-saffron rounded-xl outline-none focus:ring-2 focus:ring-saffron/10 text-sm transition-all resize-y font-mono"></textarea>
          <p class="text-[10px] text-charcoal-muted mt-1">Each line becomes a bullet point on the Services page</p>
        </div>

        <!-- sort_order input removed, auto-handled by reordering -->
      </div>

      <div class="flex gap-3 pt-2">
        <button type="submit" class="flex-1 sm:flex-none inline-flex items-center justify-center gap-2 bg-saffron hover:bg-saffron-dark text-white px-6 py-2.5 rounded-xl font-medium text-sm shadow-[0_4px_10px_rgba(227,30,36,0.15)] hover:-translate-y-0.5 transition-all duration-200">
          <i data-lucide="save" class="w-4 h-4"></i>
          <span id="submit-label">Add Service</span>
        </button>
        <button type="button" onclick="resetForm()" id="cancel-btn" class="hidden inline-flex items-center gap-2 bg-gray-100 hover:bg-gray-200 text-charcoal px-5 py-2.5 rounded-xl font-medium text-sm transition-all">
          <i data-lucide="x" class="w-4 h-4"></i>
          Cancel
        </button>
      </div>
    </form>
  </div>
</div>

<!-- Services List -->
<div class="bg-white border border-gold/15 rounded-2xl p-5 md:p-6 shadow-sm">
  <h2 class="text-base font-bold text-charcoal mb-5 flex items-center gap-2">
    <i data-lucide="briefcase" class="w-5 h-5 text-saffron"></i>
    All Services
    <span class="ml-auto text-xs font-normal text-charcoal-muted"><?= count($services) ?> total</span>
  </h2>

  <?php if (empty($services)): ?>
    <div class="text-center py-16 text-charcoal-muted font-light text-sm">
      <i data-lucide="inbox" class="w-10 h-10 mx-auto mb-3 opacity-30"></i>
      <p>No services yet. Add your first service above.</p>
    </div>
  <?php else: ?>
    <div id="services-sortable-list" class="flex flex-col gap-4">
      <?php foreach ($services as $s): ?>
        <?php $features = json_decode($s['features'] ?? '[]', true) ?: []; ?>
        <div data-id="<?= (int)$s['id'] ?>" class="border border-gold/10 hover:border-gold/30 rounded-xl p-4 md:p-5 transition-all bg-[#fdfcfa] hover:shadow-sm">
          <div class="flex items-start gap-3 md:gap-4">
            <!-- Reorder Controls -->
            <div class="flex flex-col items-center gap-1 flex-shrink-0 mr-1 border-r border-gold/10 pr-3">
              <button type="button" class="btn-move-up p-1 hover:bg-gold-light rounded text-gold-dark disabled:opacity-30 disabled:hover:bg-transparent" title="Move Up">
                <i data-lucide="arrow-up" class="w-4 h-4"></i>
              </button>
              <div class="cursor-grab active:cursor-grabbing p-1 hover:bg-gold-light rounded text-charcoal-muted drag-handle" title="Drag to Reorder">
                <i data-lucide="grip-vertical" class="w-4 h-4"></i>
              </div>
              <button type="button" class="btn-move-down p-1 hover:bg-gold-light rounded text-gold-dark disabled:opacity-30 disabled:hover:bg-transparent" title="Move Down">
                <i data-lucide="arrow-down" class="w-4 h-4"></i>
              </button>
            </div>
            <!-- Service Image -->
            <div class="w-16 h-12 rounded-xl bg-gold-light border border-gold/10 overflow-hidden flex-shrink-0 mt-0.5">
              <img src="<?= esc(filter_var($s['image_path'] ?? '', FILTER_VALIDATE_URL) ? $s['image_path'] : base_url($s['image_path'] ?? 'images/service-wedding.png')) ?>" class="w-full h-full object-cover">
            </div>
            <!-- Content -->
            <div class="flex-grow min-w-0">
              <div class="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-3 mb-1">
                <span class="text-[10px] font-bold uppercase tracking-widest text-gold-dark"><?= esc($s['subtitle']) ?></span>
              </div>
              <h3 class="font-semibold text-charcoal text-sm md:text-base leading-snug mb-1.5"><?= esc($s['title']) ?></h3>
              <p class="text-xs text-charcoal-light leading-relaxed line-clamp-2 mb-2"><?= esc($s['description']) ?></p>
              <?php if (!empty($features)): ?>
                <div class="flex flex-wrap gap-1.5">
                  <?php foreach (array_slice($features, 0, 4) as $f): ?>
                    <span class="text-[10px] px-2 py-0.5 rounded-full bg-gold-light text-gold-dark border border-gold/20"><?= esc($f) ?></span>
                  <?php endforeach; ?>
                  <?php if (count($features) > 4): ?>
                    <span class="text-[10px] px-2 py-0.5 rounded-full bg-gray-100 text-charcoal-muted">+<?= count($features) - 4 ?> more</span>
                  <?php endif; ?>
                </div>
              <?php endif; ?>
            </div>
            <!-- Actions -->
            <div class="flex flex-col sm:flex-row gap-2 flex-shrink-0">
              <button type="button"
                onclick="editService(<?= htmlspecialchars(json_encode($s), ENT_QUOTES) ?>)"
                class="inline-flex items-center gap-1.5 text-gold-dark hover:text-white hover:bg-gold border border-gold/40 hover:border-gold px-3 py-1.5 rounded-lg text-xs font-medium transition-all">
                <i data-lucide="pencil" class="w-3 h-3"></i>
                Edit
              </button>
              <button type="button"
                onclick="deleteService(<?= (int)$s['id'] ?>, '<?= base_url('admin/services/delete/' . (int)$s['id']) ?>')"
                style="cursor:pointer;"
                class="inline-flex items-center gap-1.5 text-red-500 hover:text-white hover:bg-red-500 border border-red-200 hover:border-red-500 px-3 py-1.5 rounded-lg text-xs font-medium transition-all">
                <i data-lucide="trash-2" class="w-3 h-3"></i>
                Delete
              </button>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</div>

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

<?= $this->section('admin_scripts') ?>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
  function editService(s) {
    document.getElementById('field-id').value          = s.id;
    document.getElementById('field-title').value       = s.title;
    document.getElementById('field-subtitle').value    = s.subtitle || '';
    document.getElementById('field-description').value = s.description || '';
    
    // Parse features JSON into newline-separated text
    var features = [];
    try { features = JSON.parse(s.features || '[]'); } catch(e) {}
    document.getElementById('field-features').value = features.join('\n');

    // Handle Image Preview
    document.getElementById('field-existing_image').value = s.image_path || '';
    var previewImg = document.getElementById('image-preview');
    var placeholder = document.getElementById('image-preview-placeholder');
    var imgUrl = s.image_path || '';
    if (imgUrl) {
      if (!imgUrl.startsWith('http://') && !imgUrl.startsWith('https://') && !imgUrl.startsWith('/')) {
        imgUrl = '<?= base_url() ?>/' + imgUrl;
      }
      previewImg.src = imgUrl;
      previewImg.classList.remove('hidden');
      placeholder.classList.add('hidden');
    } else {
      previewImg.src = '';
      previewImg.classList.add('hidden');
      placeholder.classList.remove('hidden');
    }

    document.getElementById('field-image').value = '';

    document.getElementById('form-title').innerHTML = '<i data-lucide="pencil" class="w-5 h-5 text-gold"></i> Edit Service: ' + s.title;
    document.getElementById('submit-label').textContent = 'Update Service';
    document.getElementById('cancel-btn').classList.remove('hidden');
    lucide.createIcons();

    // Scroll to form
    document.getElementById('service-form').scrollIntoView({ behavior: 'smooth', block: 'start' });
  }

  function resetForm() {
    document.getElementById('field-id').value          = '';
    document.getElementById('field-title').value       = '';
    document.getElementById('field-subtitle').value    = '';
    document.getElementById('field-description').value = '';
    document.getElementById('field-features').value   = '';
    document.getElementById('field-existing_image').value = '';
    document.getElementById('field-image').value = '';
    
    var previewImg = document.getElementById('image-preview');
    var placeholder = document.getElementById('image-preview-placeholder');
    previewImg.src = '';
    previewImg.classList.add('hidden');
    placeholder.classList.remove('hidden');

    document.getElementById('form-title').innerHTML = '<i data-lucide="plus-circle" class="w-5 h-5 text-saffron"></i> Add New Service';
    document.getElementById('submit-label').textContent = 'Add Service';
    document.getElementById('cancel-btn').classList.add('hidden');
    lucide.createIcons();
  }

  function deleteService(id, url) {
    if (!confirm('Delete this service? This cannot be undone.')) return;
    var form = document.createElement('form');
    form.method = 'POST';
    form.action = url;
    form.style.display = 'none';
    document.body.appendChild(form);
    form.submit();
  }

  // Handle Drag and Drop
  document.addEventListener('DOMContentLoaded', function() {
    var el = document.getElementById('services-sortable-list');
    if (el) {
      Sortable.create(el, {
        handle: '.drag-handle',
        animation: 150,
        onEnd: function() {
          updateAllOrders();
        }
      });
      updateArrowButtonsState();
    }
  });

  // Handle Move Up / Move Down Arrow Clicks
  document.addEventListener('click', function(e) {
    var btnUp = e.target.closest('.btn-move-up');
    if (btnUp && !btnUp.disabled) {
      var item = btnUp.closest('[data-id]');
      var prev = item.previousElementSibling;
      if (prev && prev.hasAttribute('data-id')) {
        item.parentNode.insertBefore(item, prev);
        updateAllOrders();
      }
    }
    
    var btnDown = e.target.closest('.btn-move-down');
    if (btnDown && !btnDown.disabled) {
      var item = btnDown.closest('[data-id]');
      var next = item.nextElementSibling;
      if (next && next.hasAttribute('data-id')) {
        item.parentNode.insertBefore(next, item);
        updateAllOrders();
      }
    }
  });

  function updateArrowButtonsState() {
    var items = document.querySelectorAll('#services-sortable-list [data-id]');
    items.forEach(function(item, index) {
      var btnUp = item.querySelector('.btn-move-up');
      var btnDown = item.querySelector('.btn-move-down');
      if (btnUp) btnUp.disabled = (index === 0);
      if (btnDown) btnDown.disabled = (index === items.length - 1);
    });
  }

  function updateAllOrders() {
    var items = document.querySelectorAll('#services-sortable-list [data-id]');
    var ids = [];
    items.forEach(function(item) {
      ids.push(item.getAttribute('data-id'));
    });
    
    updateArrowButtonsState();

    // Send AJAX to server to update sort orders
    var formData = new FormData();
    formData.append('ids', JSON.stringify(ids));

    fetch('<?= base_url('admin/services/reorder') ?>', {
      method: 'POST',
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      },
      body: formData
    })
    .then(response => response.json())
    .then(res => {
      if (!res.success) {
        console.error(res.message || 'Failed to update order');
      }
    })
    .catch(err => {
      console.error('Network error updating order:', err);
    });
  }
</script>
<?= $this->endSection() ?>
