<?php
// متغيرات: $providers (array keyed by provider), $activeProvider (string)
$providersMeta = [
    'gemini' => [
        'label'       => 'Google Gemini',
        'iconFb'      => 'bi-stars',
        'color'       => 'primary',
        'badge'       => __('ai.free_tier','Free tier available'),
        'badge_color' => 'success',
        'url'         => 'https://aistudio.google.com/app/apikey',
        'urlLabel'    => 'aistudio.google.com',
        'doc_url'     => 'https://ai.google.dev/gemini-api/docs',
        'key_prefix'  => 'AIza...',
        'models_hint' => __('ai.gemini.models_hint','Click "Load Models" to fetch available models'),
        'can_list'    => true,
    ],
    'claude' => [
        'label'       => 'Claude (Anthropic)',
        'iconFb'      => 'bi-robot',
        'color'       => 'warning',
        'badge'       => __('ai.paid_tier','Paid — highly capable'),
        'badge_color' => 'warning',
        'url'         => 'https://console.anthropic.com/settings/keys',
        'urlLabel'    => 'console.anthropic.com',
        'doc_url'     => 'https://docs.anthropic.com',
        'key_prefix'  => 'sk-ant-...',
        'models_hint' => __('ai.claude.models_hint','Select from predefined models below'),
        'can_list'    => false,
        'fixed_models'=> [
            'claude-opus-4-5',
            'claude-sonnet-4-5',
            'claude-haiku-4-5-20251001',
            'claude-3-5-sonnet-20241022',
            'claude-3-5-haiku-20241022',
            'claude-3-opus-20240229',
        ],
    ],
    'openai' => [
        'label'       => 'OpenAI (ChatGPT)',
        'iconFb'      => 'bi-chat-dots',
        'color'       => 'success',
        'badge'       => __('ai.paid_tier_credits','Paid — credits based'),
        'badge_color' => 'secondary',
        'url'         => 'https://platform.openai.com/api-keys',
        'urlLabel'    => 'platform.openai.com',
        'doc_url'     => 'https://platform.openai.com/docs',
        'key_prefix'  => 'sk-...',
        'models_hint' => __('ai.openai.models_hint','Click "Load Models" to fetch GPT models'),
        'can_list'    => true,
    ],
];

$lang          = \Core\System\Language::code();
$activeDialect = '';
foreach ($providers as $p) {
    if (!empty($p['dialect'])) { $activeDialect = $p['dialect']; break; }
}
$activeDialect = $activeDialect ?: 'fusha';
?>

