@php
/** @var \App\Models\Job $job */
/** @var string|null $clientSecret */   // payment_intent_client_secret (optional)
/** @var string|null $setupSecret */    // setup_intent_client_secret (optional)
/** @var \App\Models\Payment|null $payment */   // optional, if controller passed it
/** @var \App\Models\Deposit|null $deposit */   // optional, if controller passed it

use Illuminate\Support\Carbon;

/* -------- helpers consistent with pay.blade -------- */
$toCents = function ($v): int {
    if (is_null($v)) return 0;
    if (is_int($v)) return $v;
    if (is_numeric($v) && str_contains((string) $v, '.')) return (int) round(((float) $v) * 100);
    return (int) $v;
};
$formatMoney = function (int $cents, string $cur = 'NZD'): string {
    $amount = number_format($cents / 100, 2);
    $symbol = match (strtoupper($cur)) {
        'NZD' => 'NZ$', 'AUD' => 'A$', 'USD' => '$', 'GBP' => '£', 'EUR' => '€', default => ''
    };
    return $symbol ? $symbol . $amount : ($amount . ' ' . strtoupper($cur));
};

/* ---------------- dates (same style as pay.blade) ---------------- */
$tz = $job->timezone ?? config('app.timezone', 'UTC');
$startAt = $job->start_at ? Carbon::parse($job->start_at)->timezone($tz) : null;
$endAt   = $job->end_at   ? Carbon::parse($job->end_at)->timezone($tz)   : null;

$fmt = fn (Carbon $c) => $c->isoFormat('ddd D MMM, HH:mm');
$durationLabel = null;
if ($startAt && $endAt && $endAt->greaterThan($startAt)) {
    $mins = $endAt->diffInMinutes($startAt);
    $days = intdiv($mins, 1440);
    $hours = intdiv($mins % 1440, 60);
    $m = $mins % 60;
    $parts = [];
    if ($days)  $parts[] = $days.'d';
    if ($hours) $parts[] = $hours.'h';
    if (!$days && !$hours && $m) $parts[] = $m.'m';
    $durationLabel = implode(' ', $parts);
}
$tzShort = $startAt?->format('T') ?? $endAt?->format('T') ?? strtoupper($tz);

/* ---------------- money / totals (mirror pay.blade) --------------- */
$currency   = $job->currency ?? optional($job->flow)->currency ?? 'NZD';
$totalCents = $toCents($job->charge_amount ?? 0);
$paidCents  = $toCents($job->paid_amount_cents ?? 0);
if ($paidCents === 0 && method_exists($job, 'payments')) {
    try {
        $paidCents = (int) $job->payments()
            ->whereIn('status', ['succeeded','captured'])
            ->sum('amount_cents');
    } catch (\Throwable $e) {}
}
$remainingCts = max(0, $totalCents - $paidCents);
$holdCents    = (int) (optional($job->flow)->hold_amount_cents ?? 0);

