<?php
session_start();
if (!isset($_SESSION['loggedin'])) {
    header("Location: index.php");
    exit();
}

$jsonFile = '../js/urls.json';
$banners = json_decode(file_get_contents($jsonFile), true);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_banner'])) {
        // Add new banner
        $newBanner = [
            'src' => $_POST['new_src'],
            'alt' => $_POST['new_alt']
        ];
        $banners['carouselImages'][] = $newBanner;
    } elseif (isset($_POST['update_banners'])) {
        // Update existing banners
        $updatedBanners = [];
        foreach ($_POST['src'] as $index => $src) {
            $updatedBanners[] = [
                'src' => $src,
                'alt' => $_POST['alt'][$index]
            ];
        }
        $banners['carouselImages'] = $updatedBanners;
    } elseif (isset($_POST['delete_banner'])) {
        // Delete a banner
        $index = $_POST['delete_index'];
        array_splice($banners['carouselImages'], $index, 1);
    }

    // Save changes to JSON file
    file_put_contents($jsonFile, json_encode($banners, JSON_PRETTY_PRINT));
    header("Location: change_banner.php");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Manage Banners</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
  <style>
    body {
      font-family: 'Inter', sans-serif;
      background: linear-gradient(135deg, #0f172a, #1e293b);
      min-height: 100vh;
    }
    .glass-card {
      background: rgba(30, 41, 59, 0.6);
      backdrop-filter: blur(15px);
      border: 1px solid rgba(255, 255, 255, 0.1);
    }
    .banner-preview {
      height: 200px;
      object-fit: cover;
    }
    .drag-handle {
      cursor: move;
    }
    .sortable-ghost {
      opacity: 0.5;
      background: #334155;
    }
  </style>
</head>
<body class="text-white">
<div x-data="{
    menuOpen: false,
    newBanner: { src: '', alt: '' },
    showAddForm: false,
    sortable: null
  }" 
  class="container mx-auto px-4 py-8"
