@extends('layouts.admin')
@section('title', 'Currencies')

@section('content')

{{-- Page header --}}
<div style="display:flex;align-items:flex-start;justify-content:space-between;gap:1rem;margin-bottom:1.5rem">
  <div>
    <h1 style="font-size:1.25rem;font-weight:800;color:var(--foreground);letter-spacing:-.025em;margin:0 0 .25rem">
      Currency Management
    </h1>
    <p style="font-size:.8125rem;color:var(--muted-foreground);margin:0">
      Configure currencies, symbols and exchange rates for the client-facing catalog.
    </p>
  </div>
  <div style="display:flex;align-items:center;gap:.5rem;flex-shrink:0">
    <form method="POST" action="{{ route('admin.currencies.update-rates') }}">
      @csrf
      <button type="submit" class="btn btn-sm"
        style="background:#16a34a;color:#fff;border:none"
        onmouseover="this.style.opacity='.85'" onmouseout="this.style.opacity='1'"
        onclick="this.disabled=true;this.innerText='Updating…';this.form.submit()">
        <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="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
        </svg>
        Update Live Rates
      </button>
    </form>
    <button type="button" class="btn btn-secondary btn-sm" onclick="showModal('recalc-modal')">
      <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="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 11h.01M12 11h.01M15 11h.01M4 20h16a2 2 0 002-2V6a2 2 0 00-2-2H4a2 2 0 00-2 2v12a2 2 0 002 2z"/>
      </svg>
      Recalculate Pricing
    </button>
    <button type="button" class="btn btn-primary btn-sm" onclick="showModal('add-modal')">
      <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="M12 4v16m8-8H4"/>
      </svg>
      Add Currency
    </button>
  </div>
</div>

{{-- Stat cards --}}
<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:1rem;margin-bottom:1.25rem">
  <div class="stat-card">
    <div class="stat-icon" style="background:var(--muted)">
      <svg width="18" height="18" fill="none" stroke="var(--muted-foreground)" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75"
          d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
      </svg>
    </div>
    <div class="stat-val">{{ $stats['total'] }}</div>
    <div class="stat-lbl">Total Currencies</div>
    <div class="stat-sub">in your catalog</div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:#f0fdf4">
      <svg width="18" height="18" fill="none" stroke="#16a34a" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75"
          d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
      </svg>
    </div>
    <div class="stat-val" style="color:#16a34a">{{ $stats['active'] }}</div>
    <div class="stat-lbl">Active</div>
    <div class="stat-sub">available for checkout</div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:#eff6ff">
      <svg width="18" height="18" fill="none" stroke="#2563eb" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75"
          d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"/>
      </svg>
    </div>
    <div class="stat-val" style="color:#2563eb">{{ $stats['base'] }}</div>
    <div class="stat-lbl">Base Currency</div>
    <div class="stat-sub">all rates relative to this</div>
  </div>
</div>


{{-- Exchange rate info banner --}}
@php
  $base   = $currencies->firstWhere('is_base', true);
  $others = $currencies->where('is_base', false)->where('is_active', true)->take(3)->values();
@endphp
<div class="card" style="padding:.75rem 1.125rem;margin-bottom:1.25rem;border-color:#bfdbfe;background:#eff6ff">
  <div style="display:flex;align-items:flex-start;gap:.625rem;font-size:.8125rem;color:#1e40af;line-height:1.6">
    <svg width="15" height="15" fill="none" stroke="#2563eb" 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>
    <div>
      <strong>Exchange Rate convention:</strong>
      Enter how many <strong>{{ $base?->code ?? 'base' }}</strong> equal 1 unit of that currency.
      Example — base = {{ $base?->code ?? '?' }}:
      @foreach($others as $c)
        <span class="badge b-blue" style="margin:0 .2rem;font-family:monospace">
          1 {{ $c->code }} ≈ {{ number_format($c->exchange_rate, 2) }}
        </span>
        @if(!$loop->last)<span style="color:#93c5fd;margin:0 .1rem">|</span>@endif
      @endforeach
      . Click <strong>Update Live Rates</strong> to auto-fill from a live API
      <span style="color:#60a5fa">(built-in fallback rates apply automatically if the API is unreachable)</span>.
    </div>
  </div>
</div>

