<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" href="<?= base_url('uploads/MSFFLogo.png') ?>">
<title>Multiplex Safe Farms and Fresh</title>

<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
</head>

<body class="bg-gray-50" x-data="cartApp()" x-init="init()">

<!-- HEADER -->
<header class="w-full bg-white shadow sticky top-0 z-50">
  <div class="w-full px-6 md:px-12 flex items-center h-20 justify-between">

    <!-- LOGO -->
    <div class="flex items-center gap-3">
      <img src="<?= base_url('uploads/MSFFLogo.png') ?>" alt="Logo" class="h-14 w-auto">
      <div>
        <h3 class="text-2xl font-bold text-green-600">Multiplex Farms</h3>
        <p class="text-sm text-gray-500 italic">Safe Farms & Fresh</p>
      </div>
    </div>

    <!-- SEARCH -->
    <div class="flex-1 mx-6">
      <form action="<?= base_url('search') ?>" method="GET" class="relative">
        <i class="fa-solid fa-magnifying-glass absolute left-4 top-3 text-gray-400"></i>
        <input type="text" name="q" id="typedSearch" placeholder="Search products..."
               class="w-full pl-12 pr-4 py-2 border border-gray-200 rounded-lg shadow-sm focus:ring-2 focus:ring-green-500 focus:outline-none">
      </form>
    </div>

    <!-- CART & USER -->
    <div class="flex items-center gap-6">
      

      <?php if(session()->get('isLoggedIn')): ?>
      <div class="relative" x-data="{ open: false }">
        <button @click="open = !open" class="flex items-center bg-gray-100 px-3 py-2 rounded-xl hover:bg-gray-200 transition">
          <i class="fa-solid fa-user text-lg text-gray-700"></i>
        </button>
        <div x-show="open" @click.away="open = false"
             class="absolute right-0 mt-2 w-52 bg-white border rounded-xl shadow-lg py-2 z-50">
          <a href="<?= base_url('order-tracking') ?>" class="flex items-center px-4 py-2 hover:bg-gray-100 text-sm text-gray-700">
            <i class="fa-solid fa-box text-gray-500"></i>
            <span class="ml-2">My Orders</span>
          </a>
          <hr class="my-1">
          <a href="<?= base_url('auth/logout') ?>" class="flex items-center px-4 py-2 hover:bg-gray-100 text-sm text-red-600">
            <i class="fa-solid fa-right-from-bracket"></i>
            <span class="ml-2">Logout</span>
          </a>
        </div>
      </div>
      <?php endif; ?>
    </div>
  </div>
</header>

<!-- MAIN -->
<div class="max-w-7xl mx-auto py-10 px-4 md:px-8 space-y-8">

  <!-- CART SECTION -->
  <div id="cart-section" class="bg-white rounded-2xl shadow p-6">
    <h1 class="text-2xl font-bold mb-6 flex items-center gap-3 text-green-600 border-b pb-3">
      <i class="fa-solid fa-cart-shopping"></i> My Cart
    </h1>

    <template x-if="cartItems.length > 0">
      <div class="overflow-x-auto">
        <table class="w-full border-collapse text-gray-700">
          <thead>
            <tr class="bg-green-50 uppercase text-sm text-gray-600">
              <th class="p-3 text-left">Product</th>
              <th class="p-3 text-left">Variant</th>
              <th class="p-3 text-center">Qty</th>
              <th class="p-3 text-right">Price</th>
              <th class="p-3 text-right">Subtotal</th>
              <th class="p-3 text-center">Action</th>
            </tr>
          </thead>
          <tbody>
            <template x-for="item in cartItems" :key="item.id">
              <tr class="border-t hover:bg-green-50 transition">
                <td class="p-3 font-medium" x-text="item.name"></td>
                <td class="p-3" x-text="item.unit"></td>
                <td class="p-3 text-center" x-text="item.quantity"></td>
                <td class="p-3 text-right">₹ <span x-text="item.offer_price"></span></td>
                <td class="p-3 text-right font-semibold">₹ <span x-text="item.quantity * item.offer_price"></span></td>
                <td class="p-3 text-center">
                  <button @click="removeItem(item.id)"
                          class="bg-red-500 hover:bg-red-600 text-white px-3 py-1 rounded-lg text-sm flex items-center gap-1 mx-auto">
                    <i class="fa-solid fa-trash"></i> Remove
                  </button>
                </td>
              </tr>
            </template>
          </tbody>
          <tfoot>
            <tr class="bg-green-50 font-semibold">
              <td colspan="4" class="text-right p-3">Subtotal</td>
              <td class="text-right p-3" colspan="2" x-text="'₹ '+ cartSubtotal()"></td>
            </tr>
            <tr class="bg-green-50 font-semibold">
              <td colspan="4" class="text-right p-3">Delivery</td>
              <td class="text-right p-3" colspan="2" x-text="'₹ '+ deliveryCharge"></td>
            </tr>
            <tr class="bg-green-100 text-green-700 text-lg font-bold">
              <td colspan="4" class="text-right p-3">Grand Total</td>
              <td class="text-right p-3" colspan="2" x-text="'₹ '+ grandTotal()"></td>
            </tr>
          </tfoot>
        </table>

        <!-- Checkout -->
        <div class="mt-6 text-right">
          <button @click="scrollToCheckout()" 
                  class="bg-green-600 hover:bg-green-700 text-white py-3 px-6 rounded-xl font-semibold shadow-md transition flex items-center gap-2">
            <i class="fa-solid fa-credit-card"></i> Proceed to Checkout
          </button>
        </div>
      </div>
    </template>

    <template x-if="cartItems.length === 0">
      <p class="text-center text-gray-500 mt-6 text-lg">Your cart is empty.</p>
    </template>
  </div>

  <!-- CHECKOUT SECTION -->
  <div id="checkout-section" class="bg-white rounded-2xl shadow p-6" x-show="showCheckout" x-transition>
    <h1 class="text-2xl font-bold mb-6 flex items-center gap-3 text-green-700 border-b pb-3">
      <i class="fa-solid fa-credit-card"></i> Checkout
    </h1>
    <form @submit.prevent="placeOrder" class="space-y-4">
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label class="block text-sm font-medium mb-1">Full Name</label>
          <input type="text" x-model="checkout.name" class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-green-500" required>
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">Email</label>
          <input type="email" x-model="checkout.email" class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-green-500" required>
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">Phone</label>
          <input type="text" x-model="checkout.phone" class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-green-500" required>
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">Apartment</label>
          <select x-model="checkout.apartment_id" @change="fetchAddress"
                  class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-green-500" required>
            <option value="">-- Select Apartment --</option>
            <template x-for="apart in apartments" :key="apart.id">
              <option :value="apart.id" x-text="apart.apartName"></option>
            </template>
          </select>
        </div>
      </div>

      <div>
        <label class="block text-sm font-medium mb-1">Address</label>
        <textarea x-model="checkout.address" rows="2" class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-green-500" required></textarea>
      </div>

      <div>
        <label class="block text-sm font-medium mb-1">Payment Method</label>
        <select x-model="checkout.payment" class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-green-500" required>
          <option value="COD">Cash on Delivery</option>
          <option value="Online">Online</option>
        </select>
      </div>

      <button type="button" @click="placeOrder()" class="w-full bg-green-600 hover:bg-green-700 text-white py-3 rounded-xl font-semibold flex items-center justify-center gap-2 shadow-md transition">
        <i class="fa-solid fa-check"></i> Place Order
      </button>
    </form>
  </div>

