<?php
namespace App\Controllers\Article;

use App\Controllers\BaseController;
use App\Models\article\DeptModel;
use App\Models\common\CodeModel;

class Dept extends BaseController
{
  private $model, $codeModel;
  public function __construct()
  {
    $this->codeModel = new CodeModel();
    $this->model = new DeptModel();
  }

  public function lists(): string
  {

    $codes = $this->codeModel->getCodeLists(['NHN_PRODUCT_TYPE', 'RECEIPT_STATUS1', 'RESERVED_APM']); // 코드조회
    $sido = $this->model->getAreaList(); // 지역조회
    $bonbu = $this->model->getBonbuList();
    $team = $this->model->getTeamList();
    $user = $this->model->getUserList();

    $this->data['sido'] = $sido;
    $this->data['bonbu'] = $bonbu;
    $this->data['team'] = $team;
    $this->data['user'] = $user;
    $this->data['codes'] = $codes;


    return view("pages/article/dept/lists", $this->data);
  }

  public function getResultList()
  {
    $start = (int) $this->request->getGet('start') ?: 0;
    $end = (int) $this->request->getGet('length') ?: 10;

    $data = [
      'rcpt_atclno' => $this->request->getGet('rcpt_atclno'), // 매물ID

      'sdate' => $this->request->getGet('sdate'),           // 시작일
      'edate' => $this->request->getGet('edate'),           // 종료일

      'rsrv_tm_ap' => $this->request->getGet('rsrv_tm_ap'),   // 유형
      'rsrv_sdate' => $this->request->getGet('rsrv_sdate'),   // 시작일
      'rsrv_edate' => $this->request->getGet('rsrv_edate'),   // 종료일

      'bonbu' => $this->request->getGet('bonbu'),           // 본부
      'team' => $this->request->getGet('team'),           // 팀
      'user' => $this->request->getGet('user'),             // 담당자

      'sido' => $this->request->getGet('sido'),          // 시도
      'gugun' => $this->request->getGet('gugun'),        // 시군구
      'dong' => $this->request->getGet('dong'),         // 읍면동

      'ground_plan_yn' => $this->request->getGet('ground_plan_yn'),         // 평면도유무
      'ground_plan' => $this->request->getGet('ground_plan'),               // 평면도요청
      'direct_trad_yn' => $this->request->getGet('direct_trad_yn'),         // 직거래

      'stat' => $this->request->getGet('stat'),

      'srchType' => $this->request->getGet('srchType'),                     // 검색유형
      'srchTxt' => $this->request->getGet('srchTxt'),                       // 검색어
    ];

    $totalCount = $this->model->getTotalCount($data);

    $datas = $this->model->getResultList($start, $end, $data);

    $deptStatistics = $this->model->getDeptStatistics($data); // 조직별통계
    $areaStatistics = $this->model->getAreaStatistics($data); // 지역별통계

    return $this->response->setJSON(body: [
      'recordsTotal' => $totalCount,
      'recordsFiltered' => $totalCount,
      'data' => $datas,
      'widgets' => [
        'deptList' => $deptStatistics,
        'areaStats' => $areaStatistics,
      ],
    ]);
  }


  // 관할포인트 인쇄 - 화면
  public function print(): string
  {
    $deptSq = $this->request->getGet('depChk');
    $dept_cnt = count($deptSq);


    $listDept = $this->model->getDeptMapList($deptSq);

    if (!empty($listDept)) {
      $lati = 0;
      $long = 0;
      foreach ($listDept as $dept) {
        $lati += $dept['rcpt_y'];
        $long += $dept['rcpt_x'];
      }

      $lati = $lati / $dept_cnt;
      $long = $long / $dept_cnt;
    }

    return view("pages/article/dept/printMap", [
      // 'lati' => $lati,
      // 'long' => $long,
      'listDept' => $listDept,
    ]);
  }


  // 엑셀 다운로드
  public function excel()
  {
    try {

      $data = [
        'rcpt_atclno' => $this->request->getGet('rcpt_atclno'), // 매물ID

        'sdate' => $this->request->getGet('sdate'),           // 시작일
        'edate' => $this->request->getGet('edate'),           // 종료일

        'rsrv_tm_ap' => $this->request->getGet('rsrv_tm_ap'),   // 유형
        'rsrv_sdate' => $this->request->getGet('rsrv_sdate'),   // 시작일
        'rsrv_edate' => $this->request->getGet('rsrv_edate'),   // 종료일

        'bonbu' => $this->request->getGet('bonbu'),           // 본부
        'team' => $this->request->getGet('team'),           // 팀
        'user' => $this->request->getGet('user'),             // 담당자

        'sido' => $this->request->getGet('sido'),          // 시도
        'gugun' => $this->request->getGet('gugun'),        // 시군구
        'dong' => $this->request->getGet('dong'),         // 읍면동

        'ground_plan_yn' => $this->request->getGet('ground_plan_yn'),         // 평면도유무
        'ground_plan' => $this->request->getGet('ground_plan'),               // 평면도요청
        'direct_trad_yn' => $this->request->getGet('direct_trad_yn'),         // 직거래

        'stat' => $this->request->getGet('stat'),

        'srchType' => $this->request->getGet('srchType'),                     // 검색유형
        'srchTxt' => $this->request->getGet('srchTxt'),                       // 검색어
      ];

      $datas = $this->model->getExcelList($data);

      return $this->response->setJSON(body: [
        'data' => $datas,
      ]);

    } catch (\Exception $e) {
      $e->getPrevious()->getTraceAsString();
    }
  }