<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-robot me-2 text-primary"></i>
                <?= __('ai.settings.title','AI Settings') ?>
            </h3>
            <p class="text-muted mb-0 small">
                <?= __('ai.settings.subtitle','Configure AI providers for product descriptions and marketing messages') ?>
            </p>
        </div>
    </div>

    <?php if (!empty($_SESSION['flash_success'])): ?>
        <div class="alert alert-success alert-dismissible fade show py-2">
            <i class="bi bi-check-circle me-1"></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/settings/ai/save" id="aiForm">
        <?= \Core\System\Csrf::field() ?>

        <!-- ===== STEP 1: Choose 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">
                    <span class="badge bg-primary rounded-circle me-2" style="width:22px;height:22px;line-height:15px">1</span>
                    <?= __('ai.choose_provider','Choose AI Provider') ?>
                </h6>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <?php foreach ($providersMeta as $key => $meta): ?>
                    <div class="col-md-4">
                        <label class="d-block h-100" style="cursor:pointer">
                            <input type="radio" name="active_provider" value="<?= $key ?>"
                                   class="provider-radio d-none"
                                   <?= $activeProvider === $key ? 'checked' : '' ?>>
                            <div class="provider-card border-2 border rounded-3 p-3 h-100 transition-all
                                        <?= $activeProvider === $key ? 'border-'.$meta['color'].' bg-'.$meta['color'].'-subtle selected' : 'border-light' ?>">
                                <div class="d-flex align-items-center gap-2 mb-2">
                                    <div class="rounded-circle d-flex align-items-center justify-content-center flex-shrink-0"
                                         style="width:36px;height:36px;background:var(--bs-<?= $meta['color'] ?>-bg-subtle,rgba(13,110,253,.1))">
                                        <i class="bi <?= $meta['iconFb'] ?> text-<?= $meta['color'] ?>"></i>
                                    </div>
                                    <div>
                                        <div class="fw-semibold small lh-1"><?= $meta['label'] ?></div>
                                        <span class="badge bg-<?= $meta['badge_color'] ?>-subtle text-<?= $meta['badge_color'] ?> border border-<?= $meta['badge_color'] ?>-subtle"
                                              style="font-size:.65rem"><?= $meta['badge'] ?></span>
                                    </div>
                                    <?php if ($activeProvider === $key): ?>
                                    <i class="bi bi-check-circle-fill text-<?= $meta['color'] ?> ms-auto"></i>
                                    <?php endif; ?>
                                </div>
                                <div class="small text-muted">
                                    <a href="<?= $meta['url'] ?>" target="_blank" rel="noopener"
                                       class="text-decoration-none" onclick="event.stopPropagation()">
                                        <i class="bi bi-key me-1"></i><?= $meta['urlLabel'] ?> ↗
                                    </a>
                                </div>
                            </div>
                        </label>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- ===== STEP 2: Provider Config (dynamic) ===== -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-bottom py-3" id="configCardHeader">
                <h6 class="mb-0 fw-semibold">
                    <span class="badge bg-primary rounded-circle me-2" style="width:22px;height:22px;line-height:15px">2</span>
                    <span id="configTitle"><?= __('ai.configure','Configure Provider') ?></span>
                </h6>
            </div>
            <div class="card-body" id="configBody">
                <?php foreach ($providersMeta as $key => $meta):
                    $cfg = $providers[$key] ?? [];
                ?>
                <div id="panel-<?= $key ?>" class="provider-panel <?= $activeProvider === $key ? '' : 'd-none' ?>">

                    <div class="row g-3 mb-3">
                        <!-- API Key -->
                        <div class="col-12">
                            <label class="form-label fw-semibold small">
                                <i class="bi bi-key me-1"></i>
                                <?= __('ai.api_key','API Key') ?>
                                <a href="<?= $meta['doc_url'] ?>" target="_blank" rel="noopener"
                                   class="text-muted ms-2 small text-decoration-none">
                                    <?= __('ai.docs','Docs') ?> ↗
                                </a>
                            </label>
                            <div class="input-group">
                                <input type="password"
                                       id="key-<?= $key ?>"
                                       name="<?= $key ?>_api_key"
                                       class="form-control"
                                       value="<?= htmlspecialchars($cfg['api_key'] ?? '') ?>"
                                       placeholder="<?= $meta['key_prefix'] ?>"
                                       autocomplete="new-password">
                                <button type="button" class="btn btn-outline-secondary px-3"
                                        onclick="toggleKey('<?= $key ?>')" tabindex="-1">
                                    <i class="bi bi-eye" id="eye-<?= $key ?>"></i>
                                </button>
                            </div>
                        </div>

                        <!-- Model -->
                        <div class="col-12">
                            <label class="form-label fw-semibold small">
                                <i class="bi bi-cpu me-1"></i>
                                <?= __('ai.model','Model') ?>
                            </label>

                            <?php if (!empty($meta['fixed_models'])): ?>
                                <!-- Fixed models (Claude) -->
                                <select name="<?= $key ?>_model" id="model-<?= $key ?>" class="form-select">
                                    <?php foreach ($meta['fixed_models'] as $m): ?>
                                        <option value="<?= $m ?>"
                                            <?= ($cfg['model'] ?? '') === $m ? 'selected' : '' ?>>
                                            <?= $m ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            <?php else: ?>
                                <!-- Dynamic models (Gemini, OpenAI) -->
                                <div class="input-group">
                                    <select name="<?= $key ?>_model" id="model-<?= $key ?>" class="form-select">
                                        <?php if (!empty($cfg['model'])): ?>
                                            <option value="<?= htmlspecialchars($cfg['model']) ?>" selected>
                                                <?= htmlspecialchars($cfg['model']) ?>
                                            </option>
                                        <?php else: ?>
                                            <option value=""><?= __('ai.select_model','Select model...') ?></option>
                                        <?php endif; ?>
                                    </select>
                                    <button type="button"
                                            class="btn btn-outline-secondary"
                                            onclick="loadModels('<?= $key ?>')"
                                            id="load-btn-<?= $key ?>">
                                        <span class="spinner-border spinner-border-sm d-none" id="spin-<?= $key ?>"></span>
                                        <i class="bi bi-arrow-clockwise" id="spin-icon-<?= $key ?>"></i>
                                        <?= __('ai.load_models','Load Models') ?>
                                    </button>
                                </div>
                            <?php endif; ?>
                            <div class="form-text"><?= $meta['models_hint'] ?></div>
                        </div>
                    </div>

                    <?php if ($key === 'gemini'): ?>
                    <div class="border rounded-3 p-3 bg-light-subtle mb-3">
                        <div class="d-flex align-items-start gap-2 mb-3">
                            <i class="bi bi-image text-primary mt-1"></i>
                            <div>
                                <div class="fw-semibold small"><?= __('ai.gemini_image.title', 'Gemini Product Image Generation') ?></div>
                                <div class="text-muted small">
                                    <?= __('ai.gemini_image.help', 'This feature uses Gemini only and continues to work even if the main active AI provider is different.') ?>
                                </div>
                            </div>
                        </div>
                        <div class="form-check form-switch mb-3">
                            <input class="form-check-input" type="checkbox" role="switch"
                                   id="geminiImageGenerationEnabled"
                                   name="gemini_image_generation_enabled"
                                   value="1"
                                   <?= !empty($cfg['image_generation_enabled']) ? 'checked' : '' ?>>
                            <label class="form-check-label fw-semibold" for="geminiImageGenerationEnabled">
                                <?= __('ai.gemini_image.enable', 'Enable AI image generation') ?>
                            </label>
                        </div>
                        <div>
                            <label class="form-label fw-semibold small" for="gemini-image-model">
                                <i class="bi bi-card-image me-1"></i><?= __('ai.gemini_image.model', 'Gemini image model') ?>
                            </label>
                            <input type="text"
                                   class="form-control"
                                   id="gemini-image-model"
                                   name="gemini_image_model"
                                   value="<?= htmlspecialchars($cfg['image_model'] ?? '') ?>"
                                   placeholder="gemini-2.5-flash-image-preview">
                            <div class="form-text"><?= __('ai.gemini_image.model_hint', 'Enter the Gemini model used for image generation, such as an image preview or image generation capable model.') ?></div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Test Connection -->
                    <div class="d-flex align-items-center gap-3 pt-2 border-top">
                        <button type="button"
                                class="btn btn-sm btn-outline-<?= $meta['color'] ?>"
                                onclick="testConnection('<?= $key ?>')">
                            <i class="bi bi-plug me-1"></i>
                            <?= __('ai.test_connection','Test Connection') ?>
                        </button>
                        <span id="test-result-<?= $key ?>" class="small"></span>
                    </div>

                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- ===== STEP 3: Dialect (Arabic only) ===== -->
        <?php if ($lang === 'ar'): ?>
        <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">
                    <span class="badge bg-primary rounded-circle me-2" style="width:22px;height:22px;line-height:15px">3</span>
                    <?= __('ai.default_dialect','Arabic Dialect') ?>
                </h6>
            </div>
            <div class="card-body">
                <div class="d-flex flex-wrap gap-3">
                    <?php foreach ([
                        'fusha'    => __('ai.dialect.fusha',    'Fusha (MSA)'),
                        'algerian' => __('ai.dialect.algerian', 'Algerian'),
                        'moroccan' => __('ai.dialect.moroccan', 'Moroccan'),
                        'egyptian' => __('ai.dialect.egyptian', 'Egyptian'),
                        'saudi'    => __('ai.dialect.saudi',    'Saudi'),
                    ] as $val => $lbl): ?>
                    <div class="form-check">
                        <input class="form-check-input" type="radio"
                               name="dialect" id="d-<?= $val ?>" value="<?= $val ?>"
                               <?= $activeDialect === $val ? 'checked' : '' ?>>
                        <label class="form-check-label" for="d-<?= $val ?>"><?= $lbl ?></label>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>


        <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-magic me-2 text-primary"></i>
                    <?= __('ai.auto_seo.title', 'Automatic SEO') ?>
                </h6>
            </div>
            <div class="card-body">
                <div class="form-check form-switch mb-2">
                    <input class="form-check-input" type="checkbox" role="switch" id="autoSeoEnabled" name="auto_seo_enabled" value="1" <?= !empty($autoSeoEnabled) ? 'checked' : '' ?>>
                    <label class="form-check-label fw-semibold" for="autoSeoEnabled">
                        <?= __('ai.auto_seo.enable', 'Generate missing SEO fields automatically when saving a product') ?>
                    </label>
                </div>
                <div class="small text-muted">
                    <?= __('ai.auto_seo.help', 'Only empty SEO text fields are filled. Manual values stay untouched, and no share image is generated by AI.') ?>
                </div>
            </div>
        </div>

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

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