/* ---------------- urls / keys ---------------- */
$stripeKey = config('services.stripe.key');
$backUrl   = route('portal.pay.show.job', ['job' => $job->getKey()]);
$recordUrl = route('portal.pay.recordPaid', ['job' => $job->getKey()]);
@endphp

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Payment complete • {{ config('app.name') }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://js.stripe.com/v3/"></script>
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 24 24%22><text y=%2216%22 font-size=%2218%22>✅</text></svg>">
<style>
  .card-shadow { box-shadow: 0 10px 24px rgba(2,6,23,0.08), 0 6px 12px rgba(2,6,23,0.06); }
  .badge { border-radius: 9999px; padding: 2px 10px; font-size: 12px; font-weight: 600; }
  .badge-green { background: #DCFCE7; color: #166534; }
  .badge-amber { background: #FEF3C7; color: #92400E; }
  .badge-slate { background: #E2E8F0; color: #0F172A; }
  .mono { font-variant-numeric: tabular-nums; }
</style>
</head>
<body class="bg-slate-50 text-slate-900 antialiased">
<div class="min-h-screen">
  <!-- Header matches pay.blade -->
  <header class="border-b border-slate-200 bg-white/70 backdrop-blur supports-[backdrop-filter]:bg-white/60">
    <div class="mx-auto max-w-6xl px-4 sm:px-6 lg:px-8 py-4 flex items-center justify-between">
      <div class="flex items-center gap-3">
        <div class="h-9 w-9 rounded-2xl bg-slate-900 text-white grid place-items-center">🔒</div>
        <div>
          <div class="text-sm text-slate-500">Secured by</div>
          <div class="font-semibold tracking-tight">{{ config('app.name') }} (via Stripe)</div>
        </div>
      </div>
      <div class="hidden sm:flex items-center gap-2 text-sm">
        <span class="badge badge-slate">PCI DSS</span>
        <span class="badge badge-green">TLS 1.2+</span>
        <span class="badge badge-slate">3D Secure</span>
      </div>
    </div>
  </header>

  <main class="mx-auto max-w-6xl px-4 sm:px-6 lg:px-8 py-8">
    <!-- Title + rental line (same typography as pay.blade) -->
    <div class="mb-2">
      <h1 class="text-2xl sm:text-3xl font-semibold tracking-tight">Payment complete</h1>
      <p class="mt-1 text-slate-600">Job #{{ $job->id }} • {{ $job->title ?? 'Booking' }}</p>

      @if($startAt || $endAt)
        <div class="mt-2 text-sm text-slate-700 flex flex-wrap items-center gap-x-3 gap-y-1">
          <span class="font-medium">Rental:</span>
          <span class="mono">
            @if($startAt) {{ $fmt($startAt) }} @else <em>TBC</em> @endif
            <span class="opacity-60">→</span>
            @if($endAt) {{ $fmt($endAt) }} @else <em>TBC</em> @endif
          </span>
          <span class="text-slate-500">
            @if($durationLabel) ({{ $durationLabel }}) @endif • {{ $tzShort }}
          </span>
        </div>
      @endif
    </div>

    <!-- Alerts area (styled like pay page alert) -->
    <div id="pc-alert" class="hidden rounded-xl border border-amber-200 bg-amber-50 text-amber-800 p-3 text-sm mb-4">
      <span class="font-semibold">Heads up:</span>
      <span data-slot="message">Status not available.</span>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 items-start mt-4">
      <!-- LEFT: messages + what happens next + refs -->
      <section class="lg:col-span-2">
        <div class="bg-white rounded-2xl card-shadow p-6 space-y-4">
          <div id="messages" class="space-y-3">

            {{-- Prefer server-confirmed details when provided --}}
            @if(!empty($payment))
              <div class="rounded-xl px-4 py-3 text-sm border border-emerald-200 bg-emerald-50 text-emerald-700">
                <div class="font-semibold mb-1">Payment successful</div>
                <dl class="mono space-y-1">
                  <div class="flex justify-between gap-4"><dt class="text-slate-500">Amount</dt><dd>{{ $formatMoney((int)($payment->amount_cents ?? 0), strtoupper($payment->currency ?? ($job->currency ?? 'NZD'))) }}</dd></div>
                  <div class="flex justify-between gap-4"><dt class="text-slate-500">Intent</dt><dd>{{ $payment->stripe_payment_intent }}</dd></div>
                  @if(!empty($payment->card_brand) && !empty($payment->last4))
                    <div class="flex justify-between gap-4"><dt class="text-slate-500">Card</dt><dd>{{ strtoupper($payment->card_brand) }} •••• {{ $payment->last4 }}</dd></div>
                  @endif
                </dl>
              </div>
            @elseif(!empty($deposit))
              <div class="rounded-xl px-4 py-3 text-sm border border-blue-200 bg-blue-50 text-blue-800">
                <div class="font-semibold mb-1">Security hold authorised</div>
                <dl class="mono space-y-1">
                  <div class="flex justify-between gap-4"><dt class="text-slate-500">Amount</dt><dd>{{ $formatMoney((int)($deposit->amount_cents ?? 0), strtoupper($deposit->currency ?? ($job->currency ?? 'NZD'))) }}</dd></div>
                  <div class="flex justify-between gap-4"><dt class="text-slate-500">Authorization</dt><dd>{{ $deposit->stripe_payment_intent }}</dd></div>
                  <div class="flex justify-between gap-4"><dt class="text-slate-500">Status</dt><dd>{{ ucfirst($deposit->status ?? 'authorized') }}</dd></div>
                </dl>
              </div>
            @endif

            {{-- Keep the original warning but only when we truly have nothing client-side --}}
            @if(!$clientSecret && !$setupSecret && empty($payment) && empty($deposit))
              <div class="msg-warn rounded-xl px-4 py-3 text-sm font-medium bg-amber-50 text-amber-800 border border-amber-200">
                No confirmation details found on this page. If you just paid, your receipt will arrive by email shortly.
              </div>
            @endif
          </div>

          <div class="rounded-xl border border-slate-200 p-4 bg-slate-50/60">
            <h2 class="font-semibold mb-2">What happens next</h2>
            <ul class="text-sm text-slate-700 list-disc pl-5 space-y-1">
              <li>If your card required extra authentication, the payment may show as <strong>processing</strong> for a short time.</li>
              <li>We’ll email a receipt to the address on file (and to the one you entered during checkout, if provided).</li>
              @if($holdCents > 0)
                <li>A refundable security hold of <strong>{{ $formatMoney($holdCents, $currency) }}</strong> may appear as “pending” on your card. It is not a charge and will be released per our policy.</li>
              @endif
              <li>Need help? Reply to this email or contact support with Job #{{ $job->id }}.</li>
            </ul>
          </div>

          <div id="ids-panel" class="hidden rounded-xl border border-slate-200 p-4">
            <h2 class="font-semibold mb-2">Stripe references</h2>
            <dl class="text-sm text-slate-700 space-y-2 mono">
              <div class="flex items-center justify-between gap-4">
                <dt class="text-slate-500">PaymentIntent</dt>
                <dd><span id="pi-id" class="font-medium">—</span> <span id="pi-status" class="ml-2 text-slate-500"></span></dd>
              </div>
              <div class="flex items-center justify-between gap-4">
                <dt class="text-slate-500">SetupIntent</dt>
                <dd><span id="si-id" class="font-medium">—</span> <span id="si-status" class="ml-2 text-slate-500"></span></dd>
              </div>
            </dl>
          </div>
        </div>
      </section>

      <!-- RIGHT: summary (same card look as pay.blade) -->
      <aside class="lg:col-span-1">
        <div class="bg-white rounded-2xl card-shadow p-6 sticky top-6">
          <div class="flex items-center justify-between">
            <h2 class="font-semibold">Payment summary</h2>
            @if($remainingCts === 0)
              <span class="badge badge-green">Paid</span>
            @else
              <span class="badge badge-amber">Unpaid</span>
            @endif
          </div>

          <dl class="mt-4 space-y-3">
            <div class="flex items-center justify-between text-sm">
              <dt class="text-slate-600">Total</dt>
              <dd class="font-medium">{{ $formatMoney($totalCents, $currency) }}</dd>
            </div>
            <div class="flex items-center justify-between text-sm">
              <dt class="text-slate-600">Paid so far</dt>
              <dd class="font-medium">{{ $formatMoney($paidCents, $currency) }}</dd>
            </div>
            <div class="h-px bg-slate-200 my-2"></div>
            <div class="flex items-center justify-between">
              <dt class="text-slate-700 font-medium">Balance</dt>
              <dd class="text-lg font-semibold">{{ $formatMoney(max(0, $totalCents - $paidCents), $currency) }}</dd>
            </div>
            @if($holdCents > 0)
              <div class="h-px bg-slate-200 my-2"></div>
              <div class="text-xs text-slate-600">
                A refundable security hold of <strong>{{ $formatMoney($holdCents, $currency) }}</strong> was authorized (not charged).
              </div>
            @endif
          </dl>
        </div>
      </aside>
    </div>
  </main>
</div>

<script>
(() => {
  const pk = @json($stripeKey);
  const recordUrl = @json($recordUrl);

  const alertBox = document.getElementById('pc-alert');
  const alertMsg = alertBox?.querySelector('[data-slot="message"]');
  const messages = document.getElementById('messages');
  const idsPanel = document.getElementById('ids-panel');
  const piIdEl   = document.getElementById('pi-id');
  const piStEl   = document.getElementById('pi-status');
  const siIdEl   = document.getElementById('si-id');
  const siStEl   = document.getElementById('si-status');

  // --- message helpers (de-dup aware) ---
  const baseCls = 'rounded-xl px-4 py-3 text-sm font-medium border ';
  const clsMap  = {ok:'bg-emerald-50 text-emerald-700 border-emerald-200', warn:'bg-amber-50 text-amber-800 border-amber-200', err:'bg-rose-50 text-rose-700 border-rose-200'};

  const seen = new Set();
  // seed de-dup with any server-rendered messages
  Array.from(messages.querySelectorAll('div')).forEach(d => seen.add('warn::' + d.textContent.trim()));

  const addMsg = (type, text) => {
    const el = document.createElement('div');
    el.className = baseCls + (clsMap[type] || 'bg-slate-50 text-slate-700 border-slate-200');
    el.textContent = text;
    messages.appendChild(el);
  };
  const addMsgUnique = (type, text) => {
    const key = type + '::' + (text || '');
    if (seen.has(key)) return;
    seen.add(key);
    addMsg(type, text);
  };
  const showAlert = msg => { if (alertBox && alertMsg) { alertMsg.textContent = msg; alertBox.classList.remove('hidden'); } };

  const qs = new URLSearchParams(window.location.search);
  const piSecret = @json($clientSecret) || qs.get('payment_intent_client_secret');
  const siSecret = @json($setupSecret)  || qs.get('setup_intent_client_secret');
  const piIdFromUrl   = qs.get('payment_intent') || null;
  const holdPiFromUrl = qs.get('hold_intent')    || null;

  // Self-heal: if redirected back with PI, tell server once so Job=paid & Deposit saved
  if (piIdFromUrl && recordUrl) {
    const key = 'jobPaidPosted:{{ $job->id }}:' + piIdFromUrl;
    if (!sessionStorage.getItem(key)) {
      fetch(recordUrl, {
        method:'POST',
        credentials: 'same-origin',
        headers:{'Content-Type':'application/json','X-CSRF-TOKEN': @json(csrf_token())},
        body: JSON.stringify({ payment_intent: piIdFromUrl, hold_intent: holdPiFromUrl || null, status:'succeeded' })
      }).then(()=>sessionStorage.setItem(key,'1')).catch(()=>{});
    }
  }

  if (!pk) {
    showAlert('Payment processed, but publishable key is missing so we cannot display live status here.');
    if (!piSecret && !siSecret) addMsgUnique('warn','No confirmation details found on this page. If you just paid, your receipt will arrive by email shortly.');
    return;
  }

  const stripe = Stripe(pk);

  (async () => {
    let sawAny = false;
    try {
      if (piSecret) {
        const {paymentIntent} = await stripe.retrievePaymentIntent(piSecret);
        sawAny = true;
        idsPanel.classList.remove('hidden');
        piIdEl.textContent = paymentIntent?.id || '—';
        piStEl.textContent = paymentIntent ? `(${paymentIntent.status})` : '';
        switch (paymentIntent?.status) {
          case 'succeeded':
            addMsgUnique('ok','Final payment succeeded ✅');
            break;
          case 'processing':
            addMsgUnique('warn','Your payment is processing. We’ll email you once it’s confirmed.');
            break;
          case 'requires_action':
            addMsgUnique('warn','Additional authentication may be required to complete your payment.');
            break;
          default:
            addMsgUnique('err','We could not confirm the final payment. Please contact support.');
        }
      }
      if (siSecret) {
        const {setupIntent} = await stripe.retrieveSetupIntent(siSecret);
        sawAny = true;
        idsPanel.classList.remove('hidden');
        siIdEl.textContent = setupIntent?.id || '—';
        siStEl.textContent = setupIntent ? `(${setupIntent.status})` : '';
        if (setupIntent?.status === 'succeeded' || setupIntent?.status === 'processing') {
          addMsgUnique('ok','Your card has been saved for permitted off-session charges.');
        } else {
          addMsgUnique('warn','We could not save your card; you can try again from the payment page.');
        }
      }
    } catch (e) {
      showAlert(e?.message || 'Unable to retrieve payment status.');
    }
  })();
})();
</script>

<script>
  (function () {
    // Stripe adds these query params after redirect:
    // payment_intent, payment_intent_client_secret, setup_intent, setup_intent_client_secret, redirect_status
    const qs = new URLSearchParams(location.search);

    const payload = {
      payment_intent: qs.get('payment_intent') || null,
      // rarely used here, but harmless to pass through:
      hold_intent: qs.get('setup_intent') || null,
      // optionally tell the server how big the hold should be (falls back to Job/Flow)
      // requested_hold_cents: {{ (int) ($holdCents ?? 0) }},
    };

    if (!payload.payment_intent && !payload.hold_intent) return;

    fetch(@json(route('portal.pay.recordPaid', ['job' => $job->id])), {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // include token if your route is NOT CSRF-exempt:
        'X-CSRF-TOKEN': @json(csrf_token()),
      },
      credentials: 'same-origin',
      body: JSON.stringify(payload),
    }).catch(() => {});
  })();
</script>


</body>
</html>
