@extends('layouts.app')
@section('title', 'System Settings')
@section('content')
<x-ui.form-shell
    title="System Settings"
    description="Configure operational defaults, identity verification, notification channels, security policy and optional business modules."
    :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Settings'],['label'=>'System Settings']]"
    :narrow="true"
>
    <form method="POST" action="{{ route('admin.system-settings.update') }}" class="mf-form">
        @csrf
        @method('PUT')
        <input type="hidden" name="modules_present" value="1">
        <input type="hidden" name="sms_settings_present" value="1">
        <input type="hidden" name="identity_settings_present" value="1">

        <x-ui.form-section title="Regional & session defaults" description="Keep global behavior consistent for all users unless a later module defines a more specific rule.">
            <x-ui.form-grid>
                <div class="mf-col-5"><label class="mf-field-label">Timezone</label><input class="mf-input" name="timezone" value="{{ old('timezone',$settings['timezone'] ?? 'Africa/Dar_es_Salaam') }}" required></div>
                <div class="mf-col-3"><label class="mf-field-label">Date format</label><select class="mf-input" name="date_format">@foreach(['d/m/Y','Y-m-d','d M Y'] as $v)<option value="{{ $v }}" @selected(old('date_format',$settings['date_format'] ?? 'd/m/Y')===$v)>{{ $v }}</option>@endforeach</select></div>
                <div class="mf-col-4"><label class="mf-field-label">Session timeout</label><input type="number" min="5" max="1440" class="mf-input" name="session_timeout_minutes" value="{{ old('session_timeout_minutes',$settings['session_timeout_minutes'] ?? 120) }}"><p class="mf-field-help">Minutes before an inactive authenticated session expires.</p></div>
            </x-ui.form-grid>
        </x-ui.form-section>

        <x-ui.form-section title="Customer NIN / NIDA" description="Control NIN verification and configure the NIDA provider used to fetch customer identity details.">
            <div class="space-y-3">
                <label class="mf-option w-full items-start">
                    <input type="checkbox" name="nin_lookup_enabled" value="1" @checked((string) old('nin_lookup_enabled',$settings['nin_lookup_enabled'] ?? '0') === '1')>
                    <span>
                        <span class="block font-medium">Enable NIN verification and NIDA lookup</span>
                        <span class="block text-xs text-muted-foreground">When enabled, the customer form validates 20-digit NIN values and shows the Fetch action.</span>
                    </span>
                </label>

                <div>
                    <label class="mf-field-label" for="nida_api_url">NIDA API URL</label>
                    <input
                        id="nida_api_url"
                        type="url"
                        class="mf-input"
                        name="nida_api_url"
                        value="{{ old('nida_api_url',$settings['nida_api_url'] ?? '') }}"
                        placeholder="https://provider.example.tz/api/nida/lookup"
                        autocomplete="off"
                    >
                    <p class="mf-field-help">Enter the HTTPS base endpoint supplied by your NIDA or authorized identity provider. The system appends the customer's 20-digit NIN to this URL when Fetch is used.</p>
                </div>

                <div class="rounded-md border border-border bg-muted/20 p-3 text-xs text-muted-foreground">
                    <span class="font-medium text-foreground">When verification is disabled:</span> staff can still select “With NIN” and enter the NIN manually. The system stores the number as entered without calling the provider or enforcing the 20-digit API format.
                </div>
            </div>
        </x-ui.form-section>

        <x-ui.form-section title="SMS Notifications" description="Configure the SMS gateway used for customer and operational text messages. The API Key is encrypted and never shown after saving.">
            <div class="space-y-3">
                <label class="mf-option w-full">
                    <input type="checkbox" name="sms_enabled" value="1" @checked((string) old('sms_enabled',$settings['sms_enabled'] ?? '0') === '1')>
                    <span>
                        <span class="block font-medium">Enable SMS notifications</span>
                        <span class="block text-xs text-muted-foreground">Live notifications will only be sent when the gateway is enabled and fully configured.</span>
                    </span>
                </label>

                <x-ui.form-grid>
                    <div class="mf-col-8">
                        <label class="mf-field-label" for="sms_api_url">API URL</label>
                        <input id="sms_api_url" type="url" class="mf-input" name="sms_api_url" value="{{ old('sms_api_url',$settings['sms_api_url'] ?? '') }}" placeholder="https://messaging-service.co.tz/api/sms/v1/text/single">
                        <p class="mf-field-help">For NextSMS use <span class="font-medium">https://messaging-service.co.tz/api/sms/v1/text/single</span>. If only <span class="font-medium">https://messaging-service.co.tz</span> is saved, the system will resolve it automatically.</p>
                    </div>
                    <div class="mf-col-4">
                        <label class="mf-field-label" for="sms_sender_id">Sender ID</label>
                        <input id="sms_sender_id" class="mf-input" name="sms_sender_id" maxlength="64" value="{{ old('sms_sender_id',$settings['sms_sender_id'] ?? '') }}" placeholder="Approved sender ID">
                    </div>
                </x-ui.form-grid>

                <x-ui.form-grid>
                    <div class="mf-col-8">
                        <label class="mf-field-label" for="sms_api_key">API Key</label>
                        <input id="sms_api_key" type="password" class="mf-input" name="sms_api_key" value="" autocomplete="new-password" placeholder="{{ $smsApiKeyConfigured ? 'Leave blank to keep the saved API Key' : 'Paste your API Key' }}">
                        <p class="mf-field-help">
                            @if($smsApiKeyConfigured)
                                <span class="font-medium">API Key saved.</span> Leave this field blank unless you want to replace it.
                            @else
                                Required before SMS can be enabled or tested. The credential is encrypted before it is stored.
                            @endif
                        </p>
                    </div>
                    <div class="mf-col-4">
                        <label class="mf-field-label" for="sms_timeout_seconds">Request timeout</label>
                        <input id="sms_timeout_seconds" type="number" min="3" max="60" class="mf-input" name="sms_timeout_seconds" value="{{ old('sms_timeout_seconds',$settings['sms_timeout_seconds'] ?? 15) }}">
                        <p class="mf-field-help">Seconds to wait for the SMS provider.</p>
                    </div>
                </x-ui.form-grid>
            </div>
        </x-ui.form-section>

        <x-ui.form-section title="Modules" description="Turn optional modules on or off for the whole business. Disabling a module hides its navigation and blocks its routes, but existing records remain safely stored.">
            <div class="space-y-2">
                @foreach($moduleSettings as $key=>$module)
                    <label class="mf-option w-full">
                        <input type="checkbox" name="modules[{{ $key }}]" value="1" @checked(old('modules.'.$key,$module['enabled']))>
                        <span>
                            <span class="block font-medium">{{ $module['label'] }}</span>
                            <span class="block text-xs text-muted-foreground">{{ $module['description'] }}</span>
                        </span>
                    </label>
                @endforeach
            </div>
            <p class="mf-field-help mt-2">Module switches affect availability only. Turning a module off does not delete transactions, assets, reports, history or audit records.</p>
        </x-ui.form-section>

        <x-ui.form-section title="Security policy" description="Organization-wide authentication requirements.">
            <label class="mf-option"><input type="checkbox" name="require_2fa" value="1" @checked(old('require_2fa',$settings['require_2fa'] ?? '0')==='1')><span><span class="block font-medium">Require two-factor authentication</span><span class="block text-xs text-muted-foreground">Applied when the configured 2FA provider is enabled.</span></span></label>
        </x-ui.form-section>

        <x-ui.form-actions><button class="mf-btn mf-btn-primary">Save system settings</button></x-ui.form-actions>
    </form>

    <form method="POST" action="{{ route('admin.daily-reports.settings.update') }}" class="mf-form mt-4">
        @csrf
        @method('PUT')

        <x-ui.form-section title="Daily report delivery" description="Configure the channels used to send manager-confirmed daily branch reports. Recipient management and report history remain on the Daily Branch Reports page.">
            <div class="space-y-3">
                <x-ui.form-grid>
                    <label class="mf-option mf-col-6 w-full">
                        <input type="checkbox" name="email_enabled" value="1" @checked((string) old('email_enabled',$settings['email_enabled'] ?? '0') === '1')>
                        <span>
                            <span class="block font-medium">Send reports by email</span>
                            <span class="block text-xs text-muted-foreground">Uses the application's configured Laravel mail transport.</span>
                        </span>
                    </label>

                    <label class="mf-option mf-col-6 w-full">
                        <input type="checkbox" name="whatsapp_enabled" value="1" @checked((string) old('whatsapp_enabled',$settings['whatsapp_enabled'] ?? '0') === '1')>
                        <span>
                            <span class="block font-medium">Send reports by WhatsApp</span>
                            <span class="block text-xs text-muted-foreground">Uses a WhatsApp Cloud API-compatible messages endpoint.</span>
                        </span>
                    </label>
                </x-ui.form-grid>

                <x-ui.form-grid>
                    <div class="mf-col-7">
                        <label class="mf-field-label" for="whatsapp_api_endpoint">WhatsApp API endpoint</label>
                        <input id="whatsapp_api_endpoint" type="url" class="mf-input" name="whatsapp_api_endpoint" value="{{ old('whatsapp_api_endpoint',$business->whatsapp_api_endpoint) }}" placeholder="https://graph.facebook.com/vXX.X/PHONE_NUMBER_ID/messages">
                        <p class="mf-field-help">Save the complete messages endpoint supplied by your WhatsApp provider.</p>
                    </div>
                    <div class="mf-col-5">
                        <label class="mf-field-label" for="whatsapp_api_token">WhatsApp API token</label>
                        <input id="whatsapp_api_token" type="password" class="mf-input" name="whatsapp_api_token" value="" autocomplete="new-password" placeholder="{{ $whatsappTokenConfigured ? 'Leave blank to keep saved token' : 'Paste API token' }}">
                        <p class="mf-field-help">{{ $whatsappTokenConfigured ? 'Token saved and encrypted. Leave blank to keep it.' : 'The token is encrypted before storage.' }}</p>
                    </div>
                </x-ui.form-grid>
            </div>

            <x-ui.form-actions>
                <a class="mf-btn" href="{{ route('admin.daily-reports.index') }}">Manage report recipients</a>
                <button class="mf-btn mf-btn-primary" type="submit">Save report delivery</button>
            </x-ui.form-actions>
        </x-ui.form-section>
    </form>

    <form method="POST" action="{{ route('admin.system-settings.sms.test') }}" class="mf-form mt-4">
        @csrf
        <x-ui.form-section title="Send Test SMS" description="Send one real message using the saved API URL, Sender ID and API Key to confirm that the SMS gateway credentials are working.">
            @if(session('sms_test_success'))
                <div class="mf-alert mf-alert-success flex items-start gap-3" role="status">
                    <svg class="mt-0.5 h-5 w-5 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M20 6 9 17l-5-5" />
                    </svg>
                    <div>
                        <div class="font-semibold">Test SMS sent successfully</div>
                        <div class="mt-0.5 text-sm">{{ session('sms_test_success') }}</div>
                    </div>
                </div>
            @endif

            @if(session('sms_test_error'))
                <div class="mf-alert mf-alert-danger flex items-start gap-3" role="alert">
                    <svg class="mt-0.5 h-5 w-5 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v4m0 4h.01M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z" />
                    </svg>
                    <div>
                        <div class="font-semibold">Test SMS could not be sent</div>
                        <div class="mt-0.5 text-sm">{{ session('sms_test_error') }}</div>
                    </div>
                </div>
            @endif

            <x-ui.form-grid>
                <div class="mf-col-5">
                    <label class="mf-field-label" for="sms_test_phone">Test phone number</label>
                    <input id="sms_test_phone" class="mf-input" name="sms_test_phone" value="{{ old('sms_test_phone') }}" placeholder="0756123456" required>
                    <p class="mf-field-help">Local Tanzanian numbers are automatically converted to 255 format.</p>
                </div>
                <div class="mf-col-7">
                    <label class="mf-field-label" for="sms_test_message">Test message</label>
                    <textarea id="sms_test_message" class="mf-input" name="sms_test_message" rows="3" maxlength="480" required>{{ old('sms_test_message', 'Test SMS from '.$business->name.'.') }}</textarea>
                </div>
            </x-ui.form-grid>

            <p class="mf-field-help mt-2">Save the SMS configuration above before testing. A test can be sent even when live SMS notifications are disabled.</p>
            <x-ui.form-actions><button class="mf-btn mf-btn-primary" type="submit">Send Test SMS</button></x-ui.form-actions>
        </x-ui.form-section>
    </form>
</x-ui.form-shell>
@endsection
