<?php

namespace App\Controllers\Admin;

use App\Entities\Customer\ServiceEntity;
use App\Services\Customer\ServiceService;
use App\Services\Equipment\ServerService;
use App\Services\PaymentService;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class SearchController extends AdminController
{
    private ?ServerService $_serverService = null;
    private ?PaymentService $_paymentService = null;
    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;
    }
    public function getServerService(): ServerService
    {
        if ($this->_serverService === null) {
            $this->_serverService = new ServerService();
        }
        return $this->_serverService;
    }
    public function getPaymentService(): PaymentService
    {
        if ($this->_paymentService === null) {
            $this->_paymentService = new PaymentService();
        }
        return $this->_paymentService;
    }
    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 getChildServers(ServiceEntity $entity): array
    {
        $servers = [];
        foreach ($this->getServerService()->getEntities(['serviceinfo_uid' => $entity->getPK()]) as $serverEntity) {
            $servers[] = view_cell("\App\Cells\Equipment\ServerPartCell::parttable", [
                'serverinfo_uid' => $serverEntity->getPK(),
                'types' => SERVERPART['SERVICE_PARTTYPES'],
                'serviceinfo_serverinfo_uid' => $entity->getServerEntity()->getPK(),
                'template' => 'partlist_service'
            ]);
        }
        return $servers;
    }
    //

    protected function index_process(array $entities = []): array
    {
        $keyword = $this->request->getGet('keyword'); // 검색어
        if (!$keyword) {
            throw new \Exception("[{$keyword}] 검색어가 지정되지 않았습니다. ");
        }
        // ->select([
        //     's.serviceinfo_uid',
        //     's.uid AS server_uid',
        //     's.title AS server_title',
        //     'c.uid AS client_uid',
        //     'c.name AS client_name',
        //     'sp.uid AS part_uid',
        //     'sp.title AS part_title'
        // ])
        $db = \Config\Database::connect();
        $builder = $db->table('serverinfo s')
            ->distinct()
            ->select('s.serviceinfo_uid AS serviceinfo_uid')
            ->join('clientinfo c', 'c.uid = s.clientinfo_uid')
            ->join('serverpartinfo sp', 'sp.clientinfo_uid = c.uid', 'left')
            ->groupStart()
            ->like('c.name', $keyword, 'both', null, true)  // escape=true
            ->orLike('s.code', $keyword, 'both', null, true)
            ->orLike('s.title', $keyword, 'both', null, true)
            ->orLike('sp.title', $keyword, 'both', null, true)
            ->groupEnd();
        // SQL 확인용 (실제 운영에서는 주석 처리)
        // echo $builder->getCompiledSelect();
        // exit;
        $results = $builder->get()->getResultArray();
        // dd($results);
        $uids = [];
        foreach ($results as $result) {
            $uids[] = "'{$result['serviceinfo_uid']}'";
        }
        if (!count($uids)) {
            return [];
        }
        //서비스별 미납 Count
        $childServers = [];
        foreach ($this->getService()->getEntities("uid IN (" . implode(",", $uids) . ")") as $entity) {
            $entities[] = $entity;
            $childServers[$entity->getPK()] = $this->getChildServers($entity);
        }
        $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->getService()->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());
        }
    }
}
