<?php

namespace lib\Services;

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

class ServiceService extends CommonService
{
  public function __construct()
  {
    parent::__construct();
  }
  final public function getClassName(): string
  {
    return "Service";
  }
  final public function getClassPath(): string
  {
    return $this->getClassName();
  }
  public function getModelClass(): string
  {
    return Model::class;
  }
  public function getEntityClass(): string
  {
    return Entity::class;
  }

  //지역(치바,도쿄등)에 따른 DASHBOARD용 서비스 카운트
  private function getDistrictCountForDashboard(string $where, string $type, array $switchcodes): int
  {
    $switchcode_begin = $switchcodes['begin'];
    $switchcode_end  = $switchcodes['end'];
    $this->getModel()->where($where);
    $this->getModel()->where(["service_line" => $type, "service_status" => 'o']);
    $this->getModel()->where("service_sw BETWEEN '{$switchcode_begin}' AND '$switchcode_end'");
    $count =  $this->getModel()->count();
    // echo "<BR>" . $this->getModel()->getLastQuery();
    return $count;
  }
  final public function getTotalCountForDashboard(array $siteinfo): array
  {
    $temps = array();
    foreach ($siteinfo['totalcount_customers'] as $customer => $where) {
      $temps[$customer] = [];
      foreach ($siteinfo['totalcount_types'] as $type) {
        foreach (DBMS_SERVICE_SWITCHCODE as $district => $switchcodes) {
          $temps[$customer][$type][$district] = $this->getDistrictCountForDashboard($where, $type, $switchcodes);
        }
      } //foreach
      // echo var_dump($temps);
    } //foreach
    return $temps;
  }

  //도메인쿠폰 사용용
  public function useCouponByService(ServiceEntity $service, int $coupon): bool
  {
    if ($coupon < 0) {
      throw new \Exception("쿠폰수량이 잘못되었습니다. 쿠폰수량 : $coupon");
    }
    $this->getModel()->where("service_code", $service->getServiceCode());
    $this->getModel()->update(["coupon=(coupon-{$coupon})" => null, "coupon_use=(coupon_use+{$coupon})" => null]);
    return true;
  }
  //도메인쿠폰 Reset
  public function resetCouponByClient(ClientEntity $client, int $coupon): bool
  {
    if ($coupon < 0) {
      throw new \Exception("쿠폰수량이 잘못되었습니다. 쿠폰수량 : $coupon");
    }
    $this->getModel()->where("client_code", $client->getClientCode());
    $this->getModel()->where("server_code", $client->getTitle() . "_일회성");
    $this->getModel()->update(["coupon" => $coupon, "coupon_use" => 0]);
    return true;
  } //setCoupon
}