{{-- Currencies table --}}
<div class="card">
  <div class="card-header">
    <div>
      <div class="card-title">Currencies</div>
      <div class="card-sub">{{ $currencies->count() }} configured &nbsp;·&nbsp; {{ $currencies->where('is_active',true)->count() }} active</div>
    </div>
    @php $lastUpdate = $currencies->whereNotNull('rates_updated_at')->sortByDesc('rates_updated_at')->first(); @endphp
    @if($lastUpdate?->rates_updated_at)
    <div style="font-size:.75rem;color:var(--muted-foreground);text-align:right">
      Rates updated {{ $lastUpdate->rates_updated_at->diffForHumans() }}<br>
      <span style="font-size:.7rem">Next auto-update: daily 00:00</span>
    </div>
    @endif
  </div>

  <table style="width:100%;border-collapse:collapse">
    <thead>
      <tr style="border-bottom:1px solid var(--border)">
        <th class="th">Code</th>
        <th class="th">Name</th>
        <th class="th" style="text-align:center">Symbol</th>
        <th class="th">Exchange Rate</th>
        <th class="th" style="text-align:center">Default</th>
        <th class="th" style="text-align:center">Status</th>
        <th class="th">Actions</th>
      </tr>
    </thead>
    <tbody>
      @forelse($currencies as $currency)
      <tr class="trow">

        {{-- Code --}}
        <td class="td">
          <div style="display:flex;align-items:center;gap:.5rem">
            <span style="font-size:.9375rem;font-weight:700;color:var(--foreground)">{{ $currency->code }}</span>
            @if($currency->is_base)
              <span class="badge b-blue">BASE</span>
            @endif
          </div>
        </td>

        {{-- Name --}}
        <td class="td" style="color:var(--foreground);font-weight:500">{{ $currency->name }}</td>

        {{-- Symbol --}}
        <td class="td" style="text-align:center;font-size:1.125rem;font-weight:600;color:var(--foreground)">
          {{ $currency->symbol }}
        </td>

        {{-- Rate (inline edit) --}}
        <td class="td">
          @if($currency->is_base)
            <div class="input" style="width:170px;background:var(--muted);color:var(--muted-foreground);
              cursor:not-allowed;font-family:monospace;font-size:.8125rem">
              1.000000 (base)
            </div>
          @else
            <form method="POST" action="{{ route('admin.currencies.update-rate', $currency) }}"
              style="display:flex;align-items:center;gap:.375rem">
              @csrf
              <input type="number" name="exchange_rate" class="input"
                style="width:150px;font-family:monospace;font-size:.8125rem"
                step="0.0001" min="0.0001"
                value="{{ number_format($currency->exchange_rate, 4) }}">
              <button type="submit" class="btn btn-xs"
                style="background:#f0fdf4;color:#16a34a;border:1px solid #bbf7d0;padding:.375rem .5rem"
                title="Save rate"
                onmouseover="this.style.background='#16a34a';this.style.color='#fff'"
                onmouseout="this.style.background='#f0fdf4';this.style.color='#16a34a'">
                <svg width="12" height="12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"/>
                </svg>
              </button>
            </form>
            @if($currency->rates_updated_at)
            <div style="font-size:.7rem;color:var(--muted-foreground);margin-top:.25rem">
              Updated {{ $currency->rates_updated_at->diffForHumans() }}
            </div>
            @endif
          @endif
        </td>

        {{-- Default --}}
        <td class="td" style="text-align:center">
          @if($currency->is_default)
            <span class="badge b-green">
              <svg width="10" height="10" fill="currentColor" viewBox="0 0 24 24" style="margin-right:.25rem">
                <path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 21 12 17.77 5.82 21 7 14.14l-5-4.87 6.91-1.01L12 2z"/>
              </svg>
              Default
            </span>
          @else
            <form method="POST" action="{{ route('admin.currencies.set-default', $currency) }}">
              @csrf
              <button type="submit" class="btn btn-secondary btn-xs">Set Default</button>
            </form>
          @endif
        </td>

        {{-- Status --}}
        <td class="td" style="text-align:center">
          @if($currency->is_active)
            <span class="badge b-green">Active</span>
          @else
            <span class="badge b-gray">Disabled</span>
          @endif
        </td>

        {{-- Actions --}}
        <td class="td">
          @if($currency->is_base && $currency->is_default)
            <span style="font-size:.8rem;color:var(--muted-foreground);display:flex;align-items:center;gap:.375rem">
              <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="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>
              Default — cannot delete
            </span>
          @else
            <div style="display:flex;align-items:center;gap:.375rem">

              @if(!$currency->is_base)
              {{-- Set Base --}}
              <form method="POST" action="{{ route('admin.currencies.set-base', $currency) }}">
                @csrf
                <button type="submit" class="btn btn-secondary btn-xs"
                  onclick="return confirm('Set {{ $currency->code }} as base currency? All other rates will need to be recalculated.')">
                  Set Base
                </button>
              </form>

              {{-- Enable / Disable --}}
              <form method="POST" action="{{ route('admin.currencies.toggle', $currency) }}">
                @csrf
                <button type="submit" class="btn btn-xs {{ $currency->is_active ? 'btn-danger' : 'btn-secondary' }}"
                  style="{{ $currency->is_active ? 'background:#fff7ed;color:#c2410c;border-color:#fed7aa' : '' }}">
                  <svg width="11" height="11" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    @if($currency->is_active)
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5"
                        d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"/>
                    @else
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5"
                        d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    @endif
                  </svg>
                  {{ $currency->is_active ? 'Disable' : 'Enable' }}
                </button>
              </form>
              @endif

              {{-- Delete --}}
              @if(!$currency->is_base && !$currency->is_default)
              <form method="POST" action="{{ route('admin.currencies.destroy', $currency) }}">
                @csrf @method('DELETE')
                <button type="submit" class="btn btn-danger btn-xs"
                  onclick="return confirm('Delete {{ $currency->code }}? This cannot be undone.')">
                  <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                  </svg>
                </button>
              </form>
              @endif

            </div>
          @endif
        </td>
      </tr>
      @empty
      <tr>
        <td colspan="7" style="padding:3rem;text-align:center;color:var(--muted-foreground);font-size:.875rem">
          No currencies configured yet. Click <strong>Add Currency</strong> to get started.
        </td>
      </tr>
      @endforelse
    </tbody>
  </table>
