<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/layout.php';
require_once dirname(__DIR__, 2) . '/api/lib/ai_provider.php';

platform_require_login();
$pdo = platform_pdo();

$msg = '';
$err = '';
$testResult = null;
$editRow = null;

if (!platform_table_exists($pdo, 'platform_ai_providers')) {
    http_response_code(500);
    admin_header('مركز مزودي الذكاء الاصطناعي');
    echo '<div class="card"><strong>جدول مزودي AI غير موجود.</strong><p>لم يتم إنشاء جداول تلقائيًا. راجع قاعدة البيانات وتأكد من تطبيق Migration الدفعة السابعة.</p></div>';
    admin_footer();
    exit;
}

function ai_admin_with_active_lock(PDO $pdo, callable $callback): mixed
{
    $lockStatement = $pdo->query("SELECT GET_LOCK('etharbooking_platform_ai_active_provider', 10)");
    if ((int) $lockStatement->fetchColumn() !== 1) {
        throw new RuntimeException('تعذر الحصول على قفل تحديث المزود النشط. أعد المحاولة.');
    }

    try {
        return $callback();
    } finally {
        $pdo->query("SELECT RELEASE_LOCK('etharbooking_platform_ai_active_provider')");
    }
}

function ai_admin_activate(PDO $pdo, int $providerId): void
{
    ai_admin_with_active_lock($pdo, static function () use ($pdo, $providerId): void {
        $pdo->beginTransaction();
        try {
            $check = $pdo->prepare('SELECT id, api_key_ciphertext FROM platform_ai_providers WHERE id = ? LIMIT 1 FOR UPDATE');
            $check->execute([$providerId]);
            $provider = $check->fetch(PDO::FETCH_ASSOC);
            if (!$provider) {
                throw new RuntimeException('المزود المطلوب غير موجود.');
            }
            // Refuse activation when the current server secret cannot decrypt the saved key.
            eth_ai_key((string) $provider['api_key_ciphertext']);

            $pdo->exec('UPDATE platform_ai_providers SET is_active = 0');
            $activate = $pdo->prepare('UPDATE platform_ai_providers SET is_active = 1 WHERE id = ?');
            $activate->execute([$providerId]);
            $pdo->commit();
        } catch (Throwable $exception) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            throw $exception;
        }
    });
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!platform_verify_csrf((string) ($_POST['csrf'] ?? ''))) {
        $err = 'انتهت صلاحية نموذج الحماية. أعد تحميل الصفحة وحاول مجددًا.';
    } else {
        $action = (string) ($_POST['action'] ?? 'save');
        try {
            if ($action === 'test') {
                $providerId = filter_var($_POST['provider_id'] ?? null, FILTER_VALIDATE_INT);
                if (!$providerId || $providerId < 1) {
                    throw new RuntimeException('معرّف المزود غير صحيح.');
                }
                $testResult = eth_ai_test_provider($pdo, (int) $providerId);
                if (!empty($testResult['success'])) {
                    $msg = $testResult['message'];
                } else {
                    $err = $testResult['message'];
                }
            } elseif ($action === 'activate') {
                eth_ai_encryption_secret();
                $providerId = filter_var($_POST['provider_id'] ?? null, FILTER_VALIDATE_INT);
                if (!$providerId || $providerId < 1) {
                    throw new RuntimeException('معرّف المزود غير صحيح.');
                }
                ai_admin_activate($pdo, (int) $providerId);
                $msg = 'تم تفعيل المزود المحدد وإيقاف بقية المزودين.';
            } elseif ($action === 'disable') {
                $providerId = filter_var($_POST['provider_id'] ?? null, FILTER_VALIDATE_INT);
                if (!$providerId || $providerId < 1) {
                    throw new RuntimeException('معرّف المزود غير صحيح.');
                }
                ai_admin_with_active_lock($pdo, static function () use ($pdo, $providerId): void {
                    $statement = $pdo->prepare('UPDATE platform_ai_providers SET is_active = 0 WHERE id = ?');
                    $statement->execute([(int) $providerId]);
                });
                $msg = 'تم تعطيل المزود.';
            } elseif ($action === 'save') {
                eth_ai_encryption_secret();
                $id = filter_var($_POST['id'] ?? '0', FILTER_VALIDATE_INT);
                $id = ($id && $id > 0) ? (int) $id : 0;
                $providerCode = strtolower(trim((string) ($_POST['provider_code'] ?? '')));
                $displayName = trim((string) ($_POST['display_name'] ?? ''));
                $modelCode = trim((string) ($_POST['model_code'] ?? ''));
                $apiKey = trim((string) ($_POST['api_key'] ?? ''));
                $baseUrl = trim((string) ($_POST['base_url'] ?? ''));
                $priority = filter_var($_POST['priority'] ?? '100', FILTER_VALIDATE_INT);
                $makeActive = isset($_POST['is_active']) && (string) $_POST['is_active'] === '1';

                if ($displayName === '' || strlen($displayName) > 100) {
                    throw new RuntimeException('اسم المزود مطلوب وبحد أقصى 100 حرف.');
                }
                eth_ai_validate_provider($providerCode, $modelCode, $baseUrl);
                if ($priority === false || $priority < 0 || $priority > 100000) {
                    throw new RuntimeException('قيمة الأولوية غير صحيحة.');
                }

                $existing = null;
                if ($id > 0) {
                    $find = $pdo->prepare('SELECT id, api_key_ciphertext FROM platform_ai_providers WHERE id = ? LIMIT 1');
                    $find->execute([$id]);
                    $existing = $find->fetch(PDO::FETCH_ASSOC) ?: null;
                    if (!$existing) {
                        throw new RuntimeException('المزود المراد تعديله غير موجود.');
                    }
                }

                if ($apiKey === '' && $existing === null) {
                    throw new RuntimeException('مفتاح API مطلوب عند إضافة مزود جديد.');
                }

                $cipherText = $apiKey !== ''
                    ? eth_ai_encrypt_key($apiKey)
                    : (string) $existing['api_key_ciphertext'];
                if ($makeActive) {
                    // If the key was retained, ensure it is decryptable before activating.
                    eth_ai_key($cipherText);
                }

                $saveOperation = static function () use ($pdo, $id, $providerCode, $displayName, $modelCode, $baseUrl, $cipherText, $priority, $makeActive): void {
                    $pdo->beginTransaction();
                    try {
                        if ($makeActive) {
                            $pdo->exec('UPDATE platform_ai_providers SET is_active = 0');
                        }

                        if ($id > 0) {
                            $statement = $pdo->prepare(
                                'UPDATE platform_ai_providers
                                 SET provider_code = ?, display_name = ?, model_code = ?, base_url = ?,
                                     api_key_ciphertext = ?, priority = ?, is_active = ?
                                 WHERE id = ?'
                            );
                            $statement->execute([
                                $providerCode,
                                $displayName,
                                $modelCode,
                                $providerCode === 'compatible' ? $baseUrl : null,
                                $cipherText,
                                $priority,
                                $makeActive ? 1 : 0,
                                $id,
                            ]);
                        } else {
                            $statement = $pdo->prepare(
                                'INSERT INTO platform_ai_providers
                                 (provider_code, display_name, model_code, base_url, api_key_ciphertext, is_active, priority)
                                 VALUES (?, ?, ?, ?, ?, ?, ?)'
                            );
                            $statement->execute([
                                $providerCode,
                                $displayName,
                                $modelCode,
                                $providerCode === 'compatible' ? $baseUrl : null,
                                $cipherText,
                                $makeActive ? 1 : 0,
                                $priority,
                            ]);
                        }
                        $pdo->commit();
                    } catch (Throwable $exception) {
                        if ($pdo->inTransaction()) {
                            $pdo->rollBack();
                        }
                        throw $exception;
                    }
                };

                if ($makeActive) {
                    ai_admin_with_active_lock($pdo, $saveOperation);
                } else {
                    $saveOperation();
                }
                $msg = $id > 0 ? 'تم تحديث إعدادات المزود. لم يتم عرض مفتاح API.' : 'تمت إضافة المزود. لم يتم عرض مفتاح API.';
            } else {
                throw new RuntimeException('العملية المطلوبة غير معروفة.');
            }
        } catch (Throwable $exception) {
            error_log('[ETHAR_PLATFORM_AI_ADMIN] ' . get_class($exception) . ': ' . $exception->getMessage());
            $err = $exception->getMessage();
        }
    }
}