</div>

<script>
 function cartApp() {
  return {
    cartItems: <?= json_encode($cartItems ?? []) ?>,
    apartments: [],
    showCheckout: false,
    deliveryCharge: <?= $deliveryCharge ?? 0 ?>,
    checkout: { name:'', email:'', phone:'', apartment_id:'', address:'', payment:'COD' },

    cartSubtotal() { return this.cartItems.reduce((sum, i) => sum + (i.offer_price * i.quantity), 0); },
    grandTotal() { return this.cartSubtotal() + this.deliveryCharge; },

    removeItem(id) {
      $.post("<?= base_url('order/removeItem') ?>/"+id, {}, (res) => {
        if(res.success) this.cartItems = this.cartItems.filter(i => i.id != id);
        else alert("Failed to remove item.");
      }, 'json');
    },

    fetchApartments() {
      $.getJSON("<?= base_url('order/getApartments') ?>", (data) => { this.apartments = data; });
    },

    fetchAddress() {
      if(this.checkout.apartment_id){
        $.getJSON("<?= base_url('order/getApartmentAddress/') ?>"+this.checkout.apartment_id, (res) => {
          this.checkout.address = res.apartAddress;
        });
      } else this.checkout.address = '';
    },

    placeOrder() {
    let self = this;

    let postData = {
        checkout: JSON.stringify(this.checkout),
        cartItems: JSON.stringify(this.cartItems),
        deliveryCharge: this.deliveryCharge
    };

    console.log("Placing order:", postData);

    $.post("<?= base_url('order/placeOrder') ?>", postData, function(res){
        console.log("Response:", res);
        if(res.success){
            if(self.checkout.payment === 'Online'){
                let form = document.createElement('form');
                form.method = 'POST';
                form.action = "<?= base_url('payment/initiate') ?>";

                let inputs = {
                    name: self.checkout.name,
                    email: self.checkout.email,
                    phone: self.checkout.phone,
                    amount: res.totalAmount,
                    order_id: res.order_id
                };

                for(let key in inputs){
                    let input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = key;
                    input.value = inputs[key];
                    form.appendChild(input);
                }

                document.body.appendChild(form);
                form.submit();
            } else {
                self.cartItems = [];
                alert("Order placed with COD! Order ID: "+res.order_id);
                window.location.href="<?= base_url('order') ?>";
            }
        } else {
            alert(res.error || "Something went wrong!");
        }
    }, 'json');
},


    scrollToCheckout() {
      this.showCheckout = true;
      this.$nextTick(() => {
        document.getElementById('checkout-section').scrollIntoView({ behavior: 'smooth' });
      });
    },

    init() { 
        console.log("Cart Items:", this.cartItems);
        this.fetchApartments(); 
    }
  }
}


</script>

</body>
</html>
