@extends('layouts.app')

@section('title', 'Subscription & plans')
@section('heading', 'Subscription & plans')

@section('content')
@php
    $symbol = config('app.currency_symbol', '₹');
    $currentPlan = $company->subscriptionPlan;
    $daysLeft = $company->daysUntilLicenceExpiry();
    $defaultSelectedId = null;
    foreach ($plans as $p) {
        if ($p->isFreeDefault() || $p->is_custom) {
            continue;
        }
        if ((int) $company->subscription_plan_id === (int) $p->id) {
            continue;
        }
        if (isset($quotes[$p->id])) {
            $defaultSelectedId = (int) $p->id;
            break;
        }
    }
@endphp

<div
    class="w-full"
    x-data="{
        selectedPlanId: {{ $defaultSelectedId ? (int) $defaultSelectedId : 'null' }},
        coupon: @js(old('coupon_code', '')),
        couponMsg: '',
        couponOk: false,
        selectPlan(id) { this.selectedPlanId = id; },
        syncCoupon() {
            document.querySelectorAll('.js-form-coupon').forEach((el) => {
                el.value = (this.coupon || '').trim().toUpperCase();
            });
        },
        applyCoupon() {
            this.syncCoupon();
            const code = (this.coupon || '').trim();
            if (!code) {
                this.couponMsg = 'Enter a coupon code first.';
                this.couponOk = false;
                return;
            }
            this.couponMsg = 'Coupon will be applied at checkout / offline request.';
            this.couponOk = true;
        }
    }"
    x-init="syncCoupon()"
