<?php
namespace App\Models\article;

use CodeIgniter\Model;

class ProcessibleModel extends Model
{
  // 지역 목록 조회
    public function getAreaList($sido = '', $gugun = '')
    {

        if (!empty($gugun)) {
        $gugun = substr($gugun, '0', '5');

        $sql = "SELECT a.region_cd, TRIM(REPLACE(a.region_nm, b.region_nm, '')) region_nm" .
            " FROM region_codes a" .
            " LEFT JOIN region_codes b ON b.region_cd = CONCAT(SUBSTR(a.region_cd,1,5),'00000')" .
            " WHERE a.region_cd LIKE concat(?, '%')" .
            " AND a.region_cd NOT LIKE '%00000'" .
            " AND a.region_cd LIKE '%00'" .
            " AND a.use_yn = 'Y'" .
            " ORDER BY a.region_nm ASC";

        $query = $this->db->query($sql, [$gugun]);

        } else if (!empty($sido)) {
        $chk_sido = substr($sido, '0', '2');

        if ($chk_sido === '36') {
            $sido = substr($sido, '0', '4');
            $sql = "SELECT a.region_cd, TRIM(REPLACE(a.region_nm, b.region_nm, '')) region_nm " .
            "FROM region_codes a " .
            "LEFT JOIN region_codes b ON b.region_cd = CONCAT(SUBSTR(a.region_cd,1,4),'000000') " .
            "WHERE a.region_cd LIKE concat(?, '%') " .
            "AND a.region_cd NOT LIKE '%000000' " .
            "AND a.region_cd LIKE '%00' " .
            "AND a.use_yn = 'Y' " .
            "AND EXISTS (SELECT 'x' FROM region_codes c WHERE c.region_cd LIKE CONCAT(SUBSTR(a.region_cd,1,5),'%') AND c.region_cd > CONCAT(SUBSTR(a.region_cd,1,5),'00000')) " .
            "ORDER BY a.region_nm ASC";
        } else {
            $sido = substr($sido, '0', '2');
            $sql = "SELECT a.region_cd, TRIM(REPLACE(a.region_nm, b.region_nm, '')) region_nm" .
            " FROM region_codes a" .
            " LEFT JOIN region_codes b ON b.region_cd = CONCAT(SUBSTR(a.region_cd,1,2),'00000000')" .
            " WHERE a.region_cd LIKE concat(?, '%')" .
            " AND a.region_cd NOT LIKE '%00000000'" .
            " AND a.region_cd LIKE '%00000'" .
            " AND a.use_yn = 'Y'" .
            " AND EXISTS (SELECT 'x' FROM region_codes c WHERE c.region_cd LIKE CONCAT(SUBSTR(a.region_cd,1,5),'%') AND c.region_cd > CONCAT(SUBSTR(a.region_cd,1,5),'00000'))" .
            " ORDER BY a.region_nm ASC";
        }

        $query = $this->db->query($sql, [$sido]);
        } else {
        $sql = "SELECT a.region_cd, a.region_nm " .
            "FROM region_codes a " .
            "WHERE (a.region_cd LIKE '%00000000' " .
            "AND a.use_yn = 'Y') " .
            "OR region_cd = 3611000000;";

        $query = $this->db->query($sql);
        }


        return $query->getResultArray();
    }


    /**
     * 일자별 처리가능 수량
     */
    public function getTotal1($data)
    {
        $sql = "
                SELECT
                COUNT(*) AS cnt
                FROM
                (
                SELECT 
                a.sol_date sc_date, DATE_FORMAT(a.sol_date, '%w') day_week
                , sum(ifnull(c.am_cnt, b.am_cnt)) am_cnt
                , sum(ifnull(c.pm_cnt,b.pm_cnt)) pm_cnt
                , sum(ifnull(c.day_cnt, b.day_cnt)) day_cnt
                , case count(b.region_cd) when count(c.region_cd) then 'Y' ELSE 'N' END svc_check
                , sum(c.day_cnt) svc_count
                FROM calendar a
                LEFT JOIN service_count b on b.sc_date = '0000-00-00'
                LEFT JOIN service_count c on c.sc_date = a.sol_date AND c.region_cd = b.region_cd
                WHERE a.sol_date BETWEEN ? AND ?
                GROUP BY a.sol_date ASC
                ) AS a";

        $query = $this->db->query($sql, [$data['sdate'], $data['edate']]);

        return $query->getRow()->cnt;
    }

