@extends('layouts.customer')
@section('title', 'Checkout — '.$product->name)

@section('content')

{{-- Breadcrumb --}}
<div style="display:flex;align-items:center;gap:.5rem;margin-bottom:1.5rem;font-size:.875rem">
  <a href="{{ route('customer.market') }}"
     style="color:var(--muted-foreground);text-decoration:none;transition:color .1s"
     onmouseover="this.style.color='var(--foreground)'" onmouseout="this.style.color='var(--muted-foreground)'">
    Market
  </a>
  <span style="color:var(--border)">/</span>
  <a href="{{ route('customer.market.show', $product) }}"
     style="color:var(--muted-foreground);text-decoration:none;transition:color .1s"
     onmouseover="this.style.color='var(--foreground)'" onmouseout="this.style.color='var(--muted-foreground)'">
    {{ $product->name }}
  </a>
  <span style="color:var(--border)">/</span>
  <span style="color:var(--foreground);font-weight:500">Checkout</span>
</div>

@php
  $licensePrice = $product->priceFor($licenseType);
  $t            = fmt_price_taxed($licensePrice);
  $uc           = user_currency();
  $exR          = ($uc && !$uc->is_base && (float)$uc->exchange_rate > 0) ? (float)$uc->exchange_rate : 1.0;
  $sym          = $uc?->symbol ?? setting('currency_symbol','$');

  $gwLabels = [
    'paypal' => ['PayPal',       'assets/paypal-logo.svg',  '#0070ba'],
    'stripe' => ['Card / Stripe','assets/stripe-logo.svg',  '#635bff'],
    'manual' => ['Bank Transfer','',                         '#374151'],
  ];
@endphp

