<?php

namespace lib\Services;

use lib\Entities\ServiceEntity as Entity;
use lib\Models\AdddbModel;
use lib\Models\ClientModel;
use lib\Models\ServiceModel as Model;

class ServiceService extends CommonService
{
  private ?ClientModel $_clientModel = null;
  private ?Model $_model = null;
  private ?AdddbModel $_adddbModel = null;
  public function __construct()
  {
    parent::__construct();
  }
  final public function getClassName(): string
  {
    return "Service";
  }
  final public function getClassPath(): string
  {
    return $this->getClassName();
  }
  public function getModel(): Model
  {
    if ($this->_model === null) {
      $this->_model = new Model();
      // $this->_model->setDebug(true);
    }
    return $this->_model;
  }
  final public function getClientModel(): ClientModel
  {
    if ($this->_clientModel === null) {
      $this->_clientModel = new ClientModel();
    }
    return $this->_clientModel;
  }
  public function getAdddbModel(): AdddbModel
  {
    if ($this->_adddbModel === null) {
      $this->_adddbModel = new AdddbModel();
    }
    return $this->_adddbModel;
  }

  public function getNewServerCount(int $day, array $excepts): int|string
  {
    $this->getModel()->where("service_open_date > DATE_ADD(now(), INTERVAL -{$day} DAY)");
    $this->getModel()->where("service_status", 'o');
    $this->getModel()->whereNotIn("service_line", $excepts);
    $count =  $this->getModel()->countAllResults();
    // echo __FUNCTION__ . ":" . $this->getModel()->getLastQuery();
    return $count;
  }
  public function getUnPaymentCount(array $excepts): int|string
  {
    $this->getModel()->where("service_payment_date > now()");
    $this->getModel()->where("service_status", 'o');
    $this->getModel()->whereNotIn("service_line", $excepts);
    $count =  $this->getModel()->countAllResults();
    // echo __FUNCTION__ . ":" . $this->getModel()->getLastQuery();
    return $count;
  }

  private function getTotalCountByDistriction(string $where, string $type, string $switch_code1, string $switch_code2): int
  {
    $this->getModel()->where($where);
    $this->getModel()->where(["service_line" => $type, "service_status" => 'o']);
    $this->getModel()->where("service_sw BETWEEN '{$switch_code1}' AND '{$switch_code2}'");
    $count =  $this->getModel()->countAllResults();
    // echo "<BR>" . $this->getModel()->getLastQuery();
    return $count;
  }
  final public function getTotalCount(array $siteinfo): array
  {
    $temps = array();
    foreach ($siteinfo['totalcount_customers'] as $customer => $where) {
      $temps[$customer] = [];
      foreach ($siteinfo['totalcount_types'] as $type) {
        $temps[$customer][$type]['Chiba'] = $this->getTotalCountByDistriction($where, $type, 'C00%', 'C64%');
        $temps[$customer][$type]['Tokyo'] = $this->getTotalCountByDistriction($where, $type, 'C80%', 'C99%');
      } //foreach
      // echo var_dump($temps);
    } //foreach
    return $temps;
  }
  final public function getExtras(array $service_codes): mixed
  {
    // 공백 값 제거
    $service_codes = array_filter($service_codes, function ($value) {
      return !empty(trim($value));  // 공백 제거 후 비어있지 않은 값만 필터링
    });
    // 배열 키를 다시 정렬 (선택 사항)
    $service_codes = array_values($service_codes);
    // echo "<BR>" . $this->getAdddbModel()->getLastQuery();
    // dd($service_codes);
    if (!count($service_codes)) {
      // echo $this->getAdddbModel()->getLastQuery();
      return [];
    }
    $this->getModel()->select("clientdb.Client_Name,{$this->getModel()->getTable()}.server_code,{$this->getModel()->getTable()}.service_ip,{$this->getModel()->getTable()}.service_os,{$this->getModel()->getTable()}.service_sw");
    $this->getModel()->join('clientdb', "{$this->getModel()->getTable()}.client_code=clientdb.Client_Code");
    $this->getModel()->whereIn('service_code', $service_codes);
    // $sql = sprintf("SELECT C.Client_Name,S.server_code,S.service_ip,S.service_os,S.service_sw
    // FROM servicedb AS S JOIN clientdb AS C ON S.client_code = C.Client_Code
    // WHERE S.service_code IN (SELECT service_code FROM adddb WHERE addDB_code ='%s')", $code);
    // return $this->getRows($sql);
    return $this->getModel()->getEntitys();
  }

  public function getNews(int $limit): array
  {
    $this->getModel()->orderBy($this->getModel()->getPKField(),  'DESC');
    $this->getModel()->limit($limit);
    return $this->getModel()->getEntitys();
  }

  public function getServiceByServiceCode(string $service_code): Entity|null
  {
    $this->getModel()->where("service_code", $service_code);
    return $this->getModel()->getEntity();
  }
}