>
  <!-- Mobile Menu Button -->
  <div class="md:hidden flex justify-between items-center mb-6">
    <h2 class="text-2xl font-bold text-cyan-300">
      <i class="fas fa-images mr-2"></i>Manage Banners
    </h2>
    <button @click="menuOpen = !menuOpen" class="p-2 rounded-lg bg-slate-700 hover:bg-slate-600">
      <i class="fas fa-bars text-xl"></i>
    </button>
  </div>

  <!-- Sidebar Menu -->
  <div class="mobile-menu fixed md:relative z-40 md:z-auto w-64 h-full md:h-auto left-0 top-0 md:top-auto transform md:transform-none transition-transform duration-300 ease-in-out"
       :class="{'translate-x-0': menuOpen, '-translate-x-full': !menuOpen}">
    <div class="glass-card rounded-2xl overflow-hidden shadow-xl h-full md:h-auto">
      <div class="p-5 bg-gradient-to-r from-cyan-800 to-blue-900 flex justify-between items-center">
        <h1 class="text-3xl font-extrabold text-cyan-300 drop-shadow-md">PANEL</h1>
        <button @click="menuOpen = false" class="md:hidden p-2 text-cyan-200 hover:text-white">
          <i class="fas fa-times"></i>
        </button>
      </div>
      
      <div class="p-4">
        <div class="menu-item p-3 rounded-lg mb-2 cursor-pointer" 
             @click="window.location.href='main.php'; menuOpen = false">
          <i class="fas fa-box mr-3 text-cyan-400"></i>
          <span class="font-medium">Home page</span>
        </div>
        
        <div class="menu-item p-3 rounded-lg mb-2 cursor-pointer" 
             @click="window.location.href='add_product.php'; menuOpen = false">
          <i class="fas fa-plus-circle mr-3 text-emerald-400"></i>
          <span class="font-medium">Add Product</span>
        </div>
        
        <div class="menu-item p-3 rounded-lg mb-2 cursor-pointer bg-slate-800 border-l-cyan-500" 
             @click="menuOpen = false">
          <i class="fas fa-images mr-3 text-purple-400"></i>
          <span class="font-medium">Change Banners</span>
        </div>
        
        <div class="menu-item p-3 rounded-lg mb-2 cursor-pointer" 
             @click="window.location.href='upi_panel.php'; menuOpen = false">
          <i class="fas fa-wallet mr-3 text-purple-400"></i>
          <span class="font-medium">UPI Panel</span>
        </div>
      </div>
    </div>
  </div>
  
  <!-- Overlay for mobile menu -->
  <div x-show="menuOpen" @click="menuOpen = false" 
       class="fixed inset-0 bg-black bg-opacity-50 z-30 md:hidden"></div>
  
  <!-- Main Content -->
  <div class="flex-1 md:ml-64">
    <div class="glass-card rounded-2xl p-6 mb-8">
      <div class="flex justify-between items-center">
        <h2 class="text-3xl font-bold text-cyan-300">
          <i class="fas fa-images mr-3"></i>Manage Banners
        </h2>
        <button @click="showAddForm = !showAddForm" class="bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white px-4 py-2 rounded-lg shadow transition-all">
          <i class="fas fa-plus mr-2"></i>Add New Banner
        </button>
      </div>
    </div>

    <!-- Add Banner Form -->
    <div x-show="showAddForm" x-transition class="glass-card rounded-2xl p-6 mb-8">
      <h3 class="text-xl font-semibold mb-4 text-blue-300">
        <i class="fas fa-plus-circle mr-2"></i>Add New Banner
      </h3>
      <form method="POST" class="space-y-4">
        <div>
          <label class="block text-sm font-medium mb-1">Image URL</label>
          <input type="text" x-model="newBanner.src" name="new_src" required
                 class="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-2 focus:border-blue-500 focus:ring-blue-500">
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">Alt Text</label>
          <input type="text" x-model="newBanner.alt" name="new_alt" required
                 class="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-2 focus:border-blue-500 focus:ring-blue-500">
        </div>
        <div class="flex justify-end space-x-3">
          <button @click="showAddForm = false; newBanner = { src: '', alt: '' }" type="button" 
                  class="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition">
            Cancel
          </button>
          <button type="submit" name="add_banner"
                  class="bg-gradient-to-r from-blue-600 to-blue-700 text-white px-4 py-2 rounded-lg font-semibold shadow transition">
            Add Banner
          </button>
        </div>
      </form>
    </div>

    <!-- Banners List -->
    <div class="glass-card rounded-2xl p-6">
      <h3 class="text-xl font-semibold mb-4 text-cyan-300">
        <i class="fas fa-list mr-2"></i>Current Banners
      </h3>
      
      <?php if (empty($banners['carouselImages'])): ?>
        <div class="text-center py-8 text-gray-400">
          <i class="fas fa-image fa-3x mb-3"></i>
          <p>No banners found. Add your first banner above.</p>
        </div>
      <?php else: ?>
        <form method="POST">
          <div class="space-y-4" x-init="
            sortable = new Sortable($el, {
              animation: 150,
              ghostClass: 'sortable-ghost',
              handle: '.drag-handle',
              onEnd: function() {
                // Update the order of banners
                const items = Array.from($el.children);
                const newOrder = items.map(item => item.getAttribute('data-index'));
                const form = this.el.closest('form');
                
                // Create hidden inputs for the new order
                newOrder.forEach((index, position) => {
                  let input = form.querySelector(`input[name='order[${index}]']`);
                  if (!input) {
                    input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = `order[${index}]`;
                    form.appendChild(input);
                  }
                  input.value = position;
                });
              }
            });
          ">
            <?php foreach ($banners['carouselImages'] as $index => $banner): ?>
              <div class="flex flex-col md:flex-row gap-4 p-4 bg-slate-800 rounded-lg" data-index="<?= $index ?>">
                <div class="md:w-1/4">
                  <img src="<?= $banner['src'] ?>" alt="<?= $banner['alt'] ?>" class="banner-preview w-full rounded-lg">
                </div>
                <div class="flex-1 space-y-3">
                  <div>
                    <label class="block text-sm font-medium mb-1">Image URL</label>
                    <input type="text" name="src[]" value="<?= htmlspecialchars($banner['src']) ?>" required
                           class="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-2 focus:border-blue-500 focus:ring-blue-500">
                  </div>
                  <div>
                    <label class="block text-sm font-medium mb-1">Alt Text</label>
                    <input type="text" name="alt[]" value="<?= htmlspecialchars($banner['alt']) ?>" required
                           class="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-2 focus:border-blue-500 focus:ring-blue-500">
                  </div>
                </div>
                <div class="flex md:flex-col justify-between md:justify-start space-x-2 md:space-x-0 md:space-y-2">
                  <button type="button" class="drag-handle p-2 text-gray-400 hover:text-white">
                    <i class="fas fa-arrows-alt"></i>
                  </button>
                  <button type="submit" name="delete_banner" value="1" 
                          onclick="return confirm('Are you sure you want to delete this banner?')"
                          class="p-2 text-red-400 hover:text-red-300">
                    <i class="fas fa-trash-alt"></i>
                  </button>
                  <input type="hidden" name="delete_index" value="<?= $index ?>">
                </div>
              </div>
            <?php endforeach; ?>
          </div>
          
          <div class="mt-6 flex justify-end">
            <button type="submit" name="update_banners"
                    class="bg-gradient-to-r from-cyan-600 to-cyan-700 text-white px-6 py-3 rounded-lg font-semibold shadow transition hover:from-cyan-700 hover:to-cyan-800">
              <i class="fas fa-save mr-2"></i>Save Changes
            </button>
          </div>
        </form>
      <?php endif; ?>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.14.0/Sortable.min.js"></script>
<script>
  // Handle form submission for reordering
  document.addEventListener('DOMContentLoaded', function() {
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
      form.addEventListener('submit', function(e) {
        // Check if this is the update form
        if (this.querySelector('[name="update_banners"]')) {
          const orderInputs = this.querySelectorAll('input[name^="order["]');
          if (orderInputs.length > 0) {
            // Reorder the banners based on the new order
            const order = {};
            orderInputs.forEach(input => {
              const index = input.name.match(/\[(\d+)\]/)[1];
              order[index] = input.value;
            });
            
            // Sort the banners array
            const banners = <?= json_encode($banners['carouselImages']) ?>;
            const sortedBanners = [];
            
            Object.keys(order).forEach(index => {
              sortedBanners[order[index]] = banners[index];
            });
            
            // Update the form inputs
            const srcInputs = this.querySelectorAll('input[name="src[]"]');
            const altInputs = this.querySelectorAll('input[name="alt[]"]');
            
            sortedBanners.forEach((banner, i) => {
              srcInputs[i].value = banner.src;
              altInputs[i].value = banner.alt;
            });
          }
        }
      });
    });
  });
</script>
</body>
</html>