if (isset($_GET['edit'])) {
    $editId = filter_var($_GET['edit'], FILTER_VALIDATE_INT);
    if ($editId && $editId > 0) {
        $statement = $pdo->prepare('SELECT id, provider_code, display_name, model_code, base_url, priority, is_active FROM platform_ai_providers WHERE id = ? LIMIT 1');
        $statement->execute([(int) $editId]);
        $editRow = $statement->fetch(PDO::FETCH_ASSOC) ?: null;
    }
}

$rows = $pdo->query(
    'SELECT id, provider_code, display_name, model_code, base_url, is_active, priority, updated_at
     FROM platform_ai_providers ORDER BY priority ASC, id DESC'
)->fetchAll(PDO::FETCH_ASSOC);
$hasActiveProvider = false;
foreach ($rows as $row) {
    if ((int) $row['is_active'] === 1) {
        $hasActiveProvider = true;
        break;
    }
}
$encryptionReady = true;
try {
    eth_ai_encryption_secret();
} catch (Throwable) {
    $encryptionReady = false;
}

admin_header('مركز مزودي الذكاء الاصطناعي');
?>
<div style="max-width:1200px;margin:0 auto;display:grid;gap:18px">
    <section class="hero">
        <div>
            <h2 style="margin:0 0 6px">مركز مزودي الذكاء الاصطناعي</h2>
            <div class="muted">إدارة مركزية لمزود المساعد الإداري دون كشف مفاتيح API بعد حفظها.</div>
        </div>
        <span class="badge <?= $encryptionReady ? 'green' : 'orange' ?>">
            <?= $encryptionReady ? 'التشفير جاهز' : 'مفتاح التشفير غير مضبوط' ?>
        </span>
    </section>

    <?php if ($msg !== ''): ?><div class="flash" role="status"><?= h($msg) ?><?= isset($testResult['http_code']) && $testResult['http_code'] ? ' — HTTP ' . (int) $testResult['http_code'] : '' ?></div><?php endif; ?>
    <?php if ($err !== ''): ?><div class="flash" role="alert" style="background:#fee2e2;color:#991b1b"><?= h($err) ?><?= isset($testResult['http_code']) && $testResult['http_code'] ? ' — HTTP ' . (int) $testResult['http_code'] : '' ?></div><?php endif; ?>

    <?php if (!$encryptionReady): ?>
        <div class="card" style="border-color:#f59e0b;background:#fffbeb">
            <strong>لم يتم ضبط مفتاح التشفير على الخادم.</strong>
            <p style="margin-bottom:0">اضبط متغير البيئة <code>ETHAR_AI_ENCRYPTION_SECRET</code> في إعداد Apache أو PHP-FPM خارج مجلد الموقع، بطول عشوائي لا يقل عن 32 بايت. لا تضعه في قاعدة البيانات أو ملفات المشروع أو <code>.htaccess</code>.</p>
        </div>
    <?php endif; ?>

    <section class="card">
        <div class="section-title"><?= $editRow ? 'تعديل مزود مسجل' : 'إضافة مزود جديد' ?></div>
        <form method="post" class="form" autocomplete="off">
            <input type="hidden" name="csrf" value="<?= h(platform_csrf()) ?>">
            <input type="hidden" name="action" value="save">
            <input type="hidden" name="id" value="<?= (int) ($editRow['id'] ?? 0) ?>">

            <div class="two">
                <div class="field">
                    <label for="provider_code">المزود</label>
                    <select id="provider_code" name="provider_code" required>
                        <?php
                        $providerOptions = [
                            'gemini' => 'Google Gemini',
                            'openai' => 'OpenAI',
                            'deepseek' => 'DeepSeek',
                            'openrouter' => 'OpenRouter',
                            'compatible' => 'OpenAI-compatible API',
                        ];
                        $selectedProvider = (string) ($editRow['provider_code'] ?? 'gemini');
                        foreach ($providerOptions as $value => $label):
                        ?>
                            <option value="<?= h($value) ?>" <?= $selectedProvider === $value ? 'selected' : '' ?>><?= h($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="field">
                    <label for="display_name">الاسم الظاهر</label>
                    <input id="display_name" name="display_name" required maxlength="100" value="<?= h((string) ($editRow['display_name'] ?? '')) ?>">
                </div>
            </div>

            <div class="two">
                <div class="field">
                    <label for="model_code">معرّف النموذج Model ID</label>
                    <input id="model_code" name="model_code" required maxlength="150" value="<?= h((string) ($editRow['model_code'] ?? '')) ?>" placeholder="مثال: gemini-2.5-flash">
                </div>
                <div class="field">
                    <label for="priority">الأولوية</label>
                    <input id="priority" name="priority" type="number" min="0" max="100000" value="<?= (int) ($editRow['priority'] ?? 100) ?>">
                </div>
            </div>

            <div class="field" id="base-url-field">
                <label for="base_url">Base URL — مطلوب فقط للمزود المتوافق</label>
                <input id="base_url" name="base_url" type="url" value="<?= h((string) ($editRow['base_url'] ?? '')) ?>" placeholder="https://api.example.com/v1">
                <small class="muted">يُقبل HTTPS على المنفذ 443 فقط، ويُرفض الاتصال بعناوين الشبكات الداخلية.</small>
            </div>

            <div class="field">
                <label for="api_key">مفتاح API <?= $editRow ? '(اتركه فارغًا للاحتفاظ بالمفتاح الحالي)' : '' ?></label>
                <input id="api_key" name="api_key" type="password" autocomplete="new-password" <?= $editRow ? '' : 'required' ?> placeholder="<?= $editRow ? 'أدخل مفتاحًا جديدًا فقط عند الرغبة في تغييره' : 'أدخل مفتاح المزود' ?>">
                <small class="muted">يُشفّر المفتاح باستخدام AES-256-GCM. لا يُعرض المفتاح الحالي في الصفحة أو في الجدول.</small>
            </div>

            <label style="display:flex;gap:8px;align-items:center;font-size:13px">
                <input type="checkbox" name="is_active" value="1" <?= !empty($editRow['is_active']) || (!$editRow && !$hasActiveProvider) ? 'checked' : '' ?>>
                تفعيل هذا المزود بعد الحفظ وإيقاف المزود النشط الآخر
            </label>

            <div class="actions">
                <button class="btn primary" type="submit" <?= !$encryptionReady ? 'disabled' : '' ?>><?= $editRow ? 'حفظ التعديلات' : 'إضافة المزود' ?></button>
                <?php if ($editRow): ?><a class="btn secondary" href="ai_providers.php">إلغاء التعديل</a><?php endif; ?>
            </div>
        </form>
    </section>

    <section class="card">
        <div class="section-title">المزودون المسجلون (<?= count($rows) ?>)</div>
        <?php if (!$rows): ?>
            <p class="muted">لا يوجد مزود مسجل حاليًا.</p>
        <?php else: ?>
            <div class="table-wrap">
                <table class="table">
                    <thead><tr><th>المزود</th><th>النموذج</th><th>Base URL</th><th>الأولوية</th><th>الحالة</th><th>آخر تحديث</th><th>الإجراءات</th></tr></thead>
                    <tbody>
                    <?php foreach ($rows as $row): ?>
                        <tr>
                            <td><?= h((string) $row['display_name']) ?><br><small class="muted"><?= h((string) $row['provider_code']) ?></small></td>
                            <td><span class="code"><?= h((string) $row['model_code']) ?></span></td>
                            <td><span class="code"><?= h((string) ($row['base_url'] ?? '—')) ?></span></td>
                            <td><?= (int) $row['priority'] ?></td>
                            <td><span class="badge <?= (int) $row['is_active'] === 1 ? 'green' : 'gray' ?>"><?= (int) $row['is_active'] === 1 ? 'نشط' : 'غير نشط' ?></span></td>
                            <td><?= h((string) $row['updated_at']) ?></td>
                            <td>
                                <div class="actions">
                                    <a class="btn secondary" href="?edit=<?= (int) $row['id'] ?>">تعديل</a>
                                    <form method="post">
                                        <input type="hidden" name="csrf" value="<?= h(platform_csrf()) ?>">
                                        <input type="hidden" name="action" value="test">
                                        <input type="hidden" name="provider_id" value="<?= (int) $row['id'] ?>">
                                        <button class="btn secondary" type="submit">اختبار الاتصال</button>
                                    </form>
                                    <?php if ((int) $row['is_active'] !== 1): ?>
                                        <form method="post">
                                            <input type="hidden" name="csrf" value="<?= h(platform_csrf()) ?>">
                                            <input type="hidden" name="action" value="activate">
                                            <input type="hidden" name="provider_id" value="<?= (int) $row['id'] ?>">
                                            <button class="btn success" type="submit">تفعيل</button>
                                        </form>
                                    <?php else: ?>
                                        <form method="post" onsubmit="return confirm('سيتم تعطيل المزود الحالي. هل تريد المتابعة؟');">
                                            <input type="hidden" name="csrf" value="<?= h(platform_csrf()) ?>">
                                            <input type="hidden" name="action" value="disable">
                                            <input type="hidden" name="provider_id" value="<?= (int) $row['id'] ?>">
                                            <button class="btn danger" type="submit">تعطيل</button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </section>
</div>
<script>
(() => {
    const provider = document.getElementById('provider_code');
    const baseField = document.getElementById('base-url-field');
    const baseInput = document.getElementById('base_url');
    const updateBaseField = () => {
        const isCompatible = provider && provider.value === 'compatible';
        if (baseField) baseField.style.display = isCompatible ? 'grid' : 'none';
        if (baseInput) baseInput.required = Boolean(isCompatible);
    };
    provider?.addEventListener('change', updateBaseField);
    updateBaseField();
})();
</script>
<?php admin_footer(); ?>