<script>
const providerLabels = {
    gemini: 'Google Gemini',
    claude: 'Claude (Anthropic)',
    openai: 'OpenAI (ChatGPT)',
};

// Init — show active panel
document.querySelectorAll('.provider-radio').forEach(radio => {
    radio.addEventListener('change', function() {
        switchProvider(this.value);
    });
});

// Click on card
document.querySelectorAll('.provider-card').forEach(card => {
    card.addEventListener('click', function() {
        const radio = this.closest('label').querySelector('.provider-radio');
        if (radio) { radio.checked = true; radio.dispatchEvent(new Event('change')); }
    });
});

function switchProvider(key) {
    // update cards
    document.querySelectorAll('.provider-card').forEach(c => {
        const r = c.closest('label').querySelector('.provider-radio');
        const isSelected = r && r.value === key;
        c.classList.toggle('selected', isSelected);
        // reset border colors
        ['primary','warning','success','info','secondary'].forEach(color => {
            c.classList.remove('border-' + color, 'bg-' + color + '-subtle');
        });
        c.classList.add(isSelected ? 'border-' + getColor(key) : 'border-light');
        if (isSelected) c.classList.add('bg-' + getColor(key) + '-subtle');
    });

    // show/hide panels
    document.querySelectorAll('.provider-panel').forEach(p => p.classList.add('d-none'));
    const panel = document.getElementById('panel-' + key);
    if (panel) panel.classList.remove('d-none');

    // update header
    document.getElementById('configTitle').textContent =
        '<?= __('ai.configure','Configure') ?> ' + (providerLabels[key] || key);
}