</div>


{{-- ══════════════════════════════════════════════
     ADD CURRENCY MODAL
═══════════════════════════════════════════════ --}}
<div id="add-modal" style="display:none;position:fixed;inset:0;z-index:500;
  align-items:center;justify-content:center;background:rgba(0,0,0,.5);backdrop-filter:blur(2px)">
  <div class="card" style="width:100%;max-width:460px;padding:0;overflow:hidden;
    box-shadow:0 20px 60px rgba(0,0,0,.15)">

    {{-- Modal header --}}
    <div class="card-header">
      <div class="card-title">Add Currency</div>
      <button type="button" class="btn btn-ghost btn-xs" onclick="hideModal('add-modal')"
        style="padding:.25rem .5rem;font-size:1.125rem;line-height:1">×</button>
    </div>

    {{-- Modal body --}}
    <form method="POST" action="{{ route('admin.currencies.store') }}" style="padding:1.375rem">
      @csrf
      <div style="display:flex;flex-direction:column;gap:1rem">

        <div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem">
          <div>
            <label>ISO Code <span style="color:var(--destructive)">*</span></label>
            <input type="text" name="code" class="input"
              style="font-family:monospace;font-weight:700;text-transform:uppercase;letter-spacing:.05em"
              maxlength="3" placeholder="USD" required
              oninput="this.value=this.value.toUpperCase()">
            <p style="font-size:.72rem;color:var(--muted-foreground);margin:.25rem 0 0">3-letter ISO 4217 code</p>
          </div>
          <div>
            <label>Symbol <span style="color:var(--destructive)">*</span></label>
            <input type="text" name="symbol" class="input"
              style="font-size:1.125rem;text-align:center"
              maxlength="10" placeholder="$" required>
          </div>
        </div>

        <div>
          <label>Currency Name <span style="color:var(--destructive)">*</span></label>
          <input type="text" name="name" class="input" placeholder="US Dollar" required>
        </div>

        <div>
          <label>
            Exchange Rate
            <span style="font-weight:400;color:var(--muted-foreground)">(how many {{ $stats['base'] }} = 1 unit)</span>
            <span style="color:var(--destructive)">*</span>
          </label>
          <input type="number" name="exchange_rate" class="input"
            style="font-family:monospace"
            step="0.0001" min="0.0001" placeholder="83.72" required>
          <p style="font-size:.72rem;color:var(--muted-foreground);margin:.25rem 0 0">
            Tip: add the currency, then click <strong>Update Live Rates</strong> to auto-fill.
          </p>
        </div>

      </div>

      <div style="display:flex;justify-content:flex-end;gap:.5rem;margin-top:1.375rem;padding-top:1rem;border-top:1px solid var(--border)">
        <button type="button" class="btn btn-secondary btn-sm" onclick="hideModal('add-modal')">Cancel</button>
        <button type="submit" class="btn btn-primary btn-sm">
          Add Currency
          <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="M9 5l7 7-7 7"/>
          </svg>
        </button>
      </div>
    </form>
  </div>
