<?php

namespace App\Services\Customer;

use App\Entities\Customer\ServiceEntity;
use App\Entities\Equipment\ServerEntity;
use App\Models\Customer\ServiceModel;

class ServiceService extends CustomerService
{
    private ?string $_searchIP = null;
    public function __construct()
    {
        parent::__construct(new ServiceModel());
        $this->addClassName('Service');
    }
    public function getFormFields(): array
    {
        return [
            'fields' => [
                "clientinfo_uid",
                "type",
                "location",
                "serverinfo_uid",
                "billing_at",
                "amount",
                "start_at",
                "end_at",
                "history",
                "status",
            ],
            'filters' => [
                'site',
                'clientinfo_uid',
                'serverinfo_uid',
                'type',
                'location',
                'status'
            ],
        ];
    }
    public function getIndexFields(): array
    {
        return [
            'fields' => [
                'site',
                'clientinfo_uid',
                'type',
                'location',
                'serverinfo_uid',
                'billing_at',
                'amount',
                'start_at',
                'end_at',
                'updated_at',
                'status',
                'user_uid'
            ],
            'filters' => [
                'site',
                'clientinfo_uid',
                'serverinfo_uid',
                'type',
                'location',
                'status'
            ],
        ];
    }
    public function getBatchjobFields(): array
    {
        return ['site', 'clientinfo_uid', 'status'];
    }
    //기본 기능부분
    //검색용
    public function setSearchIp(string $ip): void
    {
        $this->_searchIP = $ip;
    }
    public function getSearchIp(): string|null
    {
        return $this->_searchIP;
    }
    // protected function getEntities_process(mixed $where = null,array $columns = ['*']): mixed
    // {
    //     $ip = $this->getSearchIp();
    //     if ($ip) {
    //         $sql = "SELECT serviceinfo.* FROM serviceinfo
    //         LEFT JOIN serviceinfo_items ON serviceinfo.uid = serviceinfo_items.serviceinfo_uid
    //         WHERE serviceinfo_items.item_type = ?
    //         AND serviceinfo_items.item_uid IN (SELECT uid FROM ipinfo WHERE ip = ?)";
    //         return $this->getModel()->query($sql, ['IP', $ip])->getResult(ServiceEntity::class);
    //     }
    //     return parent::getEntities_process($where,$columns);
    // }
    //기본 기능부분
    //FieldForm관련용
    //interval을 기준으로 최근 신규 서비스정보 가져오기
    final public function getEntitiesByNewService(int $interval, string $status = ServiceEntity::DEFAULT_STATUS): array
    {
        return $this->getEntities(sprintf("start_at >= NOW()-INTERVAL {$interval} DAY AND status = '%s'", $status));
    }
    //서비스 방식에 따른 서비스별 Count
    final public function getTotalCountsByType(): array
    {
        $totalCounts = [
            'chiba_total' => 0,
            'tokyo_total' => 0,
            'all_total' => 0,
            'normal' => ['chiba' => 0, 'tokyo' => 0, 'total' => 0],
            'defence' => ['chiba' => 0, 'tokyo' => 0, 'total' => 0],
            'dedicated' => ['chiba' => 0, 'tokyo' => 0, 'total' => 0],
            'alternative' => ['chiba' => 0, 'tokyo' => 0, 'total' => 0],
            'test' => ['chiba' => 0, 'tokyo' => 0, 'total' => 0],
        ];
        $sql = "SELECT type,
                COUNT(CASE WHEN location = 'chiba' THEN 1 END) AS chiba,
                COUNT(CASE WHEN location = 'tokyo' THEN 1 END) AS tokyo,
                COUNT(CASE WHEN location IN ('chiba', 'tokyo') THEN 1 END) AS total
                FROM serviceinfo GROUP BY type";
        foreach ($this->getModel()->query($sql)->getResult() as $row) {
            $totalCounts[$row->type] = [
                'chiba' => $row->chiba,
                'tokyo' => $row->tokyo,
                'total' => $row->total,
            ];
            $totalCounts['chiba_total'] += $row->chiba;
            $totalCounts['tokyo_total'] += $row->tokyo;
        }
        $totalCounts['all_total'] = $totalCounts['chiba_total'] + $totalCounts['tokyo_total'];
        return $totalCounts;
    }
    //다음 달로 결제일을 연장합니다.
    final public function extendBillingAt(string $billing_at, string $status): bool
    {
        $sql = "UPDATE serviceinfo SET billing_at =
                IF(DAY(billing_at) > DAY(LAST_DAY(billing_at)),
                    LAST_DAY(DATE_ADD(billing_at, INTERVAL 1 MONTH)),
                    DATE_ADD(billing_at, INTERVAL 1 MONTH)
                ) WHERE billing_at = ? AND status = ?";
        return $this->getModel()->query($sql, [$billing_at, $status]);
    }
    public function create(array $formDatas): ServiceEntity
    {
        $entity = parent::create($formDatas);
        //서버경우 서비스중으로 설정작업
        // $this->getServerService()->setService($entity)ServerEntity::STATUS_OCCUPIED);
        return parent::create($formDatas);
    }
    //List 검색용
    //검색어조건절처리
    public function index_condition_filterWord(string $word): void
    {
        if ($this->isIPAddress($word, 'ipv4')) {
            $this->setSearchIp($word);
        } else {
            parent::index_condition_filterWord($word);
        }
    }
}