>
    {{-- Page intro --}}
    <div class="mb-6">
        <p class="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Billing</p>
        <h2 class="mt-1 text-2xl font-bold tracking-tight text-slate-900 sm:text-3xl">Subscription &amp; plans</h2>
        <p class="mt-2 max-w-2xl text-sm text-slate-500 sm:text-base">
            Your licence controls how many employees can punch in. Renew or upgrade at any time.
        </p>
    </div>

    {{-- Expiry / suspended alert --}}
    @if(!$company->isAccessAllowed() || $company->isInExpiryWarningWindow())
        <div class="mb-6 flex flex-col gap-3 rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3.5 sm:flex-row sm:items-center sm:justify-between">
            <div class="flex items-start gap-3" style="align-items: center;">
                <span class="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-amber-100 text-amber-700">
                    <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                        <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>
                </span>
                <div class="text-sm text-amber-950">
                    @if(!$company->isAccessAllowed())
                        <p class="font-semibold">Your company status is {{ $company->status }}.</p>
                        <p class="mt-0.5 text-amber-800">Renew or upgrade a plan below to restore access.</p>
                    @elseif($daysLeft !== null && $daysLeft < 0)
                        <p class="font-semibold">Your licence expired on {{ $company->licence_expire_on?->format('d M Y') }}. Renew now to avoid suspension.</p>
                    @elseif($daysLeft === 0)
                        <p class="font-semibold">Your licence expires today. Renew now to avoid interruption.</p>
                    @else
                        <p class="font-semibold">Your licence expires in {{ $daysLeft }} day{{ $daysLeft === 1 ? '' : 's' }} ({{ $company->licence_expire_on?->format('d M Y') }}).</p>
                    @endif
                </div>
            </div>
            <a href="#choose-plan" class="inline-flex shrink-0 items-center justify-center rounded-xl border border-amber-300 bg-white px-3.5 py-2 text-sm font-semibold text-amber-900 shadow-sm hover:bg-amber-50">
                Manage subscription
            </a>
        </div>
    @endif

    {{-- Current plan --}}
    <section class="mb-8 rounded-2xl border border-slate-200 bg-white p-5 shadow-sm sm:p-6">
        <div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
            <div>
                <h3 class="text-lg font-semibold text-slate-900">Current plan</h3>
                <p class="mt-1 text-sm text-slate-500">Renews yearly · managed by your workspace owner</p>
            </div>
            @if($company->isAccessAllowed())
                <span class="inline-flex items-center rounded-full bg-emerald-50 px-2.5 py-1 text-xs font-semibold text-emerald-700 ring-1 ring-inset ring-emerald-200">Active</span>
            @else
                <span class="inline-flex items-center rounded-full bg-amber-50 px-2.5 py-1 text-xs font-semibold text-amber-800 ring-1 ring-inset ring-amber-200">{{ ucfirst($company->status) }}</span>
            @endif
        </div>

        <div class="mt-5 grid gap-3 sm:grid-cols-4">
            <div class="rounded-xl border border-slate-200 bg-slate-50/80 px-4 py-3">
                <p class="text-[11px] font-semibold uppercase tracking-wide text-slate-400">Plan</p>
                <p class="mt-1 text-base font-semibold text-slate-900">{{ $currentPlan?->name ?? 'No plan' }}</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-slate-50/80 px-4 py-3">
                <p class="text-[11px] font-semibold uppercase tracking-wide text-slate-400">Seats used</p>
                <p class="mt-1 text-base font-semibold text-slate-900">{{ $seatUsed }}{{ $seatLimit !== null ? ' / '.$seatLimit : '' }}</p>
            </div>
            <div class="rounded-xl border border-slate-200 bg-slate-50/80 px-4 py-3">
                <p class="text-[11px] font-semibold uppercase tracking-wide text-slate-400">Licence until</p>
                <p class="mt-1 text-base font-semibold text-slate-900">{{ $company->licence_expire_on?->format('d M Y') ?? '—' }}</p>
            </div>
        </div>

        <div class="mt-5 border-t border-slate-100 pt-5">
            <label for="coupon_code" class="block text-[11px] font-semibold uppercase tracking-wide text-slate-400">Coupon code (optional)</label>
            <div class="mt-2 flex flex-col gap-2 sm:flex-row sm:items-center">
                <div class="relative flex-1">
                    <span class="pointer-events-none absolute inset-y-0 left-3 flex items-center text-slate-400">
                        <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z"/></svg>
                    </span>
                    <input
                        type="text"
                        id="coupon_code"
                        x-model="coupon"
                        @input="syncCoupon()"
                        placeholder="SAVE10"
                        class="w-full rounded-xl border border-slate-200 bg-white py-2.5 pl-10 pr-3 text-sm uppercase text-slate-900 placeholder:normal-case placeholder:text-slate-400 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20"
                    >
                </div>
                <button
                    type="button"
                    @click="applyCoupon()"
                    class="inline-flex items-center justify-center rounded-xl border border-slate-200 bg-slate-50 px-4 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-100"
                >
                    Apply coupon
                </button>
            </div>
            <p class="mt-2 text-sm" :class="couponOk ? 'text-emerald-600' : 'text-slate-500'" x-text="couponMsg" x-show="couponMsg" x-cloak></p>
        </div>
    </section>

    {{-- Choose a plan --}}
    <section id="choose-plan" class="scroll-mt-24">
        <div class="mb-4">
            <h3 class="text-lg font-semibold text-slate-900">Choose a plan</h3>
            <p class="mt-1 text-sm text-slate-500">All plans are billed yearly. Prices are exclusive of applicable taxes.</p>
        </div>

        <div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
            @foreach($plans as $plan)
                @php
                    $quote = $quotes[$plan->id] ?? null;
                    $mode = $quote['checkout_mode'] ?? ($quote['mode'] ?? 'renew');
                    $isCurrent = (int) $company->subscription_plan_id === (int) $plan->id;
                    $effective = $plan->effectiveYearlyPrice();
                    $strike = $plan->displayStrikePrice();
                    $canCheckout = ! $plan->isFreeDefault() && ! $plan->is_custom && $quote && ($quote['total'] ?? 0) >= 0.01;
                    $isUpgrade = (bool) ($quote['is_upgrade'] ?? false);
                    $midCycleBlocked = ! $isCurrent
                        && ! $plan->is_custom
                        && ! $plan->isFreeDefault()
                        && ! $quote
                        && $company->licence_expire_on
                        && ! $company->isLicenceExpired()
                        && $company->isAccessAllowed();
                @endphp

                <article
                    @if($canCheckout)
                        @click="selectPlan({{ (int) $plan->id }})"
                    @endif
                    class="relative flex flex-col rounded-2xl border bg-white p-5 shadow-sm transition
                        {{ $isCurrent ? 'border-slate-200' : 'border-slate-200 hover:border-slate-300' }}
                        {{ $canCheckout ? 'cursor-pointer' : '' }}"
                    :class="selectedPlanId === {{ (int) $plan->id }} ? 'border-primary ring-2 ring-primary/20' : ''"
                >
                    @if($isCurrent)
                        <span class="absolute right-4 top-4 inline-flex rounded-full bg-slate-100 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-slate-600">Current plan</span>
                    @elseif($canCheckout)
                        <span
                            x-show="selectedPlanId === {{ (int) $plan->id }}"
                            x-cloak
                            class="absolute right-4 top-4 inline-flex rounded-full bg-primary px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-white"
                        >Selected</span>
                    @endif

                    <div class="pr-20">
                        <h4 class="text-lg font-semibold text-slate-900">{{ $plan->is_custom ? 'Custom / Private' : $plan->name }}</h4>
                        <p class="mt-1 text-sm text-slate-500">
                            @if($plan->is_custom)
                                Negotiated package — talk to sales or request offline
                            @elseif($plan->description)
                                {{ $plan->description }}
                            @else
                                Up to {{ $plan->employee_limit ?? 'unlimited' }} users · yearly
                            @endif
                        </p>
                    </div>

                    <div class="mt-5">
                        @if($plan->is_custom)
                            <p class="text-3xl font-bold tracking-tight text-slate-900">Custom</p>
                        @else
                            @if($strike)
                                <p class="text-sm text-slate-400 line-through">{{ $symbol }}{{ number_format($strike, 0) }}/yr</p>
                            @endif
                            <p class="text-3xl font-bold tracking-tight text-slate-900">
                                {{ $symbol }}{{ number_format($effective, 0) }}<span class="text-base font-medium text-slate-400">/yr</span>
                            </p>
                        @endif

                        @if($quote && $isUpgrade)
                            <p class="mt-2 text-sm font-semibold text-primary">Upgrade due today: {{ $symbol }}{{ number_format($quote['total'], 2) }}</p>
                            <p class="text-xs text-slate-500">{{ $quote['days_remaining'] }} days left · credit {{ $symbol }}{{ number_format($quote['unused_credit'] ?? 0, 2) }}</p>
                        @elseif($quote && ! $isCurrent)
                            <p class="mt-2 text-sm text-slate-500">Total payable: {{ $symbol }}{{ number_format($quote['total'], 2) }}</p>
                        @elseif($plan->isFreeDefault())
                            <p class="mt-2 text-sm text-slate-500">Up to {{ $plan->employee_limit ?? 10 }} users · first year</p>
                        @endif
                    </div>

                    <div class="mt-auto flex flex-col gap-2 pt-6">
                        @if($plan->isFreeDefault())
                            <button type="button" disabled class="w-full cursor-not-allowed rounded-xl bg-slate-100 px-4 py-2.5 text-sm font-semibold text-slate-400">
                                {{ $isCurrent ? 'Your current plan' : 'Not available' }}
                            </button>
                            <p class="text-center text-xs text-slate-400">Assigned automatically for new companies</p>

                        @elseif($plan->is_custom)
                            <form action="{{ route('subscription.request.store') }}" method="post" class="space-y-2" @click.stop>
                                @csrf
                                <input type="hidden" name="subscription_plan_id" value="{{ $plan->id }}">
                                <input type="hidden" name="mode" value="purchase">
                                <textarea name="notes" rows="3" required
                                          class="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm text-slate-800 placeholder:text-slate-400 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20"
                                          placeholder="Expected seats, requirements…">{{ old('notes') }}</textarea>
                                <button type="submit" class="w-full rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-sm font-semibold text-slate-800 hover:bg-slate-50">
                                    Request custom package
                                </button>
                            </form>

                        @elseif($isCurrent)
                            <button type="button" disabled class="w-full cursor-not-allowed rounded-xl bg-slate-100 px-4 py-2.5 text-sm font-semibold text-slate-400">
                                Your current plan
                            </button>
                            @if($quote && ($quote['total'] ?? 0) >= 0.01)
                                <form action="{{ route('subscription.request.store') }}" method="post" @click.stop>
                                    @csrf
                                    <input type="hidden" name="subscription_plan_id" value="{{ $plan->id }}">
                                    <input type="hidden" name="mode" value="renew">
                                    <input type="hidden" name="coupon_code" class="js-form-coupon" value="">
                                    <button type="submit" class="w-full text-center text-sm font-medium text-slate-500 hover:text-slate-800">
                                        Request offline renewal
                                    </button>
                                </form>
                            @endif

                        @elseif($midCycleBlocked)
                            <button type="button" disabled class="w-full cursor-not-allowed rounded-xl bg-slate-100 px-4 py-2.5 text-sm font-semibold text-slate-400">
                                Available at renewal
                            </button>
                            <p class="text-center text-xs text-slate-400">Downgrades are only available when renewing</p>

                        @elseif($canCheckout)
                            <div x-show="selectedPlanId === {{ (int) $plan->id }}" x-cloak class="space-y-2">
                                @if(!empty($razorpayKeyId))
                                    <button
                                        type="button"
                                        class="js-pay-online inline-flex w-full items-center justify-center gap-1 rounded-xl bg-primary px-4 py-2.5 text-sm font-semibold text-white shadow-sm hover:opacity-95"
                                        data-plan-id="{{ $plan->id }}"
                                        data-mode="{{ $mode }}"
                                        data-plan-name="{{ $plan->name }}"
                                        @click.stop
                                    >
                                        {{ $isUpgrade ? 'Upgrade & pay online' : 'Pay online (yearly)' }}
                                        <span aria-hidden="true">→</span>
                                    </button>
                                @endif
                                <form action="{{ route('subscription.request.store') }}" method="post" @click.stop>
                                    @csrf
                                    <input type="hidden" name="subscription_plan_id" value="{{ $plan->id }}">
                                    <input type="hidden" name="mode" value="{{ $mode }}">
                                    <input type="hidden" name="coupon_code" class="js-form-coupon" value="">
                                    <button type="submit" class="w-full text-center text-sm font-medium text-slate-500 hover:text-slate-800">
                                        Request offline payment
                                    </button>
                                </form>
                            </div>
                            <button
                                type="button"
                                x-show="selectedPlanId !== {{ (int) $plan->id }}"
                                class="inline-flex w-full items-center justify-center gap-1 rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-sm font-semibold text-slate-800 hover:bg-slate-50"
                            >
                                Select this plan <span aria-hidden="true">→</span>
                            </button>
                        @else
                            <button type="button" disabled class="w-full cursor-not-allowed rounded-xl bg-slate-100 px-4 py-2.5 text-sm font-semibold text-slate-400">
                                Not available
                            </button>
                        @endif
                    </div>
                </article>
            @endforeach
        </div>
    </section>