function getColor(key) {
    return { gemini: 'primary', claude: 'warning', openai: 'success' }[key] || 'primary';
}

// Toggle key visibility
function toggleKey(provider) {
    const input = document.getElementById('key-' + provider);
    const icon  = document.getElementById('eye-' + provider);
    input.type  = input.type === 'password' ? 'text' : 'password';
    icon.className = input.type === 'password' ? 'bi bi-eye' : 'bi bi-eye-slash';
}

// Load models dynamically
function loadModels(provider) {
    const apiKey  = document.getElementById('key-' + provider).value.trim();
    const spin    = document.getElementById('spin-' + provider);
    const spinIcon= document.getElementById('spin-icon-' + provider);
    const sel     = document.getElementById('model-' + provider);

    if (!apiKey) {
        alert('<?= __('ai.enter_api_key_first','Please enter the API key first') ?>');
        return;
    }

    spin.classList.remove('d-none');
    spinIcon.classList.add('d-none');

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

    fetch('/admin/ai/list-models', {
        method: 'POST',
        body: form,
        credentials: 'same-origin'
    })
    .then(r => {
        if (!r.ok) throw new Error('HTTP ' + r.status);
        return r.json();
    })
    .then(res => {
        spin.classList.add('d-none');
        spinIcon.classList.remove('d-none');
        if (res.success && res.models && res.models.length > 0) {
            const current = sel.value;
            sel.innerHTML = '';
            res.models.forEach(m => {
                const opt = document.createElement('option');
                opt.value = m; opt.textContent = m;
                if (m === current) opt.selected = true;
                sel.appendChild(opt);
            });
        } else {
            alert(res.error || '<?= __('ai.no_models_found','No models found') ?>');
        }
    })
    .catch(err => {
        spin.classList.add('d-none');
        spinIcon.classList.remove('d-none');
        alert('Error: ' + err.message);
    });
}

// Test connection
function testConnection(provider) {
    const apiKey = document.getElementById('key-' + provider).value.trim();
    const model  = document.getElementById('model-' + provider)?.value || '';
    const result = document.getElementById('test-result-' + provider);

    if (!apiKey) {
        result.innerHTML = '<span class="text-danger"><?= __('ai.enter_api_key_first','Enter API key first') ?></span>';
        return;
    }

    result.innerHTML = '<span class="spinner-border spinner-border-sm me-1 text-muted"></span><?= __('ai.testing','Testing...') ?>';

    const form = new FormData();
    form.append('provider', provider);
    form.append('api_key',  apiKey);
    form.append('model',    model);
    form.append('_csrf', document.querySelector('input[name=_csrf]')?.value || '');

    fetch('/admin/ai/test', {
        method: 'POST',
        body: form,
        credentials: 'same-origin'
    })
    .then(r => {
        if (!r.ok) throw new Error('HTTP ' + r.status + ' — <?= __('ai.check_login','check that you are logged in') ?>');
        return r.json();
    })
    .then(res => {
        if (res.success) {
            result.innerHTML = '<span class="text-success"><i class="bi bi-check-circle-fill me-1"></i><?= __('ai.connected','Connected successfully!') ?></span>';
        } else {
            result.innerHTML = '<span class="text-danger"><i class="bi bi-x-circle me-1"></i>' + (res.error || '<?= __('ai.failed','Failed') ?>') + '</span>';
        }
    })
    .catch(err => {
        result.innerHTML = '<span class="text-danger"><i class="bi bi-x-circle me-1"></i>' + err.message + '</span>';
    });
}
</script>

<style>
.provider-card { cursor:pointer; transition: all .18s ease; }
.provider-card:hover { border-color: #6c757d !important; box-shadow: 0 2px 8px rgba(0,0,0,.08); }
.provider-card.selected { box-shadow: 0 0 0 2px rgba(13,110,253,.2); }
</style>
