<?php
// متغيرات: $whatsapp (config array)
$provider  = $whatsapp['provider']  ?? 'callmebot';
$events    = $whatsapp['events']    ?? [];
$templates = $whatsapp['templates'] ?? [];
?>

<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid pb-5">

    <!-- Header -->
    <div class="d-flex justify-content-between align-items-start mb-4">
        <div>
            <h3 class="mb-1 fw-bold">
                <i class="bi bi-whatsapp me-2 text-success"></i>
                <?= __('whatsapp.title', 'WhatsApp Notifications') ?>
            </h3>
            <p class="text-muted mb-0 small">
                <?= __('whatsapp.subtitle', 'Send automatic WhatsApp messages to customers') ?>
            </p>
        </div>
        <div class="d-flex gap-2 align-items-center">
            <a href="/admin/settings/whatsapp/logs" class="btn btn-outline-success btn-sm">
                <i class="bi bi-clock-history me-1"></i>
                <?= __('whatsapp.view_logs', 'Messages Log') ?>
            </a>
            <span class="badge <?= !empty($whatsapp['is_active']) ? 'bg-success' : 'bg-secondary' ?> px-3 py-2 fs-6">
                <i class="bi <?= !empty($whatsapp['is_active']) ? 'bi-check-circle' : 'bi-x-circle' ?> me-1"></i>
                <?= !empty($whatsapp['is_active']) ? __('whatsapp.status_active','Active') : __('whatsapp.status_inactive','Inactive') ?>
            </span>
        </div>
    </div>

    <?php if (!empty($_SESSION['flash_success'])): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="bi bi-check-circle me-2"></i><?= htmlspecialchars($_SESSION['flash_success']) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION['flash_success']); ?>
    <?php endif; ?>

    <form method="POST" action="/admin/whatsapp/save" id="whatsappForm">
        <?= \Core\System\Csrf::field() ?>

        <div class="row g-4">

            <!-- LEFT COL -->
            <div class="col-lg-7">

                <!-- Enable / Provider -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white border-bottom py-3">
                        <h6 class="mb-0 fw-semibold">
                            <i class="bi bi-gear me-2 text-muted"></i>
                            <?= __('whatsapp.provider_settings', 'Provider Settings') ?>
                        </h6>
                    </div>
                    <div class="card-body">

                        <!-- Enable toggle -->
                        <div class="form-check form-switch mb-4">
                            <input class="form-check-input" type="checkbox"
                                   id="is_active" name="is_active" value="1"
                                   <?= !empty($whatsapp['is_active']) ? 'checked' : '' ?>>
                            <label class="form-check-label fw-semibold" for="is_active">
                                <?= __('whatsapp.enable', 'Enable WhatsApp Notifications') ?>
                            </label>
                        </div>

                        <!-- Provider selector -->
                        <label class="form-label fw-semibold">
                            <?= __('whatsapp.provider', 'WhatsApp Provider') ?>
                        </label>
                        <div class="row g-3 mb-4" id="providerCards">
                            <?php
                            $providers = [
                                'callmebot' => ['icon'=>'bi-robot',     'label'=>'CallMeBot',          'badge'=>__('whatsapp.free','Free'),      'color'=>'success', 'url'=>'https://www.callmebot.com/blog/free-api-whatsapp-messages/'],
                                'ultramsg'  => ['icon'=>'bi-lightning', 'label'=>'UltraMsg',            'badge'=>__('whatsapp.easy','Easy'),      'color'=>'info',    'url'=>'https://ultramsg.com/'],
                                'twilio'    => ['icon'=>'bi-telephone', 'label'=>'Twilio',              'badge'=>__('whatsapp.reliable','Reliable'),'color'=>'primary', 'url'=>'https://www.twilio.com/en-us/whatsapp'],
                                'meta'      => ['icon'=>'bi-meta',      'label'=>'Meta (Official)',     'badge'=>__('whatsapp.official','Official'),'color'=>'primary', 'url'=>'https://developers.facebook.com/docs/whatsapp/cloud-api/get-started'],
                            ];
                            foreach ($providers as $key => $p):
                            ?>
                            <div class="col-6">
                                <div class="provider-card border rounded-3 p-3 cursor-pointer <?= $provider === $key ? 'border-primary bg-primary bg-opacity-10' : '' ?>"
                                     data-provider="<?= $key ?>"
                                     onclick="selectProvider('<?= $key ?>')">
                                    <div class="d-flex align-items-center gap-2 mb-1">
                                        <i class="bi <?= $p['icon'] ?> fs-5 text-<?= $p['color'] ?>"></i>
                                        <span class="fw-semibold small"><?= $p['label'] ?></span>
                                        <span class="badge bg-<?= $p['color'] ?>-subtle text-<?= $p['color'] ?> border border-<?= $p['color'] ?>-subtle ms-auto"><?= $p['badge'] ?></span>
                                    </div>
                                    <a href="<?= $p['url'] ?>" target="_blank" rel="noopener"
                                       class="text-muted d-block mt-1" style="font-size:.72rem"
                                       onclick="event.stopPropagation()">
                                        <i class="bi bi-box-arrow-up-right me-1"></i><?= __('whatsapp.visit_provider','Visit website') ?>
                                    </a>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <input type="hidden" name="provider" id="providerInput" value="<?= htmlspecialchars($provider) ?>">

                        <!-- Provider credentials -->
                        <div id="creds-callmebot" class="provider-creds <?= $provider === 'callmebot' ? '' : 'd-none' ?>">
                            <div class="alert alert-info small py-2">
                                <i class="bi bi-info-circle me-1"></i>
                                <?= __('whatsapp.callmebot_help', 'Register your number on callmebot.com to get an API key. Send "I allow callmebot to send me messages" to +34 644 14 68 47 on WhatsApp.') ?>
                            </div>
                            <label class="form-label"><?= __('whatsapp.callmebot_apikey', 'CallMeBot API Key') ?></label>
                            <input type="text" name="callmebot_apikey" class="form-control"
                                   value="<?= htmlspecialchars($whatsapp['callmebot_apikey'] ?? '') ?>"
                                   placeholder="123456">
                        </div>

                        <div id="creds-ultramsg" class="provider-creds <?= $provider === 'ultramsg' ? '' : 'd-none' ?>">
                            <div class="row g-3">
                                <div class="col-6">
                                    <label class="form-label"><?= __('whatsapp.ultramsg_instance', 'Instance ID') ?></label>
                                    <input type="text" name="ultramsg_instance" class="form-control"
                                           value="<?= htmlspecialchars($whatsapp['ultramsg_instance'] ?? '') ?>"
                                           placeholder="instance12345">
                                </div>
                                <div class="col-6">
                                    <label class="form-label"><?= __('whatsapp.ultramsg_token', 'Token') ?></label>
                                    <input type="text" name="ultramsg_token" class="form-control"
                                           value="<?= htmlspecialchars($whatsapp['ultramsg_token'] ?? '') ?>"
                                           placeholder="your_token">
                                </div>
                            </div>
                        </div>

                        <div id="creds-twilio" class="provider-creds <?= $provider === 'twilio' ? '' : 'd-none' ?>">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label"><?= __('whatsapp.twilio_sid', 'Account SID') ?></label>
                                    <input type="text" name="twilio_sid" class="form-control"
                                           value="<?= htmlspecialchars($whatsapp['twilio_sid'] ?? '') ?>"
                                           placeholder="ACxxxxxxxxxxxxxxxx">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label"><?= __('whatsapp.twilio_token', 'Auth Token') ?></label>
                                    <input type="password" name="twilio_token" class="form-control"
                                           value="<?= htmlspecialchars($whatsapp['twilio_token'] ?? '') ?>">
                                </div>
                                <div class="col-12">
                                    <label class="form-label"><?= __('whatsapp.twilio_from', 'Twilio WhatsApp Number') ?></label>
                                    <input type="text" name="twilio_from" class="form-control"
                                           value="<?= htmlspecialchars($whatsapp['twilio_from'] ?? '') ?>"
                                           placeholder="+14155238886">
                                </div>
                            </div>
                        </div>

                        <div id="creds-meta" class="provider-creds <?= $provider === 'meta' ? '' : 'd-none' ?>">
                            <div class="row g-3">
                                <div class="col-12">
                                    <label class="form-label"><?= __('whatsapp.meta_token', 'Access Token') ?></label>
                                    <input type="password" name="meta_token" class="form-control"
                                           value="<?= htmlspecialchars($whatsapp['meta_token'] ?? '') ?>">
                                </div>
                                <div class="col-12">
                                    <label class="form-label"><?= __('whatsapp.meta_phone_id', 'Phone Number ID') ?></label>
                                    <input type="text" name="meta_phone_id" class="form-control"
                                           value="<?= htmlspecialchars($whatsapp['meta_phone_id'] ?? '') ?>"
                                           placeholder="123456789012345">
                                </div>
                            </div>
                        </div>

                    </div>
                </div>

                <!-- Message Templates -->
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white border-bottom py-3">
                        <h6 class="mb-0 fw-semibold">
                            <i class="bi bi-chat-text me-2 text-muted"></i>
                            <?= __('whatsapp.templates', 'Message Templates') ?>
                        </h6>
                    </div>
                    <div class="card-body">

                        <!-- Variables reference -->
                        <div class="alert alert-light border small mb-4">
                            <div class="fw-semibold mb-2"><?= __('whatsapp.variables', 'Available Variables') ?>:</div>
                            <div class="d-flex flex-wrap gap-1">
                                <?php foreach (['{name}','{order_id}','{total}','{product}','{tracking}','{provider}','{status}','{city}','{date}','{store_name}','{attendee_name}','{meeting_title}','{meeting_time}','{minutes_left}'] as $v): ?>
                                    <code class="bg-white border rounded px-2 py-0 small"><?= $v ?></code>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <?php
                        $tplConfig = [
                            'order_confirmed' => [
                                'event_key'  => 'event_confirmed',
                                'event_name' => __('whatsapp.event.confirmed', 'Order Confirmed'),
                                'icon'       => 'bi-check-circle text-success',
                                'tpl_key'    => 'tpl_confirmed',
                            ],
                            'order_shipped' => [
                                'event_key'  => 'event_shipped',
                                'event_name' => __('whatsapp.event.shipped', 'Order Shipped'),
                                'icon'       => 'bi-truck text-primary',
                                'tpl_key'    => 'tpl_shipped',
                            ],
                            'status_updated' => [
                                'event_key'  => 'event_status',
                                'event_name' => __('whatsapp.event.status', 'Shipping Status Updated'),
                                'icon'       => 'bi-arrow-clockwise text-info',
                                'tpl_key'    => 'tpl_status',
                            ],
                            'meeting_reminder' => [
                                'event_key'  => 'event_meeting',
                                'event_name' => __('whatsapp.event.meeting_reminder', 'Meeting Reminder'),
                                'icon'       => 'bi-calendar-event-fill text-warning',
                                'tpl_key'    => 'tpl_meeting',
                                'vars_extra' => ['{attendee_name}', '{meeting_title}', '{meeting_time}', '{minutes_left}'],
                            ],
                        ];
                        foreach ($tplConfig as $eventId => $tpl):
                            $isEnabled = !empty($events[$eventId]);
                        ?>
                        <div class="border rounded-3 p-3 mb-3 <?= $isEnabled ? '' : 'opacity-75' ?>">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <div class="d-flex align-items-center gap-2">
                                    <i class="bi <?= $tpl['icon'] ?> fs-5"></i>
                                    <span class="fw-semibold small"><?= $tpl['event_name'] ?></span>
                                </div>
                                <div class="form-check form-switch mb-0">
                                    <input class="form-check-input" type="checkbox"
                                           name="<?= $tpl['event_key'] ?>" value="1"
                                           <?= $isEnabled ? 'checked' : '' ?>
                                           onchange="this.closest('.border').classList.toggle('opacity-75', !this.checked)">
                                </div>
                            </div>
                            <textarea name="<?= $tpl['tpl_key'] ?>" class="form-control form-control-sm font-monospace"
                                      rows="4" dir="auto"><?= htmlspecialchars($templates[$eventId] ?? '') ?></textarea>
                        </div>
                        <?php endforeach; ?>

                    </div>
                </div>

            </div>

            <!-- RIGHT COL -->
            <div class="col-lg-5">

                <!-- Test Send -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white border-bottom py-3">
                        <h6 class="mb-0 fw-semibold">
                            <i class="bi bi-send me-2 text-muted"></i>
                            <?= __('whatsapp.test', 'Test Message') ?>
                        </h6>
                    </div>
                    <div class="card-body">
                        <p class="text-muted small mb-3">
                            <?= __('whatsapp.test_desc', 'Send a test message to verify your configuration before going live.') ?>
                        </p>
                        <label class="form-label"><?= __('whatsapp.test_phone', 'Phone Number') ?></label>
                        <div class="input-group mb-3">
                            <span class="input-group-text"><i class="bi bi-phone"></i></span>
                            <input type="text" id="testPhone" class="form-control"
                                   placeholder="+213xxxxxxxxx">
                        </div>
                        <label class="form-label"><?= __('whatsapp.test_message', 'Message') ?></label>
                        <textarea id="testMessage" class="form-control mb-3" rows="3">Test message from {store_name} 👋</textarea>
                        <button type="button" class="btn btn-outline-success w-100" onclick="sendTest()">
                            <i class="bi bi-whatsapp me-2"></i>
                            <?= __('whatsapp.send_test', 'Send Test') ?>
                        </button>
                        <div id="testResult" class="mt-3 d-none"></div>
                    </div>
                </div>

                <!-- How it works -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white border-bottom py-3">
                        <h6 class="mb-0 fw-semibold">
                            <i class="bi bi-info-circle me-2 text-muted"></i>
                            <?= __('whatsapp.how_it_works', 'How It Works') ?>
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="d-flex gap-3 mb-3">
                            <div class="rounded-circle bg-success bg-opacity-10 d-flex align-items-center justify-content-center flex-shrink-0"
                                 style="width:36px;height:36px">
                                <span class="fw-bold text-success small">1</span>
                            </div>
                            <div>
                                <div class="fw-semibold small"><?= __('whatsapp.step1_title', 'Choose a Provider') ?></div>
                                <div class="text-muted smaller"><?= __('whatsapp.step1_desc', 'Select and configure your preferred WhatsApp API provider.') ?></div>
                            </div>
                        </div>
                        <div class="d-flex gap-3 mb-3">
                            <div class="rounded-circle bg-primary bg-opacity-10 d-flex align-items-center justify-content-center flex-shrink-0"
                                 style="width:36px;height:36px">
                                <span class="fw-bold text-primary small">2</span>
                            </div>
                            <div>
                                <div class="fw-semibold small"><?= __('whatsapp.step2_title', 'Customize Messages') ?></div>
                                <div class="text-muted smaller"><?= __('whatsapp.step2_desc', 'Write your message templates using the available variables.') ?></div>
                            </div>
                        </div>
                        <div class="d-flex gap-3">
                            <div class="rounded-circle bg-info bg-opacity-10 d-flex align-items-center justify-content-center flex-shrink-0"
                                 style="width:36px;height:36px">
                                <span class="fw-bold text-info small">3</span>
                            </div>
                            <div>
                                <div class="fw-semibold small"><?= __('whatsapp.step3_title', 'Activate & Test') ?></div>
                                <div class="text-muted smaller"><?= __('whatsapp.step3_desc', 'Enable the service and send a test message to confirm everything works.') ?></div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Save button -->
                <button type="submit" class="btn btn-primary w-100 py-3">
                    <i class="bi bi-save me-2"></i>
                    <?= __('actions.save', 'Save Settings') ?>
                </button>

            </div>
        </div>
    </form>