    public function getList1($start, $end, $data)
    {
        $sql = "SELECT 
                a.sol_date sc_date, DATE_FORMAT(a.sol_date, '%w') day_week
                , sum(ifnull(c.am_cnt, b.am_cnt)) am_cnt
                , sum(ifnull(c.pm_cnt,b.pm_cnt)) pm_cnt
                , sum(ifnull(c.day_cnt, b.day_cnt)) day_cnt
                , case count(b.region_cd) when count(c.region_cd) then 'Y' ELSE 'N' END svc_check
                , sum(c.day_cnt) svc_count
                FROM calendar a
                LEFT JOIN service_count b on b.sc_date = '0000-00-00'
                LEFT JOIN service_count c on c.sc_date = a.sol_date AND c.region_cd = b.region_cd
                WHERE a.sol_date BETWEEN ? AND ?
                GROUP BY a.sol_date ASC ";

        $sql .= "LIMIT {$start}, {$end}";

        $query = $this->db->query($sql, [$data['sdate'], $data['edate']]);

        return $query->getResultArray();
    }

  /**
   * 지역별 수량
   */
    public function getTotal2($data)
    {
        $sql = "SELECT 
                COUNT(*) AS cnt
                FROM calendar a
                LEFT JOIN service_count b on b.sc_date = '0000-00-00' and b.region_cd LIKE CONCAT(SUBSTR(?,1,2),'%')
                LEFT JOIN service_count c on c.sc_date = a.sol_date and c.region_cd = b.region_cd
                JOIN region_codes d on d.region_cd = b.region_cd and d.use_yn = 'Y'
                WHERE a.sol_date = ?
                ORDER BY d.region_nm";

        $query = $this->db->query($sql, [$data['region'], $data['sdate']]);

        return $query->getRow()->cnt;
    }

    public function getList2($data)
    {
        $sql = "SELECT 
                a.sol_date
                , b.region_cd, d.region_nm
                , c.am_cnt, b.am_cnt default_am_cnt
                , c.pm_cnt, b.pm_cnt default_pm_cnt
                , c.day_cnt, b.day_cnt default_day_cnt
                FROM calendar a
                LEFT JOIN service_count b on b.sc_date = '0000-00-00' and b.region_cd LIKE CONCAT(SUBSTR(?,1,2),'%')
                LEFT JOIN service_count c on c.sc_date = a.sol_date and c.region_cd = b.region_cd
                JOIN region_codes d on d.region_cd = b.region_cd and d.use_yn = 'Y'
                WHERE a.sol_date = ?
                ORDER BY d.region_nm";

        $query = $this->db->query($sql, [$data['region'], $data['sdate']]);

        return $query->getResultArray();
    }

  /**
   * 기본수량
   */
    public function getTotal3($data)
    {
        $sql = "SELECT 
                COUNT(*) AS cnt
                FROM (SELECT DISTINCT CONCAT(SUBSTR(aa.region_cd, 1, 5), '00000') region_cd FROM region_codes aa WHERE aa.region_cd like CONCAT(SUBSTR(?,1,2),'%') AND aa.region_cd NOT LIKE '%00000000' AND aa.dept_sq != 0 AND aa.use_yn = 'Y') a
                INNER JOIN region_codes b ON b.region_cd = a.region_cd
                LEFT JOIN service_count c ON c.sc_date = '0000-00-00' AND c.region_cd = a.region_cd
                ORDER BY b.region_nm";

        $query = $this->db->query($sql, [$data['region']]);

        return $query->getRow()->cnt;
    }

    public function getList3($data)
    {
        $sql = "SELECT 
                b.region_cd, b.region_nm, IFNULL(c.am_cnt,0)am_cnt, IFNULL(c.pm_cnt,0) pm_cnt
                FROM (SELECT DISTINCT CONCAT(SUBSTR(aa.region_cd, 1, 5), '00000') region_cd FROM region_codes aa WHERE aa.region_cd like CONCAT(SUBSTR(?,1,2),'%') AND aa.region_cd NOT LIKE '%00000000' AND aa.dept_sq != 0 AND aa.use_yn = 'Y') a
                INNER JOIN region_codes b ON b.region_cd = a.region_cd
                LEFT JOIN service_count c ON c.sc_date = '0000-00-00' AND c.region_cd = a.region_cd
                ORDER BY b.region_nm";

        $query = $this->db->query($sql, [$data['region']]);

        return $query->getResultArray();
    }

