<?php

namespace Core\App\Controllers;

use Core\App\Models\GeminiSettingModel;
use Core\App\Services\GeminiService;

class GeminiController
{
  public function settings()
{
    $model = new GeminiSettingModel();

    $gemini = $model->get() ?? [
        'api_key'   => '',
        'is_active' => 0,
        'dialect'   => 'fusha',
        'model'     => '',
    ];

    $models = [];
    $modelsError = '';

    if (!empty($gemini['api_key'])) {
        try {
            $models = GeminiService::listModels();
        } catch (\Throwable $e) {
            $modelsError = $e->getMessage();
        }
    }

    require ROOT_PATH . '/admin/templates/settings/gemini.php';
}


    public function save()
    {
        $apiKey  = trim($_POST['api_key'] ?? '');
        $enabled = isset($_POST['enabled']) ? 1 : 0;
        $dialect = $_POST['dialect'] ?? 'fusha';
        $model   = $_POST['model'] ?? '';

        (new GeminiSettingModel())->save($apiKey, $enabled, $dialect, $model);

        header('Location: /admin/settings/gemini');
        exit;
    }

    public function generateProductDescription()
    {
        header('Content-Type: application/json');

        try {
            $title = trim($_POST['title'] ?? '');

            if ($title === '') {
                throw new \Exception(__('ai.error.missing_title'));
            }

            $result = GeminiService::generateProductDescription($title);

            echo json_encode([
                'success' => true,
                'short'   => $result['short'],
                'full'    => $result['full'],
            ]);

        } catch (\Throwable $e) {
            echo json_encode([
                'success' => false,
                'message' => $e->getMessage(),
            ]);
        }
    }
}
