<x-app-layout title="Integrations">
    <x-settings.page title="Integrations">
        <p class="text-sm text-slate-600">
            <strong class="font-semibold text-slate-800">Patient email and SMS work by default</strong> via suite messaging —
            set a Ladill mailbox and optional sender ID under
            <a href="{{ function_exists('ladill_account_url') ? ladill_account_url('/account/settings/messaging') : (config('smtp.messaging_settings_url') ?? '#') }}"
               class="text-teal-700 underline" target="_blank" rel="noopener">Account → Messaging</a>.
            Product SMS and Bird API keys below are optional (power users / custom keys).
            Connect Paystack, Flutterwave, or Hubtel so bill payments land in your account (0% Ladill fee).
        </p>

        @if (! $canManage)
            <p class="mt-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">You can view integrations, but only admins can change credentials.</p>
        @endif

        <div class="mt-6 space-y-6">
            <x-settings.card title="SMS" description="API key and approved sender ID.">
                @if ($credential->hasValidSms())
                    <div class="mb-4 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-800">
                        Connected · key {{ $credential->sms_api_key_prefix }}… · sender <strong>{{ $credential->sms_sender_id }}</strong>
                        @if ($credential->sms_validated_at)
                            · validated {{ $credential->sms_validated_at->diffForHumans() }}
                        @endif
                    </div>
                @elseif ($credential->sms_status === \App\Models\MessagingCredential::STATUS_INVALID)
                    <div class="mb-4 rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-800">
                        {{ $credential->sms_last_error ?: 'SMS credentials are invalid.' }}
                    </div>
                @endif

                @if ($canManage)
                    <form method="POST" action="{{ route('care.integrations.sms.save') }}" class="space-y-4">
                        @csrf
                        <div>
                            <label class="block text-sm font-medium text-slate-700">SMS API key</label>
                            <input type="password" name="sms_api_key" autocomplete="off" required
                                   placeholder="lsk_sms_live_…"
                                   class="mt-1 w-full rounded-lg border-slate-300 font-mono text-sm">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-slate-700">Sender ID</label>
                            <input type="text" name="sms_sender_id" maxlength="11" required
                                   value="{{ old('sms_sender_id', $credential->sms_sender_id) }}"
                                   placeholder="Approved sender ID"
                                   class="mt-1 w-full rounded-lg border-slate-300 text-sm">
                            <p class="mt-1 text-xs text-slate-500">Must match an approved sender ID on your SMS service (or the platform default).</p>
                        </div>
                        <div class="flex flex-wrap gap-2">
                            <button type="submit" class="btn-primary">Validate &amp; save</button>
                        </div>
                    </form>
                    @if ($credential->sms_api_key_encrypted || $credential->hasValidSms())
                        <div class="mt-3">
                            <x-confirm-dialog
                                name="disconnect-sms"
                                title="Disconnect SMS?"
                                message="Outbound SMS will stop until credentials are connected again."
                                :action="route('care.integrations.sms.disconnect')"
                                confirm-label="Disconnect"
                            >
                                <x-slot:trigger>
                                    <button type="button" class="text-sm text-rose-700 hover:underline">Disconnect</button>
                                </x-slot:trigger>
                            </x-confirm-dialog>
                        </div>
                    @endif
                @endif
            </x-settings.card>

            <x-settings.card title="Email" description="API key and from address on a verified domain.">
                @if ($credential->hasValidBird())
                    <div class="mb-4 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-800">
                        Connected · key {{ $credential->bird_api_key_prefix }}… · from
                        <strong>{{ $credential->bird_from_name ? $credential->bird_from_name.' <'.$credential->bird_from_email.'>' : $credential->bird_from_email }}</strong>
                        @if ($credential->bird_validated_at)
                            · validated {{ $credential->bird_validated_at->diffForHumans() }}
                        @endif
                    </div>
                @elseif ($credential->bird_status === \App\Models\MessagingCredential::STATUS_INVALID)
                    <div class="mb-4 rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-800">
                        {{ $credential->bird_last_error ?: 'Bird credentials are invalid.' }}
                    </div>
                @endif

                @if ($canManage)
                    <form method="POST" action="{{ route('care.integrations.bird.save') }}" class="space-y-4">
                        @csrf
                        <div>
                            <label class="block text-sm font-medium text-slate-700">Bird API key</label>
                            <input type="password" name="bird_api_key" autocomplete="off" required
                                   placeholder="lsk_live_…"
                                   class="mt-1 w-full rounded-lg border-slate-300 font-mono text-sm">
                            <p class="mt-1 text-xs text-slate-500">Use the HTTP API key from <a href="https://bird.ladill.com" target="_blank" rel="noopener" class="underline">bird.ladill.com</a> (starts with <code>lsk_live_</code>). Do not use the mailbox password.</p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-slate-700">From email</label>
                            <input type="email" name="bird_from_email" required
                                   value="{{ old('bird_from_email', $credential->bird_from_email) }}"
                                   placeholder="clinic@yourdomain.com"
                                   class="mt-1 w-full rounded-lg border-slate-300 text-sm">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-slate-700">From name</label>
                            <input type="text" name="bird_from_name" maxlength="100"
                                   value="{{ old('bird_from_name', $credential->bird_from_name) }}"
                                   placeholder="{{ $organization->name }}"
                                   class="mt-1 w-full rounded-lg border-slate-300 text-sm">
                        </div>
                        <div class="flex flex-wrap gap-2">
                            <button type="submit" class="btn-primary">Validate &amp; save</button>
                        </div>
                    </form>
                    @if ($credential->bird_api_key_encrypted || $credential->hasValidBird())
                        <div class="mt-3">
                            <x-confirm-dialog
                                name="disconnect-bird"
                                title="Disconnect email?"
                                message="Outbound email will stop until credentials are connected again."
                                :action="route('care.integrations.bird.disconnect')"
                                confirm-label="Disconnect"
                            >
                                <x-slot:trigger>
                                    <button type="button" class="text-sm text-rose-700 hover:underline">Disconnect</button>
                                </x-slot:trigger>
                            </x-confirm-dialog>
                        </div>
                    @endif
                @endif
            </x-settings.card>

            <x-settings.card title="Payment gateway" description="Encounter bill payments via your own Paystack, Flutterwave, or Hubtel account — 0% Ladill platform fee. Pro &amp; Enterprise only.">
                @if ($canUsePaymentGateway ?? false)
                    @if ($gateway?->isConfigured())
                        <div class="mb-4 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-800">
                            Connected · {{ $gatewayLabels[$gateway->provider] ?? ucfirst($gateway->provider) }}
                            @if (! $gateway->is_active)
                                · <span class="font-medium text-amber-800">disabled</span>
                            @endif
                        </div>
                    @else
                        <div class="mb-4 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800">
                            Online checkout stays disabled until a gateway is connected.
                        </div>
                    @endif

                    @if ($canManage)
                        <form method="POST" action="{{ route('care.integrations.gateway.save') }}" class="space-y-4">
                            @csrf
                            <div>
                                <label class="block text-sm font-medium text-slate-700">Provider</label>
                                <select name="gateway_provider" required class="mt-1 w-full rounded-lg border-slate-300 text-sm">
                                    <option value="">Select a provider</option>
                                    @foreach ($gatewayLabels as $value => $label)
                                        <option value="{{ $value }}" @selected(old('gateway_provider', $gateway?->provider) === $value)>{{ $label }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="grid gap-4 sm:grid-cols-2">
                                <div>
                                    <label class="block text-sm font-medium text-slate-700">Public key / Merchant account</label>
                                    <input type="text" name="gateway_public_key" value="{{ old('gateway_public_key') }}"
                                           placeholder="{{ $gateway?->public_key ? '•••• saved — leave blank to keep' : 'pk_live_… or Hubtel account #' }}"
                                           class="mt-1 w-full rounded-lg border-slate-300 font-mono text-sm" autocomplete="off">
                                    <p class="mt-1 text-xs text-slate-500">Hubtel: merchant account number. Paystack/Flutterwave: public key.</p>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-slate-700">Secret / API key</label>
                                    <input type="password" name="gateway_secret_key" value=""
                                           placeholder="{{ $gateway?->secret_key ? '•••• saved — leave blank to keep' : 'sk_live_…' }}"
                                           class="mt-1 w-full rounded-lg border-slate-300 font-mono text-sm" autocomplete="new-password">
                                </div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-slate-700">Webhook secret / Hubtel client auth (optional)</label>
                                <input type="password" name="gateway_webhook_secret" value=""
                                       placeholder="{{ $gateway?->webhook_secret ? '•••• saved — leave blank to keep' : 'Optional · Hubtel: clientId:clientSecret' }}"
                                       class="mt-1 w-full rounded-lg border-slate-300 font-mono text-sm" autocomplete="new-password">
                            </div>
                            <label class="inline-flex items-center gap-2 text-sm text-slate-700">
                                <input type="hidden" name="gateway_is_active" value="0">
                                <input type="checkbox" name="gateway_is_active" value="1" @checked(old('gateway_is_active', $gateway?->is_active ?? true)) class="rounded border-slate-300 text-teal-600 focus:ring-teal-500">
                                Gateway enabled for encounter billing
                            </label>
                            <div class="flex flex-wrap gap-2">
                                <button type="submit" class="btn-primary">Save gateway</button>
                            </div>
                        </form>
                        @if ($gateway)
                            <div class="mt-3">
                                <x-confirm-dialog
                                    name="disconnect-gateway"
                                    title="Disconnect payment gateway?"
                                    message="Online checkout for bills will stop until credentials are connected again."
                                    :action="route('care.integrations.gateway.disconnect')"
                                    confirm-label="Disconnect"
                                >
                                    <x-slot:trigger>
                                        <button type="button" class="text-sm text-rose-700 hover:underline">Disconnect</button>
                                    </x-slot:trigger>
                                </x-confirm-dialog>
                            </div>
                        @endif
                    @endif
                @else
                    <div class="rounded-lg border border-teal-100 bg-teal-50 px-4 py-3 text-sm text-teal-900">
                        <p class="font-medium">Your own payment gateway is a Pro feature</p>
                        <p class="mt-1 text-teal-800/80">Upgrade to Care Pro or Enterprise to connect Paystack, Flutterwave, or Hubtel for encounter bill payments with 0% Ladill fee.</p>
                        <a href="{{ route('care.pro.index') }}" class="mt-3 inline-flex text-sm font-semibold text-teal-700 hover:text-teal-900">View plans →</a>
                    </div>
                @endif
            </x-settings.card>
        </div>

        <p class="mt-6 text-sm text-slate-500">
            <a href="{{ route('care.settings') }}" class="text-teal-700 underline">← Back to facility settings</a>
        </p>
    </x-settings.page>
</x-app-layout>