</div>
@endsection

@push('scripts')
@if(!empty($razorpayKeyId))
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
@endif
<script>
(() => {
    const csrf = document.querySelector('meta[name="csrf-token"]')?.content;

    document.querySelectorAll('.js-pay-online').forEach((btn) => {
        btn.addEventListener('click', async (event) => {
            event.preventDefault();
            event.stopPropagation();
            btn.disabled = true;
            const couponInput = document.getElementById('coupon_code');
            try {
                const res = await fetch(@json(route('subscription.checkout.order')), {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': csrf,
                    },
                    body: JSON.stringify({
                        subscription_plan_id: Number(btn.dataset.planId),
                        mode: btn.dataset.mode,
                        coupon_code: (couponInput?.value || '').trim() || null,
                    }),
                });
                const data = await res.json();
                if (!res.ok) {
                    alert(data.message || 'Unable to start payment.');
                    btn.disabled = false;
                    return;
                }
                const options = {
                    key: data.key,
                    amount: data.amount,
                    currency: data.currency,
                    name: 'KiyoHR Subscription',
                    description: btn.dataset.planName,
                    order_id: data.order_id,
                    handler: function (response) {
                        const form = document.createElement('form');
                        form.method = 'POST';
                        form.action = @json(route('subscription.checkout.verify'));
                        form.innerHTML = `
                            <input type="hidden" name="_token" value="${csrf}">
                            <input type="hidden" name="razorpay_order_id" value="${response.razorpay_order_id}">
                            <input type="hidden" name="razorpay_payment_id" value="${response.razorpay_payment_id}">
                            <input type="hidden" name="razorpay_signature" value="${response.razorpay_signature}">
                        `;
                        document.body.appendChild(form);
                        form.submit();
                    },
                    modal: { ondismiss: () => { btn.disabled = false; } },
                };
                const rzp = new Razorpay(options);
                rzp.open();
            } catch (e) {
                alert('Payment could not be started.');
                btn.disabled = false;
            }
        });
    });
})();
</script>
@endpush