</div>


{{-- ══════════════════════════════════════════════
     RECALCULATE PRICING MODAL
═══════════════════════════════════════════════ --}}
<div id="recalc-modal" style="display:none;position:fixed;inset:0;z-index:500;
  align-items:center;justify-content:center;background:rgba(0,0,0,.5);backdrop-filter:blur(2px)">
  <div class="card" style="width:100%;max-width:500px;padding:0;overflow:hidden;
    box-shadow:0 20px 60px rgba(0,0,0,.15)">

    {{-- Modal header --}}
    <div class="card-header">
      <div class="card-title">Recalculate Product Pricing</div>
      <button type="button" class="btn btn-ghost btn-xs" onclick="hideModal('recalc-modal')"
        style="padding:.25rem .5rem;font-size:1.125rem;line-height:1">×</button>
    </div>

    {{-- Warning --}}
    <div style="padding:.875rem 1.375rem;background:#fffbeb;border-bottom:1px solid #fde68a">
      <div style="display:flex;align-items:flex-start;gap:.5rem">
        <svg width="15" height="15" fill="none" stroke="#d97706" viewBox="0 0 24 24" style="flex-shrink:0;margin-top:.1rem">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
            d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
        </svg>
        <p style="font-size:.8125rem;color:#92400e;margin:0;line-height:1.5">
          <strong>Warning:</strong> This permanently converts all product prices using the current
          exchange rates. Back up your data before proceeding.
        </p>
      </div>
    </div>

    {{-- Modal body --}}
    <form method="POST" action="{{ route('admin.currencies.recalculate') }}" style="padding:1.375rem">
      @csrf

      <div style="display:grid;grid-template-columns:1fr auto 1fr;align-items:end;gap:.75rem;margin-bottom:1rem">
        <div>
          <label>Convert FROM</label>
          <select name="from_currency" class="select">
            @foreach($currencies->where('is_active',true) as $c)
            <option value="{{ $c->code }}" @selected($c->is_base)>
              {{ $c->code }} — {{ $c->name }}
            </option>
            @endforeach
          </select>
        </div>

        <div style="padding-bottom:.5rem">
          <svg width="20" height="20" fill="none" stroke="var(--muted-foreground)" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3"/>
          </svg>
        </div>

        <div>
          <label>Convert TO</label>
          <select name="to_currency" class="select">
            @foreach($currencies->where('is_active',true) as $c)
            <option value="{{ $c->code }}" @selected(!$c->is_base && $c->is_default)>
              {{ $c->code }} — {{ $c->name }}
            </option>
            @endforeach
          </select>
        </div>
      </div>

      <p style="font-size:.8rem;color:var(--muted-foreground);margin-bottom:1.25rem">
        Uses the exchange rates stored in the table above. Make sure rates are up to date before recalculating.
      </p>

      <div style="display:flex;justify-content:flex-end;gap:.5rem;padding-top:1rem;border-top:1px solid var(--border)">
        <button type="button" class="btn btn-secondary btn-sm" onclick="hideModal('recalc-modal')">Cancel</button>
        <button type="submit" class="btn btn-sm"
          style="background:#d97706;color:#fff;border:none"
          onmouseover="this.style.opacity='.85'" onmouseout="this.style.opacity='1'"
          onclick="return confirm('This will update all product prices. Proceed?')">
          <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="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 11h.01M12 11h.01M15 11h.01M4 20h16a2 2 0 002-2V6a2 2 0 00-2-2H4a2 2 0 00-2 2v12a2 2 0 002 2z"/>
          </svg>
          Recalculate Prices
        </button>
      </div>
    </form>
  </div>
</div>

<script>
function showModal(id) { document.getElementById(id).style.display = 'flex'; }
function hideModal(id) { document.getElementById(id).style.display = 'none'; }
// Close on backdrop click
document.querySelectorAll('[id$="-modal"]').forEach(function(modal) {
  modal.addEventListener('click', function(e) {
    if (e.target === this) hideModal(this.id);
  });
});
</script>

@endsection
