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

$products = json_decode(file_get_contents('../js/products.json'), true);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Product Management</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);
    }
    .neon-border {
      border: 2px solid transparent;
      transition: all 0.3s ease-in-out;
    }
    .neon-border:hover {
      border-color: #22d3ee;
      box-shadow: 0 0 10px rgba(34, 211, 238, 0.5);
    }
    .menu-button {
      background: linear-gradient(135deg, #0ea5e9, #22d3ee);
      box-shadow: 0 4px 15px rgba(14, 165, 233, 0.3);
    }
    .menu-button:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(14, 165, 233, 0.4);
    }
    .menu-item {
      transition: all 0.3s ease;
      border-left: 3px solid transparent;
    }
    .menu-item:hover {
      background: rgba(15, 23, 42, 0.5);
      border-left-color: #22d3ee;
    }
    .mobile-menu {
      transition: all 0.3s ease;
    }
  </style>
</head>
<body class="text-white">
<div x-data="{ 
    openDeleteModal: false, 
    deleteId: null,
    resetting: false,
    menuOpen: false,
    activeMenu: 'products'
  }" 
  class="container mx-auto px-4 py-8 flex flex-col md:flex-row"
>
  <!-- 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-boxes mr-2"></i>Products
    </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" 
             :class="{ 'bg-slate-800 border-l-cyan-500': activeMenu === 'products' }"
             @click="activeMenu = 'products'; menuOpen = false">
          <i class="fas fa-box mr-3 text-cyan-400"></i>
          <span class="font-medium">Products</span>
        </div>
        
        <div class="menu-item p-3 rounded-lg mb-2 cursor-pointer" 
             :class="{ 'bg-slate-800 border-l-cyan-500': activeMenu === 'add' }"
             @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" 
             :class="{ 'bg-slate-800 border-l-cyan-500': activeMenu === 'banners' }"
             @click="window.location.href='change_banner.php'; 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" 
             :class="{ 'bg-slate-800 border-l-cyan-500': activeMenu === 'upi' }"
             @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 class="menu-item p-3 rounded-lg mb-2 cursor-pointer" 
             @click="
               menuOpen = false;
               Swal.fire({
                 title: 'Reset All Products?',
                 text: 'This will backup current products and reset to demo product',
                 icon: 'warning',
                 showCancelButton: true,
                 confirmButtonColor: '#d33',
                 confirmButtonText: 'Reset',
                 cancelButtonText: 'Cancel',
                 reverseButtons: true
               }).then((result) => {
                 if (result.isConfirmed) {
                   resetting = true;
                   fetch('reset_products.php')
                     .then(response => response.json())
                     .then(data => {
                       if(data.success) {
                         Swal.fire('Reset!', data.message, 'success').then(() => {
                           location.reload();
                         });
                       } else {
                         Swal.fire('Error!', data.message, 'error');
                       }
                     })
                     .catch(error => {
                       Swal.fire('Error!', 'Something went wrong', 'error');
                     })
                     .finally(() => resetting = false);
                 }
               });
             ">
          <i class="fas fa-sync-alt mr-3 text-yellow-400"></i>
          <span class="font-medium">Reset Products</span>
        </div>
        
        <div class="menu-item p-3 rounded-lg cursor-pointer" 
             @click="
               menuOpen = false;
               Swal.fire({
                 title: 'Recover Products?',
                 text: 'This will restore products from the latest backup',
                 icon: 'question',
                 showCancelButton: true,
                 confirmButtonColor: '#10b981',
                 confirmButtonText: 'Recover',
                 cancelButtonText: 'Cancel',
                 reverseButtons: true
               }).then((result) => {
                 if (result.isConfirmed) {
                   resetting = true;
                   fetch('recover_products.php')
                     .then(response => response.json())
                     .then(data => {
                       if(data.success) {
                         Swal.fire('Recovered!', data.message, 'success').then(() => {
                           location.reload();
                         });
                       } else {
                         Swal.fire('Error!', data.message, 'error');
                       }
                     })
                     .catch(error => {
                       Swal.fire('Error!', 'Something went wrong', 'error');
                     })
                     .finally(() => resetting = false);
                 }
               });
             ">
          <i class="fas fa-history mr-3 text-amber-400"></i>
          <span class="font-medium">Recover Products</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">
    <div class="glass-card rounded-2xl p-6 mb-8 hidden md:block">
      <div class="flex justify-between items-center">
        <h2 class="text-3xl font-bold text-cyan-300">
          <i class="fas fa-boxes mr-3"></i>Product Management
        </h2>
        <div class="text-slate-400">
          <span class="bg-slate-800 px-3 py-1 rounded-full text-sm">
            <?= count($products) ?> products
          </span>
        </div>
      </div>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
      <?php foreach ($products as $product): ?>
      <div class="glass-card neon-border rounded-2xl overflow-hidden shadow-2xl transition-all hover:scale-[1.03]">
        <img src="<?= $product['img1'] ?>" alt="<?= $product['name'] ?>" class="w-full h-56 object-cover">
        <div class="p-5">
          <h3 class="text-xl font-semibold mb-3 truncate"><?= $product['name'] ?></h3>
          <div class="flex justify-between items-center mb-4">
            <span class="text-lime-400 font-bold text-xl">₹<?= $product['selling_price'] ?></span>
            <span class="text-gray-400 line-through text-lg">₹<?= $product['mrp'] ?></span>
          </div>
          <div class="flex space-x-3">
            <a href="edit_product.php?id=<?= $product['id'] ?>" class="flex-1 text-center bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-600 hover:to-amber-700 text-white font-semibold px-4 py-2 rounded-lg shadow transition-all">
              ✏️ Edit
            </a>
            <button @click="openDeleteModal = true; deleteId = '<?= $product['id'] ?>'" class="flex-1 bg-gradient-to-r from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 text-white px-4 py-2 rounded-lg shadow transition-all">
              🗑️ Delete
            </button>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- Delete Modal -->
  <div x-show="openDeleteModal" x-transition class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center p-4 z-50">
    <div class="glass-card rounded-2xl p-6 max-w-md w-full text-white">
      <h3 class="text-2xl font-bold mb-4 text-red-400">
        <i class="fas fa-exclamation-triangle mr-2"></i>Confirm Deletion
      </h3>
      <p class="text-gray-300 mb-6">Are you sure you want to delete this product? This action cannot be undone.</p>
      <div class="flex justify-end space-x-4">
        <button @click="openDeleteModal = false" class="px-5 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition">Cancel</button>
        <form method="POST" action="delete_product.php">
          <input type="hidden" name="id" :value="deleteId">
          <button type="submit" class="bg-gradient-to-r from-red-600 to-red-700 text-white px-5 py-2 rounded-lg font-semibold shadow transition">
            Delete
          </button>
        </form>
      </div>
    </div>
  </div>
</div>
</body>
</html>