@extends('layouts.app')

@section('title', 'Integrations')

@section('content')
<div class="page-header">
    <div class="page-header-left"><h4 class="fw-bolder mb-0">Integrations</h4></div>
</div>

<div class="main-content">
    @if (session('success'))
        <div class="alert alert-success">{{ session('success') }}</div>
    @endif
    @if ($errors->any())
        <div class="alert alert-danger">{{ $errors->first() }}</div>
    @endif

    <div class="alert alert-info">
        API secrets are encrypted. Leave an existing secret blank when updating other settings.
        Enable an integration only after its credentials have been saved.
    </div>
    <div class="card mb-4"><div class="card-header"><h5 class="card-title">Live-provider readiness</h5></div><div class="card-body">
        <div class="row g-3">@foreach($readiness as $provider=>$state)<div class="col-md-4"><div class="border rounded p-3 h-100">
            <div class="d-flex justify-content-between"><strong>{{ ucwords(str_replace('_',' ',$provider)) }}</strong><span class="badge {{ $state['configured']&&$state['healthy']&&!$state['expired']?'bg-success':'bg-warning' }}">{{ $state['configured']?'Configured':'Incomplete' }}</span></div>
            @if($state['missing']->isNotEmpty())<small class="d-block text-danger">Missing: {{ $state['missing']->join(', ') }}</small>@endif
            @if($state['expired'])<small class="d-block text-danger">Credentials expired—refresh required.</small>@endif
            <small class="d-block">Health: {{ $state['healthy']?'Passed':'Not yet passed' }}</small>
            <small class="d-block">Last successful operation: {{ $state['last_success'] ?: 'Not verified' }}</small>
            <small class="d-block">Last inbound webhook: {{ $state['last_inbound'] ?: 'Not verified' }}</small>
            <small class="d-block">Failed operations: {{ $state['failed'] }}</small>
        </div></div>@endforeach</div>
        <p class="text-muted mt-3 mb-0">A provider is live-verified only after configuration is complete, Test Connection passes, and at least one real inbound or outbound operation is recorded successfully.</p>
    </div></div>

    <div class="row">
        @php
            $providers = [
                'facebook' => [
                    'title' => 'Facebook Lead Ads',
                    'credentials' => ['access_token' => 'Page Access Token','webhook_secret'=>'Webhook Secret','refresh_token'=>'OAuth Refresh Token','client_id'=>'OAuth Client ID','client_secret'=>'OAuth Client Secret'],
                    'configuration' => ['page_id' => 'Facebook Page ID', 'lead_form_id' => 'Lead Form ID','oauth_token_url'=>'OAuth Token Refresh URL'],
                    'action' => ['route' => 'integrations.facebook.sync', 'label' => 'Import New Leads'],
                ],
                'whatsapp' => [
                    'title' => 'WhatsApp Cloud API',
                    'credentials' => ['access_token' => 'Permanent Access Token','webhook_secret'=>'Webhook Secret','refresh_token'=>'OAuth Refresh Token','client_id'=>'OAuth Client ID','client_secret'=>'OAuth Client Secret'],
                    'configuration' => ['phone_number_id' => 'Phone Number ID', 'business_account_id' => 'WhatsApp Business Account ID','oauth_token_url'=>'OAuth Token Refresh URL'],
                ],
                'mailchimp' => [
                    'title' => 'Mailchimp',
                    'credentials' => ['api_key' => 'API Key','webhook_secret'=>'Webhook Secret'],
                    'configuration' => ['server_prefix' => 'Server Prefix (for example us21)', 'audience_id' => 'Audience/List ID'],
                    'action' => ['route' => 'integrations.mailchimp.sync', 'label' => 'Sync CRM Contacts'],
                ],
                'jira' => [
                    'title' => 'Jira Cloud',
                    'credentials' => ['email' => 'Atlassian Account Email', 'api_token' => 'API Token','webhook_secret'=>'Webhook Secret','refresh_token'=>'OAuth Refresh Token','client_id'=>'OAuth Client ID','client_secret'=>'OAuth Client Secret'],
                    'configuration' => ['site_url' => 'Site URL (https://company.atlassian.net)', 'project_key' => 'Project Key', 'issue_type' => 'Issue Type (Task/Bug)','oauth_token_url'=>'OAuth Token Refresh URL'],
                ],
                'google_calendar' => [
                    'title' => 'Google Calendar',
                    'credentials' => ['access_token' => 'OAuth Access Token','refresh_token'=>'OAuth Refresh Token','client_id'=>'OAuth Client ID','client_secret'=>'OAuth Client Secret'],
                    'configuration' => ['calendar_id' => 'Calendar ID (primary is supported)','oauth_token_url'=>'OAuth Token Refresh URL'],
                ],
                'outlook_calendar' => [
                    'title' => 'Outlook / Microsoft 365 Calendar',
                    'credentials' => ['access_token' => 'Microsoft Graph Access Token','refresh_token'=>'OAuth Refresh Token','client_id'=>'Application Client ID','client_secret'=>'Application Client Secret'],
                    'configuration' => ['calendar_id' => 'Microsoft Calendar ID','oauth_token_url'=>'OAuth Token Refresh URL'],
                ],
            ];
        @endphp

        @foreach ($providers as $provider => $definition)
            @php($setting = $settings->get($provider))
            <div class="col-xl-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">{{ $definition['title'] }}</h5>
                        <span class="badge {{ $setting?->enabled ? 'bg-success' : 'bg-secondary' }}">
                            {{ $setting?->enabled ? 'Enabled' : 'Disabled' }}
                        </span>
                        <span class="badge {{ $setting?->health_status === 'healthy' ? 'bg-soft-success text-success' : ($setting?->health_status === 'unknown' ? 'bg-soft-secondary text-secondary' : 'bg-soft-danger text-danger') }}">
                            Health: {{ ucfirst($setting?->health_status ?? 'unknown') }}
                        </span>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="{{ route('integrations.update', $provider) }}">
                            @csrf @method('PUT')
                            @foreach ($definition['credentials'] as $key => $label)
                                <div class="mb-3">
                                    <label class="form-label">{{ $label }}</label>
                                    <input type="{{ str_contains($key, 'token') || str_contains($key, 'key') ? 'password' : 'text' }}"
                                        name="credentials[{{ $key }}]" class="form-control"
                                        placeholder="{{ ($setting?->credentials[$key] ?? null) ? 'Saved — leave blank to keep' : $label }}"
                                        autocomplete="new-password">
                                </div>
                            @endforeach
                            <div class="mb-3">
                                <label class="form-label">Credentials expire at</label>
                                <input type="datetime-local" name="credentials_expires_at" class="form-control"
                                    value="{{ $setting?->credentials_expires_at?->format('Y-m-d\\TH:i') }}">
                            </div>
                            @foreach ($definition['configuration'] as $key => $label)
                                <div class="mb-3">
                                    <label class="form-label">{{ $label }}</label>
                                    <input type="text" name="configuration[{{ $key }}]" class="form-control"
                                        value="{{ old("configuration.$key", $setting?->configuration[$key] ?? '') }}">
                                </div>
                            @endforeach
                            <div class="form-check form-switch mb-3">
                                <input type="hidden" name="enabled" value="0">
                                <input class="form-check-input" type="checkbox" name="enabled" value="1"
                                    id="enabled-{{ $provider }}" @checked($setting?->enabled)>
                                <label class="form-check-label" for="enabled-{{ $provider }}">Enable integration</label>
                            </div>
                            @if ((int) auth()->user()->is_admin === 1)
                                <button class="btn btn-primary" type="submit">Save Settings</button>
                            @endif
                        </form>

                        @if ((int) auth()->user()->is_admin === 1 && $setting)
                            <form method="POST" action="{{ route('integrations.test', $provider) }}" class="d-inline">
                                @csrf
                                <button class="btn btn-light mt-3" type="submit">Test Connection</button>
                            </form>
                        @endif
                        @if ($setting?->last_synced_at)
                            <small class="d-block text-muted mt-2">Last sync: {{ $setting->last_synced_at }}</small>
                        @endif
                        @if($setting?->last_health_checked_at)<small class="d-block text-muted">Health checked: {{ $setting->last_health_checked_at }}</small>@endif
                        @if($setting?->last_refreshed_at)<small class="d-block text-success">Credentials refreshed: {{ $setting->last_refreshed_at }}</small>@endif
                        @if($setting?->refresh_error)<small class="d-block text-danger">Refresh: {{ $setting->refresh_error }}</small>@endif
                        @if ($setting?->last_error)
                            <small class="d-block text-danger mt-2">{{ $setting->last_error }}</small>
                        @endif

                        @if (isset($definition['action']) && $setting?->enabled)
                            <form method="POST" action="{{ route($definition['action']['route']) }}" class="mt-3">
                                @csrf
                                <button class="btn btn-success" type="submit">{{ $definition['action']['label'] }}</button>
                            </form>
                        @endif
                    </div>
                </div>
            </div>
        @endforeach
    </div>

    <div class="row">
        <div class="col-xl-6">
            <div class="card">
                <div class="card-header"><h5 class="card-title">Send WhatsApp Message</h5></div>
                <div class="card-body">
                    <form method="POST" action="{{ route('integrations.whatsapp.send') }}">
                        @csrf
                        <label class="form-label">Customer phone (international format)</label>
                        <input class="form-control mb-3" name="recipient" placeholder="+94771234567" required>
                        <label class="form-label">Message</label>
                        <textarea class="form-control mb-3" name="message" rows="4" maxlength="4096" required></textarea>
                        <button class="btn btn-success" type="submit">Send WhatsApp</button>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-xl-6">
            <div class="card">
                <div class="card-header"><h5 class="card-title">Create Jira Issue from Ticket</h5></div>
                <div class="card-body">
                    <form method="POST" action="{{ route('integrations.jira.issue') }}">
                        @csrf
                        <label class="form-label">CRM Ticket</label>
                        <select class="form-control mb-3" name="ticket_id" required>
                            <option value="">Select Ticket</option>
                            @foreach ($tickets as $ticket)
                                <option value="{{ $ticket->id }}">#{{ $ticket->id }} — {{ $ticket->topic ?: $ticket->contact_name }}</option>
                            @endforeach
                        </select>
                        <button class="btn btn-primary" type="submit">Create Jira Issue</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-header"><h5 class="card-title">Field Mapping</h5><small class="text-muted">Map provider payload paths to approved CRM fields. Value map must be JSON, for example {"Done":8}.</small></div>
        <div class="card-body">
            <form method="POST" action="{{ route('integrations.mappings.store') }}" class="row g-2 align-items-end">
                @csrf
                <div class="col-md-2"><label class="form-label">Provider</label><select class="form-control" name="provider">@foreach(['facebook','whatsapp','mailchimp','jira'] as $provider)<option>{{ $provider }}</option>@endforeach</select></div>
                <div class="col-md-2"><label class="form-label">CRM entity</label><select class="form-control" name="entity_type">@foreach(['lead','contact','message','ticket'] as $type)<option>{{ $type }}</option>@endforeach</select></div>
                <div class="col-md-3"><label class="form-label">External payload path</label><input class="form-control" name="external_field" placeholder="issue.fields.status.name" required></div>
                <div class="col-md-2"><label class="form-label">CRM field</label><input class="form-control" name="crm_field" placeholder="stage_id" required></div>
                <div class="col-md-2"><label class="form-label">Value map JSON</label><input class="form-control" name="value_map" placeholder='{"Done":8}'></div>
                <input type="hidden" name="enabled" value="1"><div class="col-md-1"><button class="btn btn-primary">Save</button></div>
            </form>
            <div class="table-responsive mt-4"><table class="table"><thead><tr><th>Provider</th><th>Entity</th><th>External</th><th>CRM</th><th>Value map</th><th></th></tr></thead><tbody>
                @forelse($mappings as $mapping)<tr><td>{{ ucfirst($mapping->provider) }}</td><td>{{ $mapping->entity_type }}</td><td><code>{{ $mapping->external_field }}</code></td><td><code>{{ $mapping->crm_field }}</code></td><td><code>{{ json_encode($mapping->value_map) }}</code></td><td><form method="POST" action="{{ route('integrations.mappings.destroy',$mapping) }}">@csrf @method('DELETE')<button class="btn btn-sm btn-outline-danger">Delete</button></form></td></tr>
                @empty
                    <tr class="integration-empty-row">
                        <td class="text-center text-muted">No field mappings configured.</td>
                        @for($column = 1; $column < 6; $column++)
                            <td aria-hidden="true"></td>
                        @endfor
                    </tr>
                @endforelse
            </tbody></table></div>
        </div>
    </div>

    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center"><h5 class="card-title">Synchronization Logs</h5><form method="GET" class="d-flex gap-2 flex-wrap"><input type="search" name="q" maxlength="100" value="{{ request('q') }}" class="form-control" placeholder="Search synchronization logs"><input type="date" name="date_from" value="{{ request('date_from') }}" class="form-control w-auto"><input type="date" name="date_to" value="{{ request('date_to') }}" class="form-control w-auto"><button class="btn btn-primary">Apply</button><a href="{{ route('integrations.index') }}" class="btn btn-outline-secondary">Reset</a></form></div>
        <div class="table-responsive"><table class="table table-hover mb-0"><thead><tr><th>Date</th><th>Provider</th><th>Direction</th><th>Operation</th><th>Status</th><th>Attempts</th><th>External ID</th><th>Error</th><th></th></tr></thead><tbody>
            @forelse($logs as $log)<tr><td>{{ $log->created_at }}</td><td>{{ ucfirst($log->provider) }}</td><td>{{ ucfirst($log->direction) }}</td><td>{{ str($log->operation)->headline() }}</td><td><span class="badge {{ $log->status==='completed'?'bg-soft-success text-success':($log->status==='failed'?'bg-soft-danger text-danger':'bg-soft-warning text-warning') }}">{{ ucfirst($log->status) }}</span></td><td>{{ $log->attempts }}/{{ $log->max_attempts }}</td><td>{{ $log->external_id }}</td><td class="text-danger">{{ $log->error }}</td><td>@if($log->direction==='outbound' && in_array($log->status,['failed','pending']))<form method="POST" action="{{ route('integrations.logs.retry',$log) }}">@csrf<button class="btn btn-sm btn-outline-primary">Retry</button></form>@endif</td></tr>
            @empty
                <tr class="integration-empty-row">
                    <td class="text-center text-muted py-4">No synchronization history.</td>
                    @for($column = 1; $column < 9; $column++)
                        <td aria-hidden="true"></td>
                    @endfor
                </tr>
            @endforelse
        </tbody></table></div>
        @if($logs->hasPages())<div class="card-footer">{{ $logs->links() }}</div>@endif
    </div>
</div>
@endsection
