@extends('layouts.app')

@section('title', 'Change Plan')
@section('heading', 'Change subscription plan')

@section('content')
@php
    $symbol = config('app.currency_symbol', '₹');
    $currentPlan = $company->subscriptionPlan;
    $seatUsed = $company->activeEmployeeCount();
    $seatLimit = $company->employeeSeatLimit();
    $input = 'mt-1 w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20';
    $selectedPlanId = (int) old('subscription_plan_id', $company->subscription_plan_id);
@endphp
<div class="w-full" x-data="{ selectedPlanId: {{ $selectedPlanId ?: 'null' }} }">
    <x-superadmin.page-header
        eyebrow="Billing"
        title="Change plan"
        subtitle="Assign a yearly team plan to {{ $company->name }} and record the offline payment."
    >
        <x-slot:actions>
            <a href="{{ route('superadmin.companies.index') }}" class="inline-flex rounded-xl border border-slate-200 px-4 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50">Back to companies</a>
        </x-slot:actions>
    </x-superadmin.page-header>

    <section class="mb-6 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">{{ $company->name }} · yearly catalogue</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-3">
            <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>
    </section>

    <form action="{{ route('superadmin.companies.change-plan.store', $company) }}" method="post" class="space-y-6" id="change-plan-form">
        @csrf
        <input type="hidden" name="billing_cycle" value="yearly">

        <section class="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm sm:p-6">
            <h3 class="text-sm font-semibold text-slate-900">Choose yearly plan</h3>
            <p class="mt-1 text-sm text-slate-500">Pricing is yearly team-size only. No monthly billing.</p>

            <div class="mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
                @foreach($plans as $plan)
                    @php
                        $effective = $plan->effectiveYearlyPrice();
                        $strike = $plan->displayStrikePrice();
                        $isCurrent = (int) $company->subscription_plan_id === (int) $plan->id;
                    @endphp
                    <label
                        class="relative flex cursor-pointer flex-col rounded-2xl border bg-white p-4 shadow-sm transition"
                        :class="selectedPlanId == {{ (int) $plan->id }} ? 'border-primary ring-2 ring-primary/20' : 'border-slate-200 hover:border-slate-300'"
                    >
                        <input
                            type="radio"
                            name="subscription_plan_id"
                            value="{{ $plan->id }}"
                            class="sr-only"
                            data-yearly="{{ $plan->base_price_yearly }}"
                            data-effective="{{ $effective }}"
                            @checked(old('subscription_plan_id', $company->subscription_plan_id) == $plan->id)
                            x-on:change="selectedPlanId = {{ (int) $plan->id }}"
                            required
                        >
                        <div class="absolute right-3 top-3 flex flex-wrap justify-end gap-1">
                            @if($isCurrent)
                                <span class="inline-flex rounded-full bg-slate-100 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-slate-600">Current</span>
                            @endif
                            @if($plan->is_popular)
                                <span class="inline-flex rounded-full bg-primary px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-white">Popular</span>
                            @endif
                            @if($plan->is_custom)
                                <span class="inline-flex rounded-full bg-slate-100 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-slate-600">Custom</span>
                            @endif
                        </div>
                        <div class="pr-16">
                            <h4 class="text-base font-semibold text-slate-900">{{ $plan->name }}</h4>
                            @if($plan->description)
                                <p class="mt-0.5 text-xs text-slate-500">{{ Str::limit($plan->description, 70) }}</p>
                            @endif
                        </div>
                        <div class="mt-3">
                            @if($strike)
                                <p class="text-xs text-slate-400 line-through">{{ $symbol }}{{ number_format($strike, 0) }}/yr</p>
                            @endif
                            <p class="text-2xl font-bold tracking-tight text-slate-900">
                                {{ $symbol }}{{ number_format($effective, 0) }}<span class="text-sm font-medium text-slate-400">/yr</span>
                            </p>
                        </div>
                        <div class="mt-3 rounded-xl border border-slate-200 bg-slate-50/80 px-3 py-2">
                            <p class="text-[10px] font-semibold uppercase tracking-wide text-slate-400">Seat limit</p>
                            <p class="mt-0.5 text-sm font-semibold text-slate-900">{{ $plan->employee_limit ?? 'Unlimited' }}</p>
                        </div>
                    </label>
                @endforeach
            </div>
            @error('subscription_plan_id') <p class="mt-2 text-xs text-red-600">{{ $message }}</p> @enderror
            @error('billing_cycle') <p class="mt-2 text-xs text-red-600">{{ $message }}</p> @enderror
        </section>

        <section class="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm sm:p-6">
            <h3 class="text-sm font-semibold text-slate-900">Billing details</h3>
            <div class="mt-4 grid gap-4 sm:grid-cols-2">
                <div>
                    <label for="employee_count" class="block text-[11px] font-semibold uppercase tracking-wide text-slate-400">Employee count (record)</label>
                    <input type="number" name="employee_count" id="employee_count" value="{{ old('employee_count', max(1, (int) ($company->total_users ?? $seatUsed ?: 1))) }}" step="1" min="1" required class="{{ $input }}">
                    <p class="mt-1 text-xs text-slate-500">Stored on the payment record. Plan price is flat yearly.</p>
                    @error('employee_count') <p class="mt-1 text-xs text-red-600">{{ $message }}</p> @enderror
                </div>
                <div>
                    <label for="licence_expire_on" class="block text-[11px] font-semibold uppercase tracking-wide text-slate-400">Licence expire on</label>
                    <input type="date" name="licence_expire_on" id="licence_expire_on" value="{{ old('licence_expire_on', $company->licence_expire_on?->format('Y-m-d') ?? now()->addYear()->format('Y-m-d')) }}" required class="{{ $input }}">
                    @error('licence_expire_on') <p class="mt-1 text-xs text-red-600">{{ $message }}</p> @enderror
                </div>
                <div>
                    <label class="block text-[11px] font-semibold uppercase tracking-wide text-slate-400">Estimated yearly total</label>
                    <p id="estimated-total" class="mt-1 rounded-xl border border-slate-200 bg-slate-50/80 px-3 py-2.5 text-base font-bold text-slate-900">{{ $symbol }}0</p>
                </div>
                <div>
                    <label for="paid_at" class="block text-[11px] font-semibold uppercase tracking-wide text-slate-400">Paid at</label>
                    <input type="date" name="paid_at" id="paid_at" value="{{ old('paid_at', now()->format('Y-m-d')) }}" class="{{ $input }}">
                    @error('paid_at') <p class="mt-1 text-xs text-red-600">{{ $message }}</p> @enderror
                </div>
                <div class="sm:col-span-2">
                    <label for="notes" class="block text-[11px] font-semibold uppercase tracking-wide text-slate-400">Notes</label>
                    <textarea name="notes" id="notes" rows="2" class="{{ $input }}">{{ old('notes') }}</textarea>
                    @error('notes') <p class="mt-1 text-xs text-red-600">{{ $message }}</p> @enderror
                </div>
            </div>

            <div class="mt-6 flex flex-wrap gap-3 border-t border-slate-100 pt-5">
                <button type="submit" class="inline-flex rounded-xl bg-primary px-4 py-2.5 text-sm font-semibold text-white shadow-sm hover:opacity-95">Update plan &amp; record payment</button>
                <a href="{{ route('superadmin.companies.index') }}" class="inline-flex rounded-xl border border-slate-200 px-4 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50">Cancel</a>
            </div>
        </section>
    </form>
</div>
@endsection

@push('scripts')
<script>
    (() => {
        const form = document.getElementById('change-plan-form');
        if (!form) return;

        const totalNode = document.getElementById('estimated-total');
        const symbol = @json($symbol);

        const selectedPlanRadio = () => form.querySelector('input[name="subscription_plan_id"]:checked');

        const recalc = () => {
            const selectedPlan = selectedPlanRadio();
            if (!selectedPlan) {
                totalNode.textContent = `${symbol}0`;
                return;
            }

            const effective = parseFloat(selectedPlan.dataset.effective || selectedPlan.dataset.yearly || '0') || 0;
            totalNode.textContent = `${symbol}${effective.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 2 })}`;
        };

        form.querySelectorAll('input[name="subscription_plan_id"]').forEach((radio) => {
            radio.addEventListener('change', recalc);
        });

        recalc();
    })();
</script>
@endpush
