@extends('layouts.app')
@section('title', "Checkout — God's Treat")

@push('styles')
<style>
  .checkout-wrap{padding:110px 5% 60px;max-width:1200px;margin:0 auto;}
  .checkout-grid{display:grid;grid-template-columns:1fr 360px;gap:40px;}
  .checkout-title{font-family:'Bebas Neue',sans-serif;font-size:2.4rem;margin-bottom:32px;}
  .form-section{background:var(--card);border:1px solid var(--border);border-radius:var(--radius);padding:28px;margin-bottom:24px;}
  .form-section-title{font-family:'Bebas Neue',sans-serif;font-size:1.3rem;margin-bottom:20px;color:var(--orange);}
  .form-row{display:grid;grid-template-columns:1fr 1fr;gap:16px;}
  .form-group{margin-bottom:16px;}
  .form-label{font-size:.8rem;font-weight:600;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);margin-bottom:6px;display:block;}
  .form-input{width:100%;background:var(--card2);border:1px solid var(--border2);color:var(--white);padding:12px 16px;border-radius:10px;font-size:.9rem;transition:border-color .2s;box-sizing:border-box;}
  .form-input:focus{outline:none;border-color:var(--orange);}
  .form-input.error{border-color:var(--pink);}
  .error-msg{color:var(--pink);font-size:.78rem;margin-top:4px;}
  /* Payment options */
  .pay-option{background:var(--card2);border:2px solid var(--border2);border-radius:12px;padding:18px 20px;cursor:pointer;transition:all .25s;display:flex;align-items:center;gap:14px;margin-bottom:12px;}
  .pay-option.selected{border-color:var(--orange);background:rgba(255,107,26,.08);}
  .pay-option-icon{font-size:1.8rem;}
  .pay-option-text{font-weight:600;font-size:.95rem;}
  .pay-option-sub{font-size:.78rem;color:var(--muted);}
  /* Order summary sidebar */
  .ck-summary{background:var(--card);border:1px solid var(--border);border-radius:var(--radius);padding:24px;position:sticky;top:100px;}
  .ck-item{display:flex;gap:14px;align-items:center;padding:12px 0;border-bottom:1px solid var(--border);}
  .ck-item:last-of-type{border-bottom:none;}
  .ck-img{width:56px;height:56px;background:rgba(255,107,26,.06);border-radius:10px;display:flex;align-items:center;justify-content:center;overflow:hidden;flex-shrink:0;}
  .ck-img img{max-width:80%;max-height:80%;object-fit:contain;}
  .ck-total-row{display:flex;justify-content:space-between;padding:8px 0;font-size:.9rem;}
  .ck-total-row.final{font-size:1.1rem;font-weight:800;padding-top:14px;border-top:1px solid var(--border);margin-top:8px;}
  @media(max-width:900px){.checkout-grid{grid-template-columns:1fr}.ck-summary{position:static}.form-row{grid-template-columns:1fr}}
</style>
@endpush