  // 일자별 수량 엑셀
    public function getExcelList($data)
    {
        $sql = "SELECT 
                a.sol_date sc_date
                    , CASE WHEN DATE_FORMAT(a.sol_date, '%w') = 'N' THEN '기본지정' ELSE '별도지정' END AS sc_type
                , sum(ifnull(c.am_cnt, b.am_cnt)) am_cnt
                , sum(ifnull(c.pm_cnt,b.pm_cnt)) pm_cnt
                , sum(ifnull(c.day_cnt, b.day_cnt)) day_cnt
                , case count(b.region_cd) when count(c.region_cd) then 'Y' ELSE 'N' END svc_check
                , sum(c.day_cnt) svc_count
                FROM calendar a
                LEFT JOIN service_count b on b.sc_date = '0000-00-00'
                LEFT JOIN service_count c on c.sc_date = a.sol_date AND c.region_cd = b.region_cd
                WHERE a.sol_date BETWEEN ? AND ?
                GROUP BY a.sol_date ASC";

        $query = $this->db->query($sql, [$data['sdate'], $data['edate']]);

        return $query->getResultArray();
    }

  // 지역별 수량 저장
    public function saveArea($data)
    {
        $usr_sq = session('usr_sq');
        $now = date('Y-m-d H:i:s');

        $insertData = [
            'sc_date' => $data['sc_date'],
            'region_cd' => $data['region_cd'],
            'am_cnt' => $data['am_cnt'],
            'pm_cnt' => $data['pm_cnt'],
            'day_cnt' => (int)$data['am_cnt'] + (int)$data['pm_cnt'],
            'insert_usr' => $usr_sq,
            'insert_tm' => $now,
            'update_usr' => $usr_sq,
            'update_tm' => $now
        ];

        // CI4 Query Builder upsert (INSERT ... ON DUPLICATE KEY UPDATE)
        $result = $this->db->table('service_count')->upsert($insertData);

        return [
            'success' => $result !== false,
            'msg' => $result !== false ? '성공' : '저장실패'
        ];
    }

    public function saveCount($data)
    {
        $usr_sq = session('usr_sq');
        $now = date('Y-m-d H:i:s');

        $insertData = [
            'sc_date' => '0000-00-00',
            'region_cd' => $data['region_cd'],
            'am_cnt' => $data['am_cnt'],
            'pm_cnt' => $data['pm_cnt'],
            'day_cnt' => (int)$data['am_cnt'] + (int)$data['pm_cnt'],
            'insert_usr' => $usr_sq,
            'insert_tm' => $now,
            'update_usr' => $usr_sq,
            'update_tm' => $now
        ];

        // CI4 Query Builder upsert
        $result = $this->db->table('service_count')->upsert($insertData);
        
        // 실행된 쿼리 로그 출력
        $lastQuery = $this->db->getLastQuery();
        log_message('info', '[ProcessibleModel::saveCount] Query: ' . $lastQuery);
        log_message('info', '[ProcessibleModel::saveCount] Affected Rows: ' . $this->db->affectedRows());
        
        if ($result === false) {
            $error = $this->db->error();
            log_message('error', '[ProcessibleModel::saveCount] Error: ' . json_encode($error));
            
            return [
                'success' => false,
                'msg' => '저장실패: ' . ($error['message'] ?? '알 수 없는 오류'),
                'query' => (string) $lastQuery,
                'error' => $error
            ];
        }

        return [
            'success' => true,
            'query' => (string) $lastQuery,
            'affected_rows' => $this->db->affectedRows()
        ];
    }

  /**
   * 슬롯 동기화
   * 
   */
    public function getSyncSlotData($baseDate, $region_cd)
    {
        
        $sql = "SELECT sc_date, region_cd, am_cnt, pm_cnt, day_cnt FROM service_count WHERE sc_date = ? AND region_cd IN ?";
        $datas = [
        $baseDate,
        $region_cd
        ];
        $query = $this->db->query($sql, $datas);
        return $query->getResultArray();
        
    }
}