<?php

namespace App\Controllers\Admin;

use App\Services\Customer\ServiceService;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class SearchController extends AdminController
{
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->content_title = lang("{$this->getService()->getClassName()}.title");
        $this->class_path .= $this->getService()->getClassName();
        $this->uri_path = '/admin/search';
        // $this->view_path  = '/admin/search';
    }
    public function getService(): ServiceService
    {
        if (!$this->_service) {
            $this->_service = new ServiceService();
        }
        return $this->_service;
    }
    protected function getResultSuccess(string $message = MESSAGES["SUCCESS"], ?string $actionTemplate = null): RedirectResponse|string
    {
        switch ($this->getService()->getAction()) {
            case 'index':
                $result = parent::getResultSuccess($message, 'search');
                break;
            default:
                $result = parent::getResultSuccess($message, $actionTemplate);
                break;
        }
        return $result;
    }
    protected function index_process(array $entities = []): array
    {
        $keyword = $this->request->getGet('keyword'); // 검색어
        if (!$keyword) {
            throw new \Exception("[{$keyword}] 검색어가 지정되지 않았습니다. ");
        }
        //검색어에 따른 서버정보를 검색 후 해당하는 서비스리스트를 가져온다.
        $rows = $this->getService()->getServerService()->getSearchServices($keyword);
        $uids = [];
        foreach ($rows as $row) {
            $uids[] = "'{$row->serviceinfo_uid}'";
        }
        //서비스별 서버리스트
        $childServers = [];
        foreach ($this->getService()->getEntities("uid IN (" . implode(",", $uids) . ")") as $entity) {
            $entities[] = $entity;
            $childServers[$entity->getPK()] = $this->getService()->getServerService()->getEntities(['serviceinfo_uid' => $entity->getPK()]);
        }
        $this->childServers = $childServers;
        return $entities;
    }
    public function index(): RedirectResponse|string
    {
        try {
            $this->getService()->setAction(__FUNCTION__);
            $this->getService()->setFormFields();
            //전달값정의
            $this->getService()->setFormDatas($this->request->getGet());
            $this->getService()->setFormFilters();
            $this->getService()->setFormRules();
            $this->getService()->setFormOptions();
            helper(['form']);
            //Return Url정의
            $this->getMyAuth()->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : ""));
            $entities = $this->index_process();
            $this->total_count = count($entities);
            $this->page_options = [];
            $this->entities = $entities;
            $this->per_page = 200;
            $this->page = 1;
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            return $this->getResultFail($e->getMessage());
        }
    }
}