@section('content')
<div class="checkout-wrap">
  <h1 class="checkout-title">CHECKOUT</h1>

  @if($errors->any())
  <div style="background:rgba(247,37,133,.1);border:1px solid rgba(247,37,133,.3);border-radius:12px;padding:16px;margin-bottom:24px;color:var(--pink)">
    @foreach($errors->all() as $err)<div>• {{ $err }}</div>@endforeach
  </div>
  @endif

  <div class="checkout-grid">
    <!-- Left: Form -->
    <div>
      <form method="POST" action="{{ route('checkout.store') }}" id="checkoutForm">
        @csrf
        <!-- Delivery Address -->
        <div class="form-section">
          <div class="form-section-title">📦 Delivery Address</div>
          <div class="form-row">
            <div class="form-group">
              <label class="form-label">Full Name*</label>
              <input type="text" name="name" class="form-input {{ $errors->has('name') ? 'error' : '' }}" value="{{ old('name', auth()->user()?->name) }}" placeholder="Your name" required/>
              @error('name')<div class="error-msg">{{ $message }}</div>@enderror
            </div>
            <div class="form-group">
              <label class="form-label">Phone*</label>
              <input type="tel" name="phone" class="form-input {{ $errors->has('phone') ? 'error' : '' }}" value="{{ old('phone', auth()->user()?->phone) }}" placeholder="10-digit mobile" required/>
              @error('phone')<div class="error-msg">{{ $message }}</div>@enderror
            </div>
          </div>
          <div class="form-group">
            <label class="form-label">Email*</label>
            <input type="email" name="email" class="form-input {{ $errors->has('email') ? 'error' : '' }}" value="{{ old('email', auth()->user()?->email) }}" placeholder="email@example.com" required/>
            @error('email')<div class="error-msg">{{ $message }}</div>@enderror
          </div>
          <div class="form-group">
            <label class="form-label">Full Address*</label>
            <textarea name="address" class="form-input {{ $errors->has('address') ? 'error' : '' }}" rows="2" placeholder="House/Flat, Street, Area" required style="resize:vertical">{{ old('address') }}</textarea>
            @error('address')<div class="error-msg">{{ $message }}</div>@enderror
          </div>
          <div class="form-row">
            <div class="form-group">
              <label class="form-label">City*</label>
              <input type="text" name="city" class="form-input" value="{{ old('city') }}" placeholder="City" required/>
            </div>
            <div class="form-group">
              <label class="form-label">Pincode*</label>
              <input type="text" name="pincode" class="form-input" value="{{ old('pincode') }}" placeholder="110001" maxlength="10" required/>
            </div>
          </div>
        </div>

        <!-- Payment -->
        <div class="form-section">
          <div class="form-section-title">💳 Payment Method</div>
          <div class="pay-option selected" onclick="selectPay('online', this)">
            <div class="pay-option-icon">📱</div>
            <div>
              <div class="pay-option-text">Pay Online (UPI / Card / Net Banking)</div>
              <div class="pay-option-sub">Secure payment via Razorpay</div>
            </div>
          </div>
          <div class="pay-option" onclick="selectPay('cod', this)">
            <div class="pay-option-icon">💵</div>
            <div>
              <div class="pay-option-text">Cash on Delivery</div>
              <div class="pay-option-sub">Pay when your order arrives</div>
            </div>
          </div>
          <input type="hidden" name="_payment_method" id="payMethodInput" value="online"/>
        </div>

        <!-- COD Submit button -->
        <button type="submit" class="btn-primary btn-full" id="placeOrderBtn" style="padding:18px;font-size:1rem" onclick="return handleOrder(event)">
          Place Order →
        </button>
      </form>

      <!-- Razorpay hidden form (submitted after payment success) -->
      <form method="POST" action="{{ route('checkout.razorpay') }}" id="rzpForm" style="display:none">
        @csrf
        <input type="hidden" name="name" id="rzp_name"/>
        <input type="hidden" name="email" id="rzp_email"/>
        <input type="hidden" name="phone" id="rzp_phone"/>
        <input type="hidden" name="address" id="rzp_address"/>
        <input type="hidden" name="city" id="rzp_city"/>
        <input type="hidden" name="pincode" id="rzp_pincode"/>
        <input type="hidden" name="razorpay_payment_id" id="rzp_payment_id"/>
        <input type="hidden" name="razorpay_order_id" id="rzp_order_id"/>
        <input type="hidden" name="razorpay_signature" id="rzp_signature"/>
      </form>
    </div>

    <!-- Right: Order Summary -->
    <div class="ck-summary">
      <h3 style="font-family:'Bebas Neue',sans-serif;font-size:1.4rem;margin-bottom:16px">ORDER SUMMARY</h3>
      @foreach($items as $item)
      <div class="ck-item">
        <div class="ck-img">
          <img src="{{ asset('images/' . $item->product->image) }}" alt="{{ $item->product->name }}" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22100%22 height=%22100%22><rect width=%22100%22 height=%22100%22 fill=%22%23ff6b1a11%22/><text x=%2250%22 y=%2258%22 text-anchor=%22middle%22 fill=%22%23ff6b1a55%22 font-size=%2240%22>🌾</text></svg>'"/>
        </div>
        <div style="flex:1">
          <div style="font-size:.88rem;font-weight:600">{{ $item->product->name }}</div>
          <div style="color:var(--muted);font-size:.78rem">×{{ $item->qty }}</div>
        </div>
        <div style="font-weight:700">₹{{ number_format($item->product->price * $item->qty) }}</div>
      </div>
      @endforeach
      <!-- Coupon -->
      <div style="margin:16px 0;padding:14px;background:var(--card2);border:1px solid var(--border2);border-radius:10px">
        <div style="font-size:.78rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);margin-bottom:8px">Have a coupon?</div>
        <div style="display:flex;gap:8px" id="couponRow">
          <input type="text" id="couponInput" placeholder="Enter code" class="form-input" style="flex:1;padding:9px 12px;font-size:.85rem;text-transform:uppercase"/>
          <button onclick="applyCoupon()" class="btn-primary" style="padding:9px 14px;font-size:.8rem;white-space:nowrap">Apply</button>
        </div>
        <div id="couponMsg" style="margin-top:6px;font-size:.78rem"></div>
        @if(session('coupon'))
        <div style="margin-top:8px;display:flex;align-items:center;justify-content:space-between;background:rgba(6,214,160,.08);border:1px solid rgba(6,214,160,.2);padding:8px 12px;border-radius:8px">
          <span style="color:#06d6a0;font-size:.82rem;font-weight:700">{{ session('coupon.code') }} applied</span>
          <button onclick="removeCoupon()" style="background:none;border:none;color:var(--pink);cursor:pointer;font-size:.75rem">Remove</button>
        </div>
        @endif
      </div>

      <div class="ck-total-row" style="margin-top:8px"><span>Subtotal</span><span>₹{{ number_format($subtotal) }}</span></div>
      @if($discount > 0)
      <div class="ck-total-row" id="discountRow"><span style="color:#06d6a0">Discount ({{ session('coupon.code') }})</span><span style="color:#06d6a0">-₹{{ number_format($discount) }}</span></div>
      @endif
      <div class="ck-total-row" id="shippingRow">
        <span>Delivery</span>
        <span style="{{ $shipping > 0 ? '' : 'color:#06d6a0' }}">{{ $shipping > 0 ? '₹'.$shipping : 'FREE' }}</span>
      </div>
      <div class="ck-total-row final" id="totalRow"><span>Total</span><span>₹{{ number_format($total) }}</span></div>
      <div style="margin-top:14px;padding:12px;background:rgba(6,214,160,.08);border:1px solid rgba(6,214,160,.2);border-radius:10px;font-size:.78rem;color:var(--muted)">
        🔒 Your payment is encrypted and secure. We never store card details.
      </div>
    </div>
  </div>
