@extends('layouts.app')
@section('title','Lipa kwa WiFi — '.$router->name)

@section('content')
<div style="max-width:460px;margin:0 auto">
  <h1 style="margin:0 0 10px;font-size:22px">Lipa kifurushi cha WiFi</h1>
  <div class="muted" style="margin-bottom:16px">
    Router: <strong>{{ $router->name }}</strong> ({{ $router->site }})
  </div>

  @if(session('error'))
    <div class="card" style="border-color:var(--bb-red);color:var(--bb-red);margin-bottom:12px">
      {{ session('error') }}
    </div>
  @endif

  <div class="card full" style="padding:18px 16px">
    <form method="POST" action="{{ route('pay.initiate', $router) }}" id="payForm">
      @csrf

      <div style="margin-bottom:10px">
        <label class="label">Chagua Mtandao</label>
        <select name="operator" class="input" required>
          @foreach($operators as $label => $value)
            <option value="{{ $value }}" @selected(old('operator')===$value)>{{ $label }}</option>
          @endforeach
        </select>
      </div>

      <div style="margin-bottom:10px">
        <label class="label">Weka Namba ya Simu</label>
        <input type="tel" name="phone" class="input"
          placeholder="weka namba hapa"
          value="{{ old('phone') }}"
          required id="phoneInput">
        <div class="muted" style="font-size:12px;margin-top:4px">
          Tutabadilisha moja kwa moja kuwa muundo <strong>255xxxxxxxxx</strong>.
        </div>
      </div>

      <div style="margin-bottom:10px">
        <label class="label">Chagua Kifurushi</label>
        <select name="plan_id" class="input" required>
          @foreach($plans as $plan)
            <option value="{{ $plan->id }}">
              {{ $plan->name }} – {{ number_format($plan->price) }} {{ $plan->currency ?? 'TZS' }}
            </option>
          @endforeach
        </select>
      </div>

      <div style="margin-bottom:14px">
        <div style="font-size:13px;margin-bottom:6px">
          Bonyeza <strong>'Lipa sasa'</strong> kufanya malipo
        </div>
        <div style="display:flex;align-items:flex-start;gap:6px">
          <div style="width:10px;height:10px;border-radius:999px;background:#2563eb;margin-top:4px"></div>
          <div>
            <strong>AzamPay</strong><br>
            <span class="muted" style="font-size:12px">
              Airtel, Tigo, Halopesa, Azampesa
            </span>
          </div>
        </div>
      </div>

      <button class="btn" style="width:100%;font-size:16px;padding:12px 0">
        Lipa Sasa
      </button>
    </form>
  </div>
</div>

<script>
(function(){
  const input = document.getElementById('phoneInput');
  if(!input) return;

  input.addEventListener('blur', function(){
    let v = this.value.replace(/\D+/g,'');
    if (!v) return;

    if (v.startsWith('0') && v.length === 10) {
      v = '255' + v.substring(1);
    } else if (v.length === 9) {
      v = '255' + v;
    }
    this.value = v;
  });
})();
</script>
@endsection