<div style="display:grid;grid-template-columns:1fr 380px;gap:1.5rem;align-items:start">

  {{-- ── Left: payment form ── --}}
  <div style="display:flex;flex-direction:column;gap:1.25rem">


    <form method="POST" action="{{ route('customer.checkout.initiate', $product) }}" id="checkout-form">
      @csrf

      {{-- License type passed as hidden input from product page --}}
      <input type="hidden" name="license_type" value="{{ $licenseType }}">

      {{-- Step 1: Payment gateway --}}
      <div class="card" style="padding:1.375rem">
        <div style="font-size:1rem;font-weight:700;color:var(--foreground);margin-bottom:1rem;
          display:flex;align-items:center;gap:.625rem">
          <span style="width:1.625rem;height:1.625rem;border-radius:50%;background:var(--foreground);
            color:var(--background);display:flex;align-items:center;justify-content:center;
            font-size:.75rem;font-weight:700;flex-shrink:0">1</span>
          Choose Payment Method
        </div>

        <div style="display:flex;flex-direction:column;gap:.625rem;margin-bottom:1.25rem">
          @foreach($enabledGateways as $gw)
          @php [$gwName, , ] = $gwLabels[$gw] ?? [$gw, '', '#374151']; @endphp
          <label style="display:flex;align-items:center;gap:.875rem;padding:.875rem 1rem;
            border-radius:var(--radius);border:1.5px solid var(--border);cursor:pointer;
            transition:border-color .15s;background:var(--background)"
            onmouseover="this.style.borderColor='var(--foreground)'"
            onmouseout="this.style.borderColor=this.querySelector('input').checked?'var(--foreground)':'var(--border)'"
            onclick="this.style.borderColor='var(--foreground)'">
            <input type="radio" name="gateway" value="{{ $gw }}"
              @checked($gateway === $gw)
              style="width:1rem;height:1rem;accent-color:var(--foreground);flex-shrink:0"
              onchange="document.querySelectorAll('[data-gw-panel]').forEach(p=>p.style.display='none');
                        var el=document.getElementById('gw-{{$gw}}'); if(el) el.style.display='block';
                        document.querySelectorAll('.gw-label').forEach(c=>c.style.borderColor='var(--border)');
                        this.closest('label').style.borderColor='var(--foreground)'">
            <div style="flex:1;display:flex;align-items:center;gap:.75rem">
              @php
                $gwMeta = [
                  'stripe'   => ['bg'=>'#635bff','text'=>'#fff','abbr'=>'S',  'name'=>setting('stripe_label','Stripe'),   'desc'=>'Visa, Mastercard, Amex'],
                  'paypal'   => ['bg'=>'#003087','text'=>'#009cde','abbr'=>'PP', 'name'=>setting('paypal_label','PayPal'),   'desc'=>'PayPal account or card'],
                  'razorpay' => ['bg'=>'#072654','text'=>'#3395ff','abbr'=>'R',  'name'=>setting('razorpay_label','Razorpay'),'desc'=>'UPI, Cards, Netbanking'],
                  'cashfree' => ['bg'=>'#1a73e8','text'=>'#fff','abbr'=>'CF', 'name'=>setting('cashfree_label','Cashfree'),'desc'=>'UPI, Cards, Netbanking'],
                  'manual'   => ['bg'=>'var(--muted)','text'=>'var(--muted-foreground)','abbr'=>'$','name'=>'Bank Transfer','desc'=>'We\'ll email payment instructions'],
                ];
                $m = $gwMeta[$gw] ?? $gwMeta['manual'];
              @endphp
              <div style="width:2rem;height:2rem;border-radius:.4rem;background:{{ $m['bg'] }};
                display:flex;align-items:center;justify-content:center;flex-shrink:0;
                border:1px solid var(--border)">
                <span style="font-size:.7rem;font-weight:900;color:{{ $m['text'] }}">{{ $m['abbr'] }}</span>
              </div>
              <div>
                <div style="font-size:.9rem;font-weight:600;color:var(--foreground)">{{ $m['name'] }}</div>
                <div style="font-size:.75rem;color:var(--muted-foreground)">{{ $m['desc'] }}</div>
              </div>
            </div>
          </label>
          @endforeach
        </div>

        {{-- PayPal info panel --}}
        @if(in_array('paypal', $enabledGateways))
        <div id="gw-paypal" data-gw-panel
          style="display:{{ $gateway==='paypal'?'block':'none' }};
          padding:.875rem;background:#f0f8ff;border:1px solid #bfdbfe;
          border-radius:var(--radius);margin-bottom:1rem;font-size:.8125rem;color:#1e40af">
          <div style="display:flex;align-items:center;gap:.5rem">
            <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
            You'll be redirected to PayPal to complete your payment securely.
            {{ setting('paypal_sandbox','1')==='1' ? '(Sandbox mode — use test credentials)' : '' }}
          </div>
        </div>
        @endif

        {{-- Stripe info panel --}}
        @if(in_array('stripe', $enabledGateways))
        <div id="gw-stripe" data-gw-panel
          style="display:{{ $gateway==='stripe'?'block':'none' }};
          padding:.875rem;background:#f5f3ff;border:1px solid #ddd6fe;
          border-radius:var(--radius);margin-bottom:1rem;font-size:.8125rem;color:#4c1d95">
          <div style="display:flex;align-items:center;gap:.5rem">
            <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/>
            </svg>
            Secure card payment powered by Stripe. Your card details are never stored on our servers.
          </div>
        </div>
        @endif

        {{-- Manual info panel --}}
        @if(in_array('manual', $enabledGateways))
        <div id="gw-manual" data-gw-panel
          style="display:{{ $gateway==='manual'?'block':'none' }};
          padding:.875rem;background:var(--muted);border:1px solid var(--border);
          border-radius:var(--radius);margin-bottom:1rem;font-size:.8125rem;color:var(--muted-foreground)">
          <div style="display:flex;align-items:flex-start;gap:.5rem">
            <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="flex-shrink:0;margin-top:.1rem">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
            Place your order now and we'll send bank transfer details to <strong>{{ auth()->user()->email }}</strong>.
            Your license will be activated once payment is confirmed (usually within 1 business day).
          </div>
        </div>
        @endif

        {{-- Razorpay info panel --}}
        @if(in_array('razorpay', $enabledGateways))
        <div id="gw-razorpay" data-gw-panel
          style="display:{{ $gateway==='razorpay'?'block':'none' }};
          padding:.875rem;background:#eff6ff;border:1px solid #bfdbfe;
          border-radius:var(--radius);margin-bottom:1rem;font-size:.8125rem;color:#1e40af">
          <div style="display:flex;align-items:center;gap:.5rem">
            <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
            You'll complete payment via Razorpay — supports UPI, Cards, Netbanking and Wallets.
            {{ setting('razorpay_environment','sandbox')==='sandbox' ? '(Sandbox mode)' : '' }}
          </div>
        </div>
        @endif

        {{-- Cashfree info panel --}}
        @if(in_array('cashfree', $enabledGateways))
        <div id="gw-cashfree" data-gw-panel
          style="display:{{ $gateway==='cashfree'?'block':'none' }};
          padding:.875rem;background:#eff6ff;border:1px solid #bfdbfe;
          border-radius:var(--radius);margin-bottom:1rem;font-size:.8125rem;color:#1e40af">
          <div style="display:flex;align-items:center;gap:.5rem">
            <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
            You'll complete payment via Cashfree — fast, secure payouts for India.
            {{ setting('cashfree_environment','sandbox')==='sandbox' ? '(Sandbox mode)' : '' }}
          </div>
        </div>
        @endif

        {{-- Place order button --}}
        <button type="submit" id="pay-btn" class="btn btn-primary"
          style="width:100%;padding:.875rem;font-size:.9375rem;font-weight:700;font-family:inherit;
            border-radius:var(--radius);cursor:pointer"
          onclick="this.disabled=true;this.innerHTML='Processing…';this.form.submit()">
          <svg width="15" height="15" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
          </svg>
          Proceed to Payment
        </button>

        <p style="font-size:.72rem;color:var(--muted-foreground);text-align:center;margin-top:.75rem">
          By purchasing you agree to our Terms of Service. Licenses are non-refundable once activated.
        </p>
      </div>

    </form>
  </div>

  {{-- ── Right: order summary ── --}}
  <div style="position:sticky;top:calc(3.75rem + 1.5rem)">
    <div class="card" style="overflow:hidden">
      <div class="card-header">
        <div class="card-title">Order Summary</div>
      </div>

      {{-- Product --}}
      <div style="padding:1.125rem;border-bottom:1px solid var(--border)">
        <div style="display:flex;align-items:center;gap:.75rem">
          @php $typeIcons=['plugin'=>'🔌','module'=>'🧩','software'=>'💻','theme'=>'🎨','api'=>'⚡','saas'=>'☁️']; @endphp
          <div style="width:2.5rem;height:2.5rem;border-radius:.5rem;background:var(--muted);
            border:1px solid var(--border);display:flex;align-items:center;
            justify-content:center;font-size:1.125rem;flex-shrink:0">
            {{ $typeIcons[$product->type] ?? '📦' }}
          </div>
          <div>
            <div style="font-size:.9375rem;font-weight:600;color:var(--foreground)">{{ $product->name }}</div>
            <div style="display:flex;align-items:center;gap:.375rem;margin-top:.2rem;flex-wrap:wrap">
              <span style="font-size:.7rem;font-weight:600;padding:.1rem .45rem;border-radius:.3rem;
                {{ $licenseType === 'unlimited'
                    ? 'background:var(--foreground);color:var(--background)'
                    : 'background:var(--muted);border:1px solid var(--border);color:var(--foreground)' }}">
                {{ $licenseType === 'unlimited' ? 'Extended' : 'Regular' }}
              </span>
              <span style="font-size:.72rem;color:var(--muted-foreground)">v{{ $product->version }}</span>
            </div>
          </div>
        </div>
      </div>

      {{-- Price breakdown --}}
      <div style="padding:1.125rem;border-bottom:1px solid var(--border)">
        <div style="display:flex;justify-content:space-between;font-size:.875rem;margin-bottom:.5rem">
          <span style="color:var(--muted-foreground)">Base price</span>
          <span style="font-weight:500;color:var(--foreground)">{{ fmt_price($product->priceFor($licenseType)) }}</span>
        </div>

        @if($t['rate'] > 0)
        @foreach($t['rules'] as $rule)
        @php $ruleAmt = round($licensePrice * (float)$rule->rate / 100 / $exR, 2); @endphp
        <div style="display:flex;justify-content:space-between;font-size:.875rem;margin-bottom:.5rem">
          <span style="color:var(--muted-foreground)">
            {{ $rule->name }} ({{ number_format((float)$rule->rate,1) }}%)
          </span>
          <span style="color:var(--foreground)">+ {{ $sym }}{{ number_format($ruleAmt,2) }}</span>
        </div>
        @endforeach
        @else
        <div style="display:flex;justify-content:space-between;font-size:.875rem;margin-bottom:.5rem">
          <span style="color:var(--muted-foreground)">Tax</span>
          <span style="color:#16a34a;font-weight:500">None</span>
        </div>
        @endif
      </div>

      {{-- Total --}}
      <div style="padding:1.125rem">
        <div style="display:flex;justify-content:space-between;align-items:center">
          <span style="font-size:1rem;font-weight:700;color:var(--foreground)">Total</span>
          <span style="font-size:1.25rem;font-weight:800;color:var(--foreground)">{{ $t['total'] }}</span>
        </div>
        @if($uc && !$uc->is_base)
        <div style="font-size:.72rem;color:var(--muted-foreground);text-align:right;margin-top:.25rem">
          ≈ converted to {{ $uc->code }}
        </div>
        @endif
      </div>
    </div>

    {{-- Security badges --}}
    <div style="display:flex;align-items:center;justify-content:center;gap:1.25rem;
      margin-top:1rem;padding:.875rem;background:var(--card);border:1px solid var(--border);
      border-radius:var(--radius)">
      @foreach([
        ['M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z','Secure'],
        ['M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z','Encrypted'],
        ['M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z','Instant License'],
      ] as [$path,$badge])
      <div style="display:flex;align-items:center;gap:.375rem;font-size:.7rem;color:var(--muted-foreground)">
        <svg width="13" height="13" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="{{ $path }}"/>
        </svg>
        {{ $badge }}
      </div>
      @endforeach
    </div>
  </div>

</div>

<script>
// Sync border colours when page loads
document.querySelectorAll('input[name="gateway"]:checked, input[name="license_type"]:checked').forEach(function(inp) {
  inp.closest('label').style.borderColor = 'var(--foreground)';
});
</script>

@endsection