</div>
@endsection

@push('scripts')
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
  const RZP_KEY = '{{ $rzpKey }}';
  const AMOUNT  = {{ $total * 100 }};

  function applyCoupon() {
    const code = document.getElementById('couponInput').value.trim();
    if (!code) return;
    fetch('{{ route('coupon.apply') }}', {
      method: 'POST',
      headers: {'Content-Type':'application/json','X-CSRF-TOKEN':csrfToken},
      body: JSON.stringify({code})
    }).then(r => r.json()).then(data => {
      const msg = document.getElementById('couponMsg');
      if (data.error) {
        msg.style.color = 'var(--pink)';
        msg.textContent = data.error;
      } else {
        msg.style.color = '#06d6a0';
        msg.textContent = data.message;
        setTimeout(() => location.reload(), 800);
      }
    });
  }

  function removeCoupon() {
    fetch('{{ route('coupon.remove') }}', {method:'POST',headers:{'X-CSRF-TOKEN':csrfToken}})
      .then(() => location.reload());
  }

  document.getElementById('couponInput')?.addEventListener('keypress', e => { if(e.key==='Enter'){e.preventDefault();applyCoupon();} });
  let currentMethod = 'online';

  function selectPay(method, el) {
    currentMethod = method;
    document.querySelectorAll('.pay-option').forEach(o => o.classList.remove('selected'));
    el.classList.add('selected');
    document.getElementById('payMethodInput').value = method;
    document.getElementById('placeOrderBtn').textContent = method === 'cod' ? 'Place Order (COD) →' : 'Pay Now →';
  }

  function handleOrder(e) {
    if (currentMethod === 'cod') return true; // submit form normally

    e.preventDefault();
    // Validate form first
    const form = document.getElementById('checkoutForm');
    const name = form.name.value.trim();
    const email = form.email.value.trim();
    const phone = form.phone.value.trim();
    const address = form.address.value.trim();
    const city = form.city.value.trim();
    const pincode = form.pincode.value.trim();

    if (!name || !email || !phone || !address || !city || !pincode) {
      showToast('Please fill all required fields ❌', false);
      return false;
    }

    // Create Razorpay order
    fetch('{{ route('checkout.create-order') }}', {
      method: 'POST',
      headers: {'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken},
      body: JSON.stringify({})
    })
    .then(r => r.json())
    .then(data => {
      const options = {
        key: RZP_KEY,
        amount: data.amount,
        currency: 'INR',
        order_id: data.id,
        name: "God's Treat",
        description: 'Premium Makhana Order',
        image: '{{ asset('images/Pack.png') }}',
        prefill: { name, email, contact: phone },
        theme: { color: '#ff6b1a' },
        handler: function(response) {
          // Fill hidden form and submit
          document.getElementById('rzp_name').value = name;
          document.getElementById('rzp_email').value = email;
          document.getElementById('rzp_phone').value = phone;
          document.getElementById('rzp_address').value = address;
          document.getElementById('rzp_city').value = city;
          document.getElementById('rzp_pincode').value = pincode;
          document.getElementById('rzp_payment_id').value = response.razorpay_payment_id;
          document.getElementById('rzp_order_id').value = response.razorpay_order_id || data.id;
          document.getElementById('rzp_signature').value = response.razorpay_signature;
          document.getElementById('rzpForm').submit();
        },
        modal: {
          ondismiss: () => showToast('Payment cancelled', false)
        }
      };
      new Razorpay(options).open();
    })
    .catch(() => showToast('Error initiating payment. Try COD.', false));

    return false;
  }
</script>
@endpush