</div>
</section>
</div>

<script>
function selectProvider(key) {
    document.querySelectorAll('.provider-card').forEach(c => {
        c.classList.toggle('border-primary', c.dataset.provider === key);
        c.classList.toggle('bg-primary',     c.dataset.provider === key);
        c.classList.toggle('bg-opacity-10',  c.dataset.provider === key);
    });
    document.querySelectorAll('.provider-creds').forEach(d => d.classList.add('d-none'));
    const el = document.getElementById('creds-' + key);
    if (el) el.classList.remove('d-none');
    document.getElementById('providerInput').value = key;
}

function sendTest() {
    const phone   = document.getElementById('testPhone').value.trim();
    const message = document.getElementById('testMessage').value.trim();
    const result  = document.getElementById('testResult');

    if (!phone) {
        result.className = 'mt-3 alert alert-warning';
        result.textContent = '<?= __('whatsapp.test_phone_required', 'Please enter a phone number') ?>';
        return;
    }

    result.className = 'mt-3 alert alert-info';
    result.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span><?= __('whatsapp.sending', 'Sending...') ?>';
    result.classList.remove('d-none');

    const form = new FormData();
    form.append('phone',   phone);
    form.append('message', message);
    form.append('_csrf',  document.querySelector('input[name=_csrf]')?.value || '');

    fetch('/admin/whatsapp/test', { method: 'POST', body: form })
        .then(r => r.json())
        .then(res => {
            if (res.success) {
                result.className = 'mt-3 alert alert-success';
                result.innerHTML = '<i class="bi bi-check-circle me-2"></i><?= __('whatsapp.test_success', 'Message sent successfully!') ?>';
            } else {
                result.className = 'mt-3 alert alert-danger';
                result.innerHTML = '<i class="bi bi-x-circle me-2"></i>' + (res.error || '<?= __('whatsapp.test_failed', 'Failed to send') ?>');
            }
        })
        .catch(() => {
            result.className = 'mt-3 alert alert-danger';
            result.textContent = '<?= __('errors.network', 'Network error') ?>';
        });
}
</script>

<style>
.provider-card { cursor: pointer; transition: all .2s; }
.provider-card:hover { border-color: #0d6efd !important; }
.smaller { font-size: .75rem; }
</style>