  public function excel2()
  {
    try {

      $data = [
        'rcpt_atclno' => $this->request->getGet('rcpt_atclno'), // 매물ID

        'sdate' => $this->request->getGet('sdate'),           // 시작일
        'edate' => $this->request->getGet('edate'),           // 종료일

        'rsrv_tm_ap' => $this->request->getGet('rsrv_tm_ap'),   // 유형
        'rsrv_sdate' => $this->request->getGet('rsrv_sdate'),   // 시작일
        'rsrv_edate' => $this->request->getGet('rsrv_edate'),   // 종료일

        'bonbu' => $this->request->getGet('bonbu'),           // 본부
        'team' => $this->request->getGet('team'),           // 팀
        'user' => $this->request->getGet('user'),             // 담당자

        'sido' => $this->request->getGet('sido'),          // 시도
        'gugun' => $this->request->getGet('gugun'),        // 시군구
        'dong' => $this->request->getGet('dong'),         // 읍면동

        'ground_plan_yn' => $this->request->getGet('ground_plan_yn'),         // 평면도유무
        'ground_plan' => $this->request->getGet('ground_plan'),               // 평면도요청
        'direct_trad_yn' => $this->request->getGet('direct_trad_yn'),         // 직거래

        'stat' => $this->request->getGet('stat'),

        'srchType' => $this->request->getGet('srchType'),                     // 검색유형
        'srchTxt' => $this->request->getGet('srchTxt'),                       // 검색어

        'type' => 'excel',
      ];

      $datas = $this->model->getResultList(null, null, $data);

      return $this->response->setJSON(body: [
        'data' => $datas,
      ]);

    } catch (\Exception $e) {
      $e->getPrevious()->getTraceAsString();
    }
  }


  // 배정변경
  public function updateAssign()
  {
    try {

      $team = $this->request->getPost('team');
      $damdang = $this->request->getPost(index: 'usr_id');

      if (empty($team)) {
        return $this->response->setJSON([
          'code' => '9',
          'msg' => '팀정보 누락',
        ]);
      }

      if (empty($damdang)) {
        return $this->response->setJSON([
          'code' => '9',
          'msg' => '담당자정보 누락',
        ]);
      }


      $rows = $this->request->getPost('rows');

      $rows = json_decode($rows, true);

      if (count($rows) > 0) {
        foreach ($rows as $row) {
          $params = [
            'dept_sq' => $team,
            'damdang' => $damdang,
            'rcpt_sq' => $row['rcpt_sq'],
          ];

          $this->model->updateAssign($params);

        }
      } else {
        return $this->response->setJSON([
          'code' => '9',
          'msg' => '저장데이터 누락',
        ]);
      }

      return $this->response->setJSON([
        'code' => '0',
        'msg' => 'success'
      ]);


    } catch (\Exception $e) {
      return $this->response->setJSON([
        'code' => '9',
        'msg' => $e->getMessage(),
      ]);
    }
  }

  // 상세화면
  public function detail($id): string
  {

    $id = (string) $id;

    if ($id === '') {
      throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
    }

    $codes = $this->codeModel->getCodeLists(['TRADE_TYPE', 'RECEIPT_STATUS2', 'RECEIPT_STATUS3', 'SMS_MSG_TYPE']); // 코드조회
    $bonbu = $this->model->getBonbuList();
    $team = $this->model->getTeamList();

    $data = $this->model->getDetail($id);
    $history = $this->model->getHistory($id);

    // $aptGround = $this->model->getAptGround($data['rcpt_dong']);

    // 시간대별통계
    $tmCount = $this->model->getUsrRsrvDateTmCount($id);

    $this->data['codes'] = $codes;
    $this->data['bonbu'] = $bonbu;
    $this->data['team'] = $team;

    $this->data['data'] = $data;
    $this->data['history'] = $history;

    $this->data['tmCount'] = $tmCount;

    return view("pages/article/dept/detail", $this->data);
  }
}