<?php

// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: AiServicesConfigController.php,v 1.1.2.4.2.1 2025/07/21 13:03:42 qvarin Exp $

namespace Pmb\AI\Controller;

use Pmb\AI\Library\Services\Service;
use Pmb\AI\Orm\AiServicesConfigOrm;
use Pmb\AI\Views\AiServicesConfigView;
use Pmb\Common\Controller\Controller;
use Pmb\Common\Helper\Helper;

if (stristr($_SERVER['REQUEST_URI'], basename(__FILE__))) {
    die("no access");
}

class AiServicesConfigController extends Controller
{
    public $action = "";

    public function proceed($action = "")
    {
        $this->action = $action;

        switch ($action) {
            case "save":
                return $this->saveAction();
            case "delete":
                $this->deleteAction();
                break;
            case "validatetoken":
                return $this->validateTokenAction();
            case "getmodels":
                return $this->getModelsAction();
            default:
                $this->getFormAction();
                break;
        }
    }


    public function getFormAction()
    {
        $service = new Service();
        $aiServicesConfigView = new AiServicesConfigView("AI/aiServicesConfig", [
            "aiserviceslist" => Service::getServices(),
            "aiserviceconfig" => $service->getParameters(),
        ]);
        print $aiServicesConfigView->render();
    }


    public function saveAction()
    {
        $service = new Service();
        return [
            "valided" => $service->save(Helper::toArray($this->data)),
        ];
    }

    public function deleteAction()
    {
        try {
            $aiServicesOrm = new AiServicesConfigOrm(AiServicesConfigOrm::ID_SERVICE_CONFIG);
            $aiServicesOrm->settings_ai_services_config = null;
            $aiServicesOrm->save();
            return true;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    public function setData($data)
    {
        $this->data = $data;
    }

    public function validateTokenAction()
    {
        $service = new Service();
        $return = [
            "valided" => $service->validateToken(intval($this->data->id), Helper::toArray($this->data->parameters))
        ];
        return $return;
    }

    public function getModelsAction()
    {
        $service = new Service();
        $return = [
            "listModels" => $service->getModels(intval($this->data->id), Helper::toArray($this->data->parameters))
        ];
        return $return;
    }
}
