<?php
//require_once('conf.inc.php');
//require_once("dbCon.php");


require_once getenv("DOCUMENT_ROOT")."/assets/conf.inc.php";
require_once getenv("DOCUMENT_ROOT")."/assets/dbCon.php";
include getenv("DOCUMENT_ROOT")."/include/session_include.php";
include_once getenv("DOCUMENT_ROOT")."/lib/erp_api.php";
include_once getenv("DOCUMENT_ROOT")."/assets/api/install.php";
include_once getenv("DOCUMENT_ROOT")."/assets/api/daily.php";

error_reporting(E_ALL);
ini_set('display_errors', '1');

date_default_timezone_set('America/Toronto');

class API extends CONF {
    use InstallAPI;
    
    protected $dailyService;
    public function __construct() {
        $this->dailyService = new DailyService();
    }
    
  public function processApi() {
    $func = $_GET['func'];

    if(isset($_POST['search_date'])) {
        $_POST['search_date'] = str_replace("-","",$_POST['search_date']);
    }
    if(isset($_POST['orderdate'])) {
        $_POST['orderdate'] = str_replace("-","",$_POST['orderdate']);
    }
    
    if(empty($func))
      $this->response('',404);

    if((int)method_exists($this,$func) > 0)
      $this->$func();
    else
      $this->response('',404);
  }

  private function json($data){
    if(is_array($data)){
      return json_encode($data);
    }
  }

  public function inqPoint(){
    try {

        $optionCondition = " AND";
        if($_POST['option']['ordered'] === "true") {
            $optionCondition .= " td.d_orderdate != ''";
        }else{
            $optionCondition .= " td.d_orderdate = ''";
        }

        $searchCondition = "";

        if(strlen($_POST['search']) > 0){
            $searchCondition .= " AND (tc.c_accountno LIKE '%".$_POST['search']."%'
                                OR tc.c_name LIKE '%".$_POST['search']."%'
                                OR tc.c_name LIKE '%".strtoupper($_POST['search'])."%'
                                OR tc.c_name LIKE '%".strtolower($_POST['search'])."%'
                                OR tc.c_phone LIKE '%".$_POST['search']."%')";
        }

        $result = array();
        $uidList = "";
        $customerUidArr = [];
				
        $sqOptionPoint = qry("SELECT
                                'flag' AS type,
                                tc.c_uid,
                                tc.c_accountno,
                                tc.c_paymentcycle,
                                tc.c_maincontainer,
                                tc.c_rate,                                
                                tc.c_name,
                                IF(tc.c_phoneext IS NULL OR LENGTH(tc.c_phoneext) < 1, tc.c_phone, CONCAT(tc.c_phone,' (ext.',tc.c_phoneext,')')) AS phone,
                                CONCAT(tc.c_address, ', ', tc.c_city, ', ', tc.c_postal) AS addr,
                                tc.c_paymenttype,
                                td.d_uid,
                                td.d_orderdate,
                                    IFNULL(td.d_quantity,0) as d_quantity,
                                    IFNULL(td.d_estquantity,0) as d_estquantity,
                                td.d_ordertype,
                                td.d_driveruid,
                                td.d_createruid,
                                td.d_status,
                                tc.c_comment_ri,
                                tc.c_location,   
                                IFNULL(DATE_FORMAT(tc.c_lastpickupdate,'%Y-%m-%d'),'') as c_lastpickupdate,
                                IFNULL(DATE_FORMAT(tc.c_lastpaiddate,'%Y-%m-%d'),'') as c_lastpaiddate,
                                IFNULL(tc.c_geolat,'') as lat,
                                IFNULL(tc.c_geolon,'') as lon,
                                td.d_ruid,
                                td.d_druid,
                                td.r_note
                            FROM
                                (SELECT
                                    c_uid,
                                    c_accountno,
                                    c_paymentcycle,
                                		c_maincontainer,
                                		c_rate,                                    
                                    c_driveruid,
                                    c_name,
                                    c_phoneext,
                                    c_phone,
                                    c_address,
                                    c_city,
                                    c_province,
                                    c_postal,
                                    c_paymenttype,
                                    c_lastpickupdate,
                                    c_lastpaiddate,
                                    c_comment_ri,
                                    c_location,
                                    c_geolat,
                                    c_geolon
                                FROM
                                    tbl_customer) tc,
                                (SELECT
                                    td.d_uid,
                                    td.d_ruid,
                                    tr.r_note,
                                    td.d_customeruid,
                                    td.d_orderdate,
                                    td.d_quantity,
                                    td.d_estquantity,
                                    td.d_ordertype,
                                    td.d_driveruid,
                                    td.d_druid,
                                	td.d_createruid,
                                    td.d_status
                                FROM
                                    tbl_daily td
                                LEFT OUTER JOIN tbl_request tr 
                                ON td.d_ruid = tr.r_uid) td
                            WHERE
                                tc.c_uid = td.d_customeruid
                                AND td.d_druid = ".(int)$_POST['driver']."
                                AND td.d_orderdate = '".$_POST['search_date']."'
                                ".$optionCondition.$searchCondition."
                            GROUP BY tc.c_uid
                            ORDER BY td.d_orderdate DESC");

        $loc_comp = array();
        while($rstOptionPoint = fetch_array($sqOptionPoint)) {
            $color = '#FF80FF';
            $orderFlag = 'DISABLED';		
            if ($rstOptionPoint['d_driveruid'] == $rstOptionPoint['d_createruid']) {
            		$color = '#FFFDD5'; // Driver 가 직접 Add Order 시
            		if ($rstOptionPoint['d_orderdate'] >= date('Ymd')) $orderFlag = '';	// Driver 가 직접 Add Order 한 경우 해당일 이후것 삭제 가능함
            }
            if($rstOptionPoint['d_status'] === 'F') {
                $color = '#7B7A7A';
            }else{
                switch($rstOptionPoint['d_ordertype']) {
                    case 'R':
                        $color = '#FF0000';
                        break;
                    case 'S':
                        $color = '#800080';
                        break;
                }
            }
            
            $crntLoc = array($rstOptionPoint['lat'],$rstOptionPoint['lon']);

            for($i=0;$i < 99;$i++) {
                if(in_array($crntLoc,$loc_comp)){
                    $crntLoc = array($rstOptionPoint['lat'],((float)$rstOptionPoint['lon']+0.0001000));
                }else{
                    break;
                }
            }                

            $loc_comp[] = $crntLoc;
            $customerUidArr[] = (int)$rstOptionPoint['c_uid'];

						$d_ordertype = $rstOptionPoint['d_ordertype'];
						if ($d_ordertype == 'S') $d_ordertype = '&#128197;';
						else if ($d_ordertype == 'R') $d_ordertype = '&#127939;';
						else $d_ordertype = '';
						
            $result[] = array(
                "type" => $rstOptionPoint['type'],
                "id" => $rstOptionPoint['c_uid'],
                "accountno" => $rstOptionPoint['c_accountno'],
                "paymentcycle" => $rstOptionPoint['c_paymentcycle'],
                "maincontainer" => $rstOptionPoint['c_maincontainer'],
                "rate" => $rstOptionPoint['c_rate'],                
                "name" => $rstOptionPoint['c_name'],
                "phone" => $rstOptionPoint['phone'],
                "address" => $rstOptionPoint['addr'],
                "payment_type" => $rstOptionPoint['c_paymenttype'],
                "order_date" => $rstOptionPoint['d_orderdate'],
                "ordertype" => $d_ordertype,
                "lat" => (string)$crntLoc[0],
                "lon" => (string)$crntLoc[1],
                "qty" => $rstOptionPoint['d_quantity'],
                "estqty" => $rstOptionPoint['d_estquantity'],
                "color" => $color,
                "comment" => $rstOptionPoint['c_comment_ri'],
                "container_location" => stripslashes($rstOptionPoint['c_location']),
                "last_pickup_date" => $rstOptionPoint['c_lastpickupdate'],
                "last_paid_date" => $rstOptionPoint['c_lastpaiddate'],
                "duid" => $rstOptionPoint['d_uid'],
                "druid" => $rstOptionPoint['d_ruid'],
                "ddruid" => $rstOptionPoint['d_druid'],
                "rnote" => $rstOptionPoint['r_note'],
                "orderFlag" => $orderFlag
            );
            if(strlen($uidList) > 0){
                $uidList .= ",".$rstOptionPoint['c_uid'];
            }else{
                $uidList .= $rstOptionPoint['c_uid'];
            }            
        }


        // 오늘 날짜
        $today = new DateTime(date("Y-m-d"));
        //$today = new DateTime('20240425');
        // 지정한 날짜
        $searchDate = new DateTime($_POST['search_date']);
        // 두 날짜 간 차이 계산
        $interval = $today->diff($searchDate);
        
			
        $qtyCondition = "";

        foreach($_POST['quantity'] as $quantity) {
            if($quantity['checked'] === "true") {
                if(strlen($qtyCondition) > 0){
                    $qtyCondition .= " OR";
                }else{
                    $qtyCondition .= " AND (";
                }
                if($quantity['max'] === 'MAX') {
                    $qtyCondition .= " (tc.realQty > ".$quantity['min'].")";
                }else{
                    $qtyCondition .= " (tc.realQty BETWEEN ".$quantity['min']." AND ".$quantity['max'].")";
                }                
            }
        }

        $sqDriverRegion = qry("SELECT
                                m_uid
                            FROM
                                tbl_member
                            WHERE
                                m_currentdriver = ".(int)$_POST['driver']);
        $rstDriverRegion = fetch_array($sqDriverRegion);
        $driverid = $rstDriverRegion['m_uid'];

            

        if(strlen($qtyCondition) > 0){
            $qtyCondition .= ")";

            if(strlen($uidList) > 0){
                $uidList = "AND tc.c_uid NOT IN (".$uidList.")";
            }
    
            $sqQtyPoint = qry("SELECT
                                    'map-marker' AS type,
                                    tc.c_uid,
		                                tc.c_accountno,
		                                tc.c_paymentcycle,
		                                tc.c_maincontainer,
		                                tc.c_rate,                                      
                                    tc.c_name,
                                    IF(tc.c_phoneext IS NULL OR LENGTH(tc.c_phoneext) < 1, tc.c_phone, CONCAT(tc.c_phone,' (ext.',tc.c_phoneext,')')) AS phone,
                                    CONCAT(tc.c_address, ', ', tc.c_city, ', ', tc.c_postal) AS addr,
                                    tc.c_paymenttype,
                                    IFNULL(tc.c_fullquantity,0),
                                    IFNULL(tc.c_fullquantitydaily,0),
                                    tc.realQty,
                                    tc.c_schedule,
                                    tc.c_comment_ri,
                                    tc.c_location,
		                                IFNULL(DATE_FORMAT(tc.c_lastpickupdate,'%Y-%m-%d'),'') as c_lastpickupdate,
                                		IFNULL(DATE_FORMAT(tc.c_lastpaiddate,'%Y-%m-%d'),'') as c_lastpaiddate,
                                    IFNULL(tc.c_geolat,'') as lat,
                                    IFNULL(tc.c_geolon,'') as lon
                                FROM
                                (SELECT
                                    c_uid,
                                    c_accountno,
                                    c_paymentcycle,
                                    c_maincontainer,
                                    c_rate,                                          
                                    c_driveruid,
                                    c_name,
                                    c_phoneext,
                                    c_phone,
                                    c_address,
                                    c_city,
                                    c_province,
                                    c_postal,
                                    c_paymenttype,
                                    c_lastpickupdate,
                                    c_lastpaiddate,
                                    c_fullquantitydaily,
                                    c_fullquantity,
                                    IFNULL((c_fullquantity - c_fullquantitydaily + (".(int)$interval->days." * c_fullquantitydaily)),0) as realQty,
                                    c_location,
                                    c_schedule,
                                    c_comment_ri,
                                    c_geolat,
                                    c_geolon
                                FROM
                                    tbl_customer
                                WHERE
                                    c_status = 'A') tc
                                WHERE
                                    tc.c_driveruid = ".(int)$driverid."
                                    ".$uidList."                                    
                                    ".$qtyCondition.$searchCondition."
                                GROUP BY tc.c_uid");

						$loc_comp = array();
            while($rstQtyPoint = fetch_array($sqQtyPoint)) {
                $realQty = $rstQtyPoint['realQty'];
                //$colorArr = array('#000000','#D32F2F','#1ABC9C','#FBC02D','#2979FF','#CDDC39'); //Something wrong on black
                $colorArr = array('#000000','#FFFF00','#FBC02D','#1ABC9C','#2979FF','#000000'); //Something wrong on black                
                $color = $colorArr[0];            
                $qtyNum = 1;
                foreach($_POST['quantity'] as $quantity) {
                    if($quantity['max'] === 'MAX') {
                        if((int)$realQty  >= (int)$quantity['min']) {
                            $color = $colorArr[$qtyNum];
                            break;
                        }
                    }else{
                        if((int)$realQty  >= (int)$quantity['min'] && (int)$realQty <= (int)$quantity['max']) {
                            $color = $colorArr[$qtyNum];
                            break;
                        }
                    }               
                    $qtyNum += 1;
                }

                $crntLoc = array($rstQtyPoint['lat'],$rstQtyPoint['lon']);

                for($i=0;$i < 99;$i++) {
                    if(in_array($crntLoc,$loc_comp)){
                        $crntLoc = array($rstQtyPoint['lat'],((float)$rstQtyPoint['lon']+0.0001000));
                    }else{
                        break;
                    }
                }                

                $loc_comp[] = $crntLoc;
                $customerUidArr[] = (int)$rstQtyPoint['c_uid'];

								$c_schedule = $rstQtyPoint['c_schedule'];
								if ($c_schedule == 'Will Call') $c_schedule = '&#128222;';
								else if ($c_schedule != 'None') $c_schedule = '&#128197;';
								else $c_schedule = '';

                $result[] = array(
                    "type" => $rstQtyPoint['type'],
                    "id" => $rstQtyPoint['c_uid'],
		                "accountno" => $rstQtyPoint['c_accountno'],
		                "paymentcycle" => $rstQtyPoint['c_paymentcycle'],
		                "maincontainer" => $rstQtyPoint['c_maincontainer'],
		                "rate" => $rstQtyPoint['c_rate'],                       
                    "name" => $rstQtyPoint['c_name'],
                    "phone" => $rstQtyPoint['phone'],
                    "address" => $rstQtyPoint['addr'],
                    "payment_type" => $rstQtyPoint['c_paymenttype'],
                    "order_date" => null,
                    "ordertype" => $c_schedule,
                    "lat" => (string)$crntLoc[0],
                    "lon" => (string)$crntLoc[1],
                    "estqty" => $realQty,
                    "color" => $color,
                    "comment" => $rstQtyPoint['c_comment_ri'],
                    "container_location" => stripslashes($rstQtyPoint['c_location']),
                    "last_pickup_date" => $rstQtyPoint['c_lastpickupdate'],
                    "last_paid_date" => $rstQtyPoint['c_lastpaiddate']
                );       
            }
        }        
        $customerUidArr = array_values(array_unique($customerUidArr));
        $containerMap = [];

        if (!empty($customerUidArr)) {
            $in = implode(',', array_map('intval', $customerUidArr));

            $sqCC = qry("
                SELECT
                    cc_customer_uid,
                    cc_type,
                    cc_owner_type,
                    cc_has_lock,
                    cc_has_wheel,
                    cc_has_woodframe
                FROM tbl_customer_container
                WHERE cc_status = 'A'
                AND cc_customer_uid IN ($in)
                ORDER BY cc_customer_uid, cc_type, cc_uid
            ");

            while ($cc = fetch_array($sqCC)) {
                $cu = (int)$cc['cc_customer_uid'];
                if (!isset($containerMap[$cu])) $containerMap[$cu] = [];
                $containerMap[$cu][] = [
                    'cc_type' => $cc['cc_type'],
                    'cc_owner_type' => $cc['cc_owner_type'],
                    'cc_has_lock' => $cc['cc_has_lock'],
                    'cc_has_wheel' => $cc['cc_has_wheel'],
                    'cc_has_woodframe' => $cc['cc_has_woodframe'],
                ];
            }
        }

        for ($i = 0; $i < count($result); $i++) {
            $cid = (int)$result[$i]['id']; // JSON에서 customer id로 쓰는 필드
            $result[$i]['containers'] = $containerMap[$cid] ?? [];
        }
    

        $this->response($this->json(array("result"=>$result)), 200);
    } catch(Exception $e) {
        $error = array($e->getMessage());
        $this->response($this->json($error), 417);
    }   
  }

  public function updtPoint(){
    try {
        qry("UPDATE tbl_customer SET c_geolat=".$_POST['lat'].", c_geolon=".$_POST['lon'].", c_is_transfer='N' WHERE c_uid=".(int)$_POST['id']);

        // ====================
        // Integration to ERP
        // ====================
        $erp = new ErpApi();

        try {
            $columns = array();
			$values = array();
            $columns[] = "c_accountno";
            $columns[] = "c_geolat";
			$columns[] = "c_geolon";
            $values[] = $_POST['accountno'];
            $values[] = $_POST['lat'];
            $values[] = $_POST['lon'];
            $lguserid = $_SESSION['ss_UID'];
            $erp->updateCustomerFromMis($columns, $values, $lguserid);

            // 성공 시 c_is_transfer='Y'
            qry("UPDATE tbl_customer SET c_is_transfer = 'Y' WHERE c_uid = ".(int)$_POST['id']);

        } catch (Exception $e) {
            // 여기서는 아무것도 안함.
        }
        
        $this->response($this->json(array("markerIndex"=>$_POST['marker_index'], "lat"=>$_POST['lat'], "lon"=>$_POST['lon'], "name"=>$_POST['name'], "qty"=>$_POST['qty'], "property"=>$_POST['property'])), 200);
    } catch(Exception $e) {
        $error = array($e->getMessage());
        $this->response($this->json($error), 417);
    }   
  }

  public function updtShortInfo(){
    try {
        qry("UPDATE tbl_customer 
        		 SET c_location='".addslashes($_POST['location'])."', 
        					c_comment_ri='".addslashes($_POST['comment'])."',
                            c_is_transfer='N' 
        		 WHERE c_uid=".(int)$_POST['id']);
        
        // ====================
        // Integration to ERP
        // ====================
        $erp = new ErpApi();

        try {
            $columns = array();
			$values = array();
            $columns[] = "c_accountno";
            $columns[] = "c_location";
			$columns[] = "c_comment_ri";
            $values[] = $_POST['accountno'];
            $values[] = addslashes($_POST['location']);
            $values[] = addslashes($_POST['comment']);
            $lguserid = $_SESSION['ss_UID'];
            $erp->updateCustomerFromMis($columns, $values, $lguserid);

            // 성공 시 c_is_transfer='Y'
            qry("UPDATE tbl_customer SET c_is_transfer = 'Y' WHERE c_uid = ".(int)$_POST['id']);

        } catch (Exception $e) {
            // 여기서는 아무것도 안함.
        }
        
        $this->response($this->json(array("result"=>"success")), 200);
    } catch(Exception $e) {
        $error = array($e->getMessage());
        $this->response($this->json($error), 417);
    }   
  }


  public function inqDriverGeo(){
        try {
            $sqDriverGeo = qry("SELECT
                                    m_geolat,
                                    m_geolon
                                FROM
                                    tbl_member
                                WHERE
                                    m_uid = ".(int)$_POST['driver']);
            $rstDriverGeo = fetch_array($sqDriverGeo);
            $result = array(
                "geolat" => $rstDriverGeo['m_geolat'],
                "geolon" => $rstDriverGeo['m_geolon']
            );
            
            $this->response($this->json(array("result"=>$result)), 200);
        } catch(Exception $e) {
            $error = array($e->getMessage());
            $this->response($this->json($error), 417);
        }     
  }


    private function getGeoCoordinates($address) {
        // Google API 키를 여기에 입력하세요.
        $apiKey = 'AIzaSyDg9u03mGrBhyOisp7VGc27CTPI9QXp8sY';

        // 주소를 URL 인코딩
        $address = urlencode($address);

        // Google Maps Geocoding API URL
        $url = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&key={$apiKey}";

        // cURL 세션 초기화
        $ch = curl_init();

        // cURL 옵션 설정
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        // URL의 내용을 가져옴
        $responseJson = curl_exec($ch);
        curl_close($ch);

        // JSON 응답을 PHP 배열로 변환
        $response = json_decode($responseJson, true);

        // 위도와 경도를 추출
        if ($response['status'] == 'OK') {
            $latitude = $response['results'][0]['geometry']['location']['lat'];
            $longitude = $response['results'][0]['geometry']['location']['lng'];

            return array('latitude' => $latitude, 'longitude' => $longitude);
        } else {
            // 에러 처리
            return false;
        }
    }

    public function inqNearby(){
        try {

            $result = array();
            $uidList = "";
            $customerUidArr = [];
						
            $sqOptionPoint = qry("SELECT
                                    'flag' AS type,
                                    tc.c_uid,
	                                tc.c_accountno,
	                                tc.c_paymentcycle,
	                                tc.c_maincontainer,
	                                tc.c_rate,                                     
                                    tc.c_name,
                                    IF(tc.c_phoneext IS NULL OR LENGTH(tc.c_phoneext) < 1, tc.c_phone, CONCAT(tc.c_phone,' (ext.',tc.c_phoneext,')')) AS phone,
                                    CONCAT(tc.c_address, ', ', tc.c_city, ', ', tc.c_postal) AS addr,
                                    tc.c_paymenttype,
                                    td.d_orderdate,
                                    IFNULL(td.d_quantity,0) as d_quantity,
                                    IFNULL(td.d_estquantity,0) as d_estquantity,
                                    td.d_ordertype,
                                  td.d_uid,
                                  td.d_druid,
	                                td.d_driveruid,
	                                td.d_createruid,                                    
                                    td.d_status,
                                    tc.c_comment_ri,
                                    tc.c_location,   
                                IFNULL(DATE_FORMAT(tc.c_lastpickupdate,'%Y-%m-%d'),'') as c_lastpickupdate,
                                IFNULL(DATE_FORMAT(tc.c_lastpaiddate,'%Y-%m-%d'),'') as c_lastpaiddate,                                    
                                    IFNULL(tc.c_geolat,'') as lat,
                                    IFNULL(tc.c_geolon,'') as lon,
                                    (
                                        ST_Distance_Sphere(
                                            point(".(float)$_POST['center_lon'].", ".(float)$_POST['center_lat']."),
                                            point(tc.c_geolon, tc.c_geolat)
                                        )
                                    ) / 1000 AS distance_km,
                                    td.r_note
                                FROM
                                     (SELECT
                                        c_uid,
		                                    c_accountno,
		                                    c_paymentcycle,
		                                		c_maincontainer,
		                                		c_rate,                                                        
                                        c_driveruid,
                                        c_name,
                                        c_phoneext,
                                        c_phone,
                                        c_address,
                                        c_city,
                                        c_province,
                                        c_postal,
                                        c_paymenttype,
                                        c_lastpickupdate,
                                        c_lastpaiddate,
                                        c_location,
                                        c_comment_ri,
                                        c_geolat,
                                        c_geolon
                                    FROM
                                        tbl_customer) tc,
                                    (SELECT
                                        td.d_uid,
                                        td.d_customeruid,
                                        td.d_orderdate,
                                        td.d_quantity,
                                        td.d_estquantity,
                                        td.d_ordertype,
                                        td.d_driveruid,
                                        td.d_ruid,
                                        td.d_druid,
                                        td.d_createruid,
                                        td.d_status,
                                        tr.r_note
                                    FROM
                                        tbl_daily td
                                    LEFT OUTER JOIN tbl_request tr ON td.d_ruid = tr.r_uid) td
                                WHERE
                                    tc.c_uid = td.d_customeruid

                                    AND td.d_druid = ".(int)$_POST['driver']."
                                    AND td.d_orderdate = '".$_POST['search_date']."'
                              
                                GROUP BY tc.c_uid
                                /* HAVING distance_km <= 1 */
                                ORDER BY td.d_orderdate DESC");

           $loc_comp = array(); 
            while($rstOptionPoint = fetch_array($sqOptionPoint)) {
		            $color = '#FF80FF';
		            $orderFlag = 'DISABLED';
		            $d_ordertype = '';
		            if ($rstOptionPoint['d_driveruid'] == $rstOptionPoint['d_createruid']) {
		            		$color = '#FFFDD5'; // Driver 가 직접 Add Order 시
		            		if ($rstOptionPoint['d_orderdate'] >= date('Ymd')) $orderFlag = '';		// Driver 가 직접 Add Order 한 경우 해당일 이후것 삭제 가능함
		            }
		            if($rstOptionPoint['d_status'] === 'F') {
		                $color = '#7B7A7A';
		                $d_ordertype = '';
		            }else{
		                switch($rstOptionPoint['d_ordertype']) {
		                    case 'R':
		                        $color = '#FF0000';
		                        $d_ordertype = '&#127939;';
		                        break;
		                    case 'S':
		                        $color = '#800080';
		                        $d_ordertype = '&#128197;';
		                        break;
		                }
		            }

                $crntLoc = array($rstOptionPoint['lat'],$rstOptionPoint['lon']);
                $customerUidArr[] = (int)$rstOptionPoint['c_uid'];

                for($i=0;$i < 99;$i++) {
                    if(in_array($crntLoc,$loc_comp)){
                        $crntLoc = array($rstOptionPoint['lat'],((float)$rstOptionPoint['lon']+0.0001000));
                    }else{
                        break;
                    }
                }                

                $loc_comp[] = $crntLoc;
       
                $result[] = array(
                    "type" => $rstOptionPoint['type'],
                    "id" => $rstOptionPoint['c_uid'],
                "accountno" => $rstOptionPoint['c_accountno'],
                "paymentcycle" => $rstOptionPoint['c_paymentcycle'],
                "maincontainer" => $rstOptionPoint['c_maincontainer'],
                "rate" => $rstOptionPoint['c_rate'],                       
                    "name" => $rstOptionPoint['c_name'],
                    "phone" => $rstOptionPoint['phone'],
                    "address" => $rstOptionPoint['addr'],
                    "payment_type" => $rstOptionPoint['c_paymenttype'],
                    "order_date" => $rstOptionPoint['d_orderdate'],
                    "ordertype" => $d_ordertype,
                    "lat" => (string)$crntLoc[0],
                    "lon" => (string)$crntLoc[1],
                    "qty" => $rstOptionPoint['d_quantity'],
                    "estqty" => $rstOptionPoint['d_estquantity'],
                    "color" => $color,
                    "comment" => $rstOptionPoint['c_comment_ri'],
                    "container_location" => stripslashes($rstOptionPoint['c_location']),
                    "last_pickup_date" => $rstOptionPoint['c_lastpickupdate'],
                "last_paid_date" => $rstOptionPoint['c_lastpaiddate'],
                "duid" => $rstOptionPoint['d_uid'],
                "druid" => $rstOptionPoint['d_druid'],
                "rnote" => $rstOptionPoint['r_note'],
                "orderFlag" => $orderFlag
                );
                if(strlen($uidList) > 0){
                    $uidList .= ",".$rstOptionPoint['c_uid'];
                }else{
                    $uidList .= $rstOptionPoint['c_uid'];
                }            
            }


            // 오늘 날짜
            $today = new DateTime(date("Y-m-d"));
            //$today = new DateTime('20240425');
            // 지정한 날짜
            $searchDate = new DateTime($_POST['search_date']);
            // 두 날짜 간 차이 계산
            $interval = $today->diff($searchDate);
						
            $qtyCondition = "";

            foreach($_POST['quantity'] as $quantity) {
                if($quantity['checked'] === "true") {
                    if(strlen($qtyCondition) > 0){
                        $qtyCondition .= " OR";
                    }else{
                        $qtyCondition .= " AND (";
                    }
                    if($quantity['max'] === 'MAX') {
                        $qtyCondition .= " (tc.realQty > ".$quantity['min'].")";
                    }else{
                        $qtyCondition .= " (tc.realQty BETWEEN ".$quantity['min']." AND ".$quantity['max'].")";
                    }               
                }
            }

		        $sqDriverRegion = qry("SELECT
		                                m_uid
		                            FROM
		                                tbl_member
		                            WHERE
		                                m_currentdriver = ".(int)$_POST['driver']);
		        $rstDriverRegion = fetch_array($sqDriverRegion);
		        $driverid = $rstDriverRegion['m_uid'];
        
        
            if(strlen($qtyCondition) > 0){
                $qtyCondition .= ")";

                if(strlen($uidList) > 0){
                    $uidList = "AND tc.c_uid NOT IN (".$uidList.")";
                }
    
                $sqQtyPoint = qry("SELECT
                                        'map-marker' AS type,
                                        tc.c_uid,
		                                tc.c_accountno,
		                                tc.c_paymentcycle,
		                                tc.c_maincontainer,
		                                tc.c_rate,                                              
                                        tc.c_name,
                                        IF(tc.c_phoneext IS NULL OR LENGTH(tc.c_phoneext) < 1, tc.c_phone, CONCAT(tc.c_phone,' (ext.',tc.c_phoneext,')')) AS phone,
                                        CONCAT(tc.c_address, ', ', tc.c_city, ', ', tc.c_postal) AS addr,
                                        tc.c_paymenttype,
                                        IFNULL(tc.c_fullquantity,0),
                                        IFNULL(tc.c_fullquantitydaily,0),
                                        tc.realQty,                                        
                                        tc.c_comment_ri,
                                        tc.c_location,
                                        tc.c_schedule,
		                                IFNULL(DATE_FORMAT(tc.c_lastpickupdate,'%Y-%m-%d'),'') as c_lastpickupdate,
                                		IFNULL(DATE_FORMAT(tc.c_lastpaiddate,'%Y-%m-%d'),'') as c_lastpaiddate,
                                        IFNULL(tc.c_geolat,'') as lat,
                                        IFNULL(tc.c_geolon,'') as lon,
                                        (
                                            ST_Distance_Sphere(
                                                point(".(float)$_POST['center_lon'].", ".(float)$_POST['center_lat']."),
                                                point(tc.c_geolon, tc.c_geolat)
                                            )
                                        ) / 1000 AS distance_km
                                    FROM
                                        (SELECT
                                            c_uid,
				                                    c_accountno,
				                                    c_paymentcycle,
				                                    c_maincontainer,
				                                    c_rate,                                              
                                            c_driveruid,
                                            c_name,
                                            c_phoneext,
                                            c_phone,
                                            c_address,
                                            c_city,
                                            c_province,
                                            c_postal,
                                            c_paymenttype,
                                            c_lastpickupdate,
                                    				c_lastpaiddate,                                            
                                            c_fullquantitydaily,
                                            c_fullquantity,
                                            IFNULL((c_fullquantity - c_fullquantitydaily + (".(int)$interval->days." * c_fullquantitydaily)),0) as realQty,
                                            c_location,
                                            c_schedule,
                                            c_comment_ri,
                                            c_geolat,
                                            c_geolon
                                        FROM
                                            tbl_customer
                                        WHERE
                                            c_status = 'A') tc
                                    WHERE
                                        tc.c_driveruid = ".(int)$driverid."
                                        ".$uidList."
                                        ".$qtyCondition."                                
                                    GROUP BY tc.c_uid
                                    HAVING distance_km <= 1");
    
                $loc_comp = array();
                while($rstQtyPoint = fetch_array($sqQtyPoint)) {
                    //$realQty = $rstQtyPoint['c_fullquantity'] - $rstQtyPoint['c_fullquantitydaily'] + ((int)$interval->days * $rstQtyPoint['c_fullquantitydaily']);
                    $realQty = $rstQtyPoint['realQty'];
                    //$colorArr = array('#000000','#D32F2F','#1ABC9C','#FBC02D','#2979FF','#CDDC39'); //Something wrong on black
                    $colorArr = array('#000000','#FFFF00','#FBC02D','#1ABC9C','#2979FF','#000000'); //Something wrong on black       
                    $color = $colorArr[0];            
                    $qtyNum = 1;
                    foreach($_POST['quantity'] as $quantity) {
                        if($quantity['max'] === 'MAX') {
                            if((int)$realQty  >= (int)$quantity['min']) {
                                $color = $colorArr[$qtyNum];
                                break;
                            }
                        }else{
                            if((int)$realQty  >= (int)$quantity['min'] && (int)$realQty <= (int)$quantity['max']) {
                                $color = $colorArr[$qtyNum];
                                break;
                            }
                        }               
                        $qtyNum += 1;
                    }

                    $crntLoc = array($rstQtyPoint['lat'],$rstQtyPoint['lon']);
                    $customerUidArr[] = (int)$rstQtyPoint['c_uid'];

                    for($i=0;$i < 99;$i++) {
                        if(in_array($crntLoc,$loc_comp)){
                            $crntLoc = array($rstQtyPoint['lat'],((float)$rstQtyPoint['lon']+0.0001000));
                        }else{
                            break;
                        }
                    }                

                    $loc_comp[] = $crntLoc;

										$c_schedule = $rstQtyPoint['c_schedule'];
										if ($c_schedule == 'Will Call') $c_schedule = '&#128222;';
										else if ($c_schedule != 'None') $c_schedule = '&#128197;';
										else $c_schedule = '';
								
                    $result[] = array(
                        "type" => $rstQtyPoint['type'],
                        "id" => $rstQtyPoint['c_uid'],
				                "accountno" => $rstQtyPoint['c_accountno'],
				                "paymentcycle" => $rstQtyPoint['c_paymentcycle'],
				                "maincontainer" => $rstQtyPoint['c_maincontainer'],
				                "rate" => $rstQtyPoint['c_rate'],                           
                        "name" => $rstQtyPoint['c_name'],
                        "phone" => $rstQtyPoint['phone'],
                        "address" => $rstQtyPoint['addr'],
                        "payment_type" => $rstQtyPoint['c_paymenttype'],
                        "order_date" => null,
                        "ordertype" => $c_schedule,
		                    "lat" => (string)$crntLoc[0],
		                    "lon" => (string)$crntLoc[1],
                        "estqty" => $realQty,
                        "color" => $color,
                        "comment" => $rstQtyPoint['c_comment_ri'],
                        "container_location" => stripslashes($rstQtyPoint['c_location']),
                        "last_pickup_date" => $rstQtyPoint['c_lastpickupdate'],
                    		"last_paid_date" => $rstQtyPoint['c_lastpaiddate']                        
                    );       
                }
            }

            $customerUidArr = array_values(array_unique($customerUidArr));
            $containerMap = [];

            if (!empty($customerUidArr)) {
                $in = implode(',', array_map('intval', $customerUidArr));

                $sqCC = qry("
                    SELECT
                        cc_customer_uid,
                        cc_type,
                        cc_owner_type,
                        cc_has_lock,
                        cc_has_wheel,
                        cc_has_woodframe
                    FROM tbl_customer_container
                    WHERE cc_status = 'A'
                    AND cc_customer_uid IN ($in)
                    ORDER BY cc_customer_uid, cc_type, cc_uid
                ");

                while ($cc = fetch_array($sqCC)) {
                    $cu = (int)$cc['cc_customer_uid'];
                    if (!isset($containerMap[$cu])) $containerMap[$cu] = [];
                    $containerMap[$cu][] = [
                        'cc_type' => $cc['cc_type'],
                        'cc_owner_type' => $cc['cc_owner_type'],
                        'cc_has_lock' => $cc['cc_has_lock'],
                        'cc_has_wheel' => $cc['cc_has_wheel'],
                        'cc_has_woodframe' => $cc['cc_has_woodframe'],
                    ];
                }
            }
            
            for ($i = 0; $i < count($result); $i++) {
                $cid = (int)$result[$i]['id']; // JSON에서 customer id로 쓰는 필드
                $result[$i]['containers'] = $containerMap[$cid] ?? [];
            }    
            $this->response($this->json(array("result"=>$result)), 200);
        } catch(Exception $e) {
            $error = array($e->getMessage());
            $this->response($this->json($error), 417);
        }   
      }

      
      public function inqHistory(){
        try {
            $sqHistory = qry("SELECT
                                    IFNULL(DATE_FORMAT(td.d_orderdate,'%Y-%m-%d'),'') as d_orderdate,
                                    td.d_quantity,
                                    td.d_driveruid,
                                    td.d_paystatus,
                                    IFNULL(td.d_drinitial,'-') as d_drinitial,
                                    IFNULL(td.d_payamount,'') as d_payamount,
                                    tm.m_initial
                                FROM
                                    tbl_daily td,tbl_member tm
                                WHERE
                                    td.d_customeruid = '".$_POST['id']."'
                                    AND td.d_status = 'F'
                                    AND td.d_driveruid = tm.m_uid
                                ORDER BY td.d_orderdate DESC");
            $result = array();
            while($rstHistory = fetch_array($sqHistory)) {

								if($rstHistory['d_paystatus'] === 'P') {
										//$d_paystatusSTR = $arrPaidStatus['P'];
										$d_paystatusSTR = "Paid". " ($".$rstHistory['d_payamount'] . ")";
								}
								else if ($rstHistory['d_paystatus'] === 'N') {
										$d_paystatusSTR = "Unpaid";
                                }
                                else if ($rstHistory['d_paystatus'] === 'G') {
										$d_paystatusSTR = "Paid (Grease Trap)";
								}
								else $d_paystatusSTR = "";

            	
                $result[] = array(
                    "date" => $rstHistory['d_orderdate'],
                    "quantity" => $rstHistory['d_quantity'],
                    "driver" => $rstHistory['d_drinitial'],
                    "paid" => $d_paystatusSTR
                );
            }
            
            $this->response($this->json(array("result"=>$result)), 200);
        } catch(Exception $e) {
            $error = array($e->getMessage());
            $this->response($this->json($error), 417);
        }   
      }


      public function inqShortNotice(){ 
        try {
            $sqNotice = qry("SELECT
                                    IFNULL(DATE_FORMAT(td.d_orderdate,'%Y-%m-%d'),'') as d_orderdate,
                                    tr.r_note
                                FROM
                                    tbl_daily td,tbl_request tr
                                WHERE
                                    td.d_uid = '".$_POST['id']."'
                                    AND td.d_ruid = tr.r_uid
                                ORDER BY td.d_uid DESC LIMIT 1 ");
                                
            $rstNotice = fetch_array($sqNotice);
            
            $result = array(
                "orderdate" => $rstNotice['d_orderdate'],
                "rnote" => $rstNotice['r_note']
            );

            $this->response($this->json(array("result"=>$result)), 200);
        } catch(Exception $e) {
            $error = array($e->getMessage());
            $this->response($this->json($error), 417);
        }   
      }
      

      public function inqRouteAddress(){
        try {

            $myLocation = ["lat" => (float)$_POST['m_lat'], "lon" => (float)$_POST['m_lon']];
            $apiKey = "AIzaSyDg9u03mGrBhyOisp7VGc27CTPI9QXp8sY"; // Google Maps API 키

            $getThisYear = date("Y");
            $getLastYear = date("Y", strtotime('last year'));

						$_POST['route_date'] = str_replace("-","",$_POST['route_date']);
						
            $sqAddress = qry("SELECT
                                    tc.c_uid,
                                    tc.c_name,
                                    tc.c_address,
                                    tc.c_city,
                                    tc.c_postal,
                                    td.d_accountno,
                                    td.d_maincontainer,
                                    td.d_paymenttype,
                                    td.d_rate,
                                    td.d_lastpickupquantity,
                                    td.d_estquantity,
                                    IFNULL(td.d_quantity, '') as d_quantity,
                                    td.d_lastpaiddate,
                                    s.THIS_YEAR,
                                    s.LAST_YEAR,
                                    td.d_fullcycle,
                                    td.d_lastpickupdate,
                                    IFNULL(tc.c_geolat,'') as lat,
                                    IFNULL(tc.c_geolon,'') as lon
                                FROM
                                    tbl_customer tc,
                                    tbl_daily td
                                        LEFT JOIN (SELECT
                                            d_customeruid,
                                            SUM(CASE WHEN d_visitdate like '".$getThisYear."%' THEN d_quantity ELSE 0 END) AS THIS_YEAR,
                                            SUM(CASE WHEN d_visitdate like '".$getLastYear."%' THEN d_quantity ELSE 0 END) AS LAST_YEAR
                                        FROM  tbl_daily
                                        WHERE d_status = 'F'
                                        GROUP BY d_customeruid) s ON s.d_customeruid = td.d_customeruid
                                WHERE
                                    tc.c_uid = td.d_customeruid
                                    AND td.d_druid = '".$_POST['driver']."'
                                    AND td.d_orderdate = '".$_POST['route_date']."'");
            $results = array();
            while($rstAddress = fetch_array($sqAddress)) {
                if (strlen($rstAddress['lat']) < 1 || strlen($rstAddress['lon']) < 1) {
                    // 주소로부터 위도와 경도 찾기 (예제에서는 이름 필드를 주소로 가정)
                    $address = urlencode($rstAddress['address']);
                    $url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=$apiKey";
            
                    $response = file_get_contents($url);
                    $json = json_decode($response, true);
            
                    if (!empty($json['results'])) {
                        $rstAddress["lat"] = $json['results'][0]['geometry']['location']['lat'];
                        $rstAddress["lon"] = $json['results'][0]['geometry']['location']['lng'];
                    }
                }

                $results[] = array(
                    "id" => $rstAddress['c_uid'],
                    "name" => $rstAddress['c_name'],
                    "address" => str_replace("/", "&#47;", $rstAddress['c_address']),
                    "city" => $rstAddress['c_city'],
                    "postal" => $rstAddress['c_postal'],
                    "accountno" => $rstAddress['d_accountno'],
                    "maincontainer" => $rstAddress['d_maincontainer'],
                    "paymenttype" => $rstAddress['d_paymenttype'],
                    "rate" => $rstAddress['d_rate'],
                    "lastpickupquantity" => $rstAddress['d_lastpickupquantity'],
                    "estquantity" => $rstAddress['d_estquantity'],
                    "quantity" => $rstAddress['d_quantity'],
                    "lastpaiddate" => $rstAddress['d_lastpaiddate'],
                    "THIS_YEAR" => (float)$rstAddress['THIS_YEAR'],
                    "LAST_YEAR" => (float)$rstAddress['LAST_YEAR'],
                    "fullcycle" => $rstAddress['d_fullcycle'],
                    "lastpickupdate" => $rstAddress['d_lastpickupdate'],
                    "lat" => (float)$rstAddress['lat'],
                    "lon" => (float)$rstAddress['lon']
                );
            }

            usort($results, function($a, $b) use ($myLocation) {
                $distA = sqrt(pow($a["lat"] - $myLocation["lat"], 2) + pow($a["lon"] - $myLocation["lon"], 2));
                $distB = sqrt(pow($b["lat"] - $myLocation["lat"], 2) + pow($b["lon"] - $myLocation["lon"], 2));
                return $distA <=> $distB;
            });
            
            $this->response($this->json(array("result"=>$results)), 200);
        } catch(Exception $e) {
            $error = array($e->getMessage());
            $this->response($this->json($error), 417);
        }   
      }      

      public function inqShortInfo(){
  	
        try {
            $sqShortInfo = qry("SELECT
                                    c_uid,
                                    c_accountno,
                                    c_name,
                                    c_paymenttype,
                                    c_comment_ri,
                                    c_location
                                FROM
                                    tbl_customer
                                WHERE
                                    c_uid = ".(int)$_POST['id']);
            $rstShortInfo = fetch_array($sqShortInfo);

            // 설치 이미지 조회 추가
            $query_img = "
                SELECT i_filepath, i_filename 
                FROM tbl_customer_image
                WHERE i_customeruid = '".(int)$_POST['id']."'
                AND i_type = 'install'
                AND i_status = 'A'
                ORDER BY i_createddate DESC
                LIMIT 1
            ";
            $imgRow = qry($query_img);
            $installImgUrl = "";

            if ($row = fetch_array($imgRow)) {
                $installImgUrl = $row['i_filepath'] . $row['i_filename'];
            }

						if ($rstShortInfo['c_paymenttype'] == "CA") {

								$sqShortDaily = qry("SELECT 
																				IFNULL(DATE_FORMAT(td.d_orderdate,'%Y-%m-%d'),'') as d_orderdate,
		                                    td.d_paystatus,
		                                    td.d_payamount						
																		FROM tbl_daily td 
																		WHERE
																				td.d_customeruid = '".$_POST['id']."'
		                                		AND td.d_status = 'F' 
		                                		AND td.d_quantity > 1 
		                                ORDER BY td.d_visitdate DESC LIMIT 1 ");
								if(db_num_rows($sqShortDaily) > 0) {
										$rstShortDaily = fetch_array($sqShortDaily);

										if($rstShortDaily['d_paystatus'] === 'P') {
												//$d_paystatusSTR = $arrPaidStatus['P'];
												$d_paystatusSTR = "Paid". " (".$rstShortDaily['d_orderdate']." / $".$rstShortDaily['d_payamount'] . ")";
										}
										else if ($rstShortDaily['d_paystatus'] === 'N') {
												$d_paystatusSTR = "Unpaid" ." (".$rstShortDaily['d_orderdate'].")";
										}   

		            } else {
		            		$d_paystatusSTR = "";
		            }

            }
            else $d_paystatusSTR = "";
            
            $result = array(
                "id" => $_POST['id'],
                "accountno" => $rstShortInfo['c_accountno'],
                "name" => $rstShortInfo['c_name'],
                "payment_type" => $rstShortInfo['c_paymenttype'],
                "paymentstring" => $d_paystatusSTR,
                "comment" => $rstShortInfo['c_comment_ri'],
                "location" => $rstShortInfo['c_location'],
                "install_img" => $installImgUrl
            );
            
            $this->response($this->json(array("result"=>$result)), 200);
        } catch(Exception $e) {
            $error = array($e->getMessage());
            $this->response($this->json($error), 417);
        }   
      }

    public function addOrder()
    {
        try {

            $customer_uid = (int)$_POST['customer_uid'];
            $orderdate    = preg_replace('/[^0-9]/', '', $_POST['orderdate'] ?? '');
            $ordertype    = trim($_POST['ordertype'] ?? 'N');
            $ruid         = trim($_POST['ruid'] ?? '');
            $driveruid    = (int)$_POST['driveruid'];

            if ($customer_uid <= 0) {
                throw new Exception("invalid customer_uid");
            }

            if (strlen($orderdate) !== 8) {
                throw new Exception("invalid orderdate");
            }

            // =========================
            // customer 조회
            // =========================
            $sqCus = qry("
                SELECT c_accountno, c_driveruid
                FROM tbl_customer
                WHERE c_uid = {$customer_uid}
                LIMIT 1
            ");

            $customer = fetch_array($sqCus);

            if (!$customer) {
                throw new Exception("Customer not found");
            }

            $now14 = date("YmdHis");

            // =========================
            // payload 구성
            // =========================
            $payload = [
                'd_customeruid' => $customer_uid,
                'd_accountno'   => $customer['c_accountno'],
                'd_orderdate'   => $orderdate,
                'd_ordertype'   => $ordertype,
                'd_ruid'        => $ruid,
                'd_driveruid'   => $customer['c_driveruid'], // legacy
                'd_druid'       => $driveruid,               // 실제 driver
                'd_status'      => 'A',
                'd_createruid'  => $_SESSION['ss_UID'] ?? '',
                'd_createddate' => $now14,
                'n_level'       => $_SESSION['ss_LEVEL'],
            ];

            // =========================
            // saveDaily 호출
            // =========================
            $afterData = $this->dailyService->saveDaily($payload);

            // =========================
            // response
            // =========================
            $this->response($this->json([
                "msg" => "Order has been successfully added.",
                "c_index" => $_POST['c_index'],
                "d_uid" => $afterData['d_uid'] ?? null
            ]), 200);

        } catch (Exception $e) {
            $error = array($e->getMessage());
            $this->response($this->json($error), 417);
        }
    }

    public function addOrderDirect()
    {
        try {

            $customer_uid = (int)$_POST['customer_uid'];
            $orderdate = preg_replace('/[^0-9]/', '', $_POST['orderdate'] ?? '');
            $driveruid = (int)$_POST['driveruid'];
            $creatoruid = trim($_POST['d_createruid'] ?? '');
            $jobtype = $_POST['jobtype'] ?? 'UCO';

            if ($customer_uid <= 0) {
                throw new Exception("invalid customer_uid");
            }

            if (strlen($orderdate) !== 8) {
                throw new Exception("invalid orderdate");
            }

            // =========================
            // 중복 체크
            // =========================
            $sqCheckOrder = qry("
                SELECT count(d_uid) as rowcnt
                FROM tbl_daily 
                WHERE d_orderdate='{$orderdate}' 
                    AND d_customeruid={$customer_uid}
                    AND d_jobtype = 'UCO'
            ");
            $rstCheckOrder = fetch_array($sqCheckOrder);

            if ($rstCheckOrder['rowcnt'] > 0) {
                $this->response($this->json([
                    "msg"=>"This order already exists.",
                    "c_index"=>$_POST['c_index'],
                    "c_return"=>"0"
                ]), 200);
                return;
            }

            // =========================
            // 최소 customer 정보만 조회
            // =========================
            $sqCus = qry("
                SELECT c_accountno, c_driveruid
                FROM tbl_customer 
                WHERE c_uid = {$customer_uid}
                LIMIT 1
            ");
            if (db_num_rows($sqCus) === 0) {
                throw new Exception("Customer not found");
            }
            $customer = fetch_array($sqCus);

            $now14 = date("YmdHis");

            // =========================
            // PAYLOAD
            // =========================
            $payload = [
                'd_customeruid' => $customer_uid,
                'd_accountno'   => $customer['c_accountno'],
                'd_orderdate'   => $orderdate,
                'd_driveruid'   => $customer['c_driveruid'], // legacy 유지
                'd_druid'       => $driveruid,               // 실제 driver
                'd_status'      => 'A',
                'd_ordertype'   => 'N',
                'd_jobtype'     => 'UCO',
                'd_createruid'  => $creatoruid,
                'd_createddate' => $now14,
                'n_level'       => $_SESSION['ss_LEVEL'],
            ];

            // =========================
            // SAVE (모든 로직은 daily.php)
            // =========================
            $afterData = $this->dailyService->saveDaily($payload);

            // =========================
            // RESPONSE
            // =========================
            $this->response($this->json([
                "msg"=>"Order has been successfully added.",
                "c_index"=>$_POST['c_index'],
                "c_return"=>1,
                "d_uid"=>$afterData['d_uid'] ?? null
            ]), 200);

            return;

        } catch(Exception $e) {
            $error = [$e->getMessage()];
            $this->response($this->json($error), 417);
        }
    }
      
    public function removeOrder()
    {
        try {

            $duid       = (int)($_POST['duid'] ?? 0);
            $customerId = (int)($_POST['id'] ?? 0);

            if ($duid <= 0) {
                throw new Exception("invalid duid");
            }

            // =========================
            // 기존 daily 조회 (삭제용 key 확보)
            // =========================
            $sqDaily = qry("
                SELECT d_orderdate, d_accountno, d_jobtype
                FROM tbl_daily
                WHERE d_uid = '{$duid}'
                LIMIT 1
            ");

            $daily = fetch_array($sqDaily);

            if (!$daily) {
                throw new Exception("Daily record not found");
            }

            // =========================
            // DELETE (중앙화)
            // =========================
            $this->dailyService->deleteDaily(
                $daily['d_orderdate'],
                $daily['d_accountno'],
                $daily['d_jobtype']
            );

            // =========================
            // RESPONSE
            // =========================
            $this->response($this->json([
                "msg" => "Order has been successfully removed.",
                "c_index" => $_POST['c_index']
            ]), 200);

        } catch(Exception $e) {
            $error = [$e->getMessage()];
            $this->response($this->json($error), 417);
        }
    }

      public function initInput(){
        try {
            $sqInput = qry("SELECT
                                td.d_uid,
                                td.d_customeruid,
                                td.d_orderdate,
                                td.d_ordertype,
                                td.d_jobtype,
                                td.d_driveruid,
                                td.d_druid,
                                td.d_ruid,
                                td.d_visitdate,
                                td.d_quantity,
                                td.d_payamount,
                                td.d_paystatus,
                                td.d_payeename,
                                td.d_payeesign,
                                td.d_sludge,
                                td.d_rate,
                                tc.c_sludge,
                                tc.c_paymenttype,
                                tc.c_name
                            FROM
                                tbl_daily td,
                                tbl_customer tc
                            WHERE
                                td.d_customeruid = tc.c_uid
                                AND td.d_customeruid='".$_POST['c_uid']."'
                                AND td.d_orderdate='".$_POST['orderdate']."'"
                            );           
                            
            $result = array();
            if(db_num_rows($sqInput) > 0) {
                $rstInput = fetch_array($sqInput);
                
								// 이미 존재하는 오더장을 수정한다면 Note 정보도 가져와야 함
								$sqNoteInput = qry("SELECT n_note FROM tbl_note WHERE n_dailyuid = '".$rstInput['d_uid']."' ");
								if(db_num_rows($sqNoteInput) > 0) {
										$rstNoteInput = fetch_array($sqNoteInput);
										$noteSTR = $rstNoteInput['n_note'];
		            } else 
		              	$noteSTR = "";
		              
                $result = array(
                    "d_uid" => $rstInput['d_uid'],
                    "d_customeruid" => $rstInput['d_customeruid'],
                    "d_orderdate" => $rstInput['d_orderdate'],
                    "d_jobtype" => $rstInput['d_jobtype'],
                    "d_driveruid" => $rstInput['d_driveruid'],
                    "d_druid" => $rstInput['d_druid'],
                    "d_visitdate" => $rstInput['d_visitdate'],
                    "d_quantity" => $rstInput['d_quantity'],
                    "d_payamount" => $rstInput['d_payamount'],
                    "d_paystatus" => $rstInput['d_paystatus'],
                    "d_payeename" => $rstInput['d_payeename'],
                    "d_payeesign" => $rstInput['d_payeesign'],
                    "d_sludge" => ($rstInput['d_sludge'] === null || $rstInput['d_sludge'] === '') ? $rstInput['c_sludge'] : $rstInput['d_sludge'],
                    "d_paymenttype" => $rstInput['c_paymenttype'],
                    "d_name" => $rstInput['c_name'],
                    "d_rate" => $rstInput['d_rate'],
                    "d_note" => $noteSTR
                );
            }
            else {	// tbl_daily data 없는 경우 처리
	            	$sqInput = qry("SELECT
	                                c_driveruid,
	                                c_sludge,
	                                c_paymenttype,
	                                c_rate,
	                                c_name
	                            FROM
	                                tbl_customer
	                            WHERE
	                                c_uid='".$_POST['c_uid']."'");    
                
                $rstInput = fetch_array($sqInput);               

				        $sqDriverInfo = qry("SELECT
				                                m_currentdriver
				                            FROM
				                                tbl_member
				                            WHERE
				                                m_uid = ".$rstInput['c_driveruid']);
				        $rstDriverInfo = fetch_array($sqDriverInfo);
        
                                     	
                $result = array(
                    "d_uid" => '',
                    "d_customeruid" => $_POST['c_uid'],
                    "d_orderdate" => $_POST['orderdate'],
                    "d_driveruid" => $rstInput['c_driveruid'],
                    "d_druid" => $rstDriverInfo['m_currentdriver'],
                    "d_visitdate" => $_POST['orderdate'],
                    "d_sludge" => $rstInput['c_sludge'],
                    "d_paymenttype" => $rstInput['c_paymenttype'],
                    "d_name" => $rstInput['c_name'],
                    "d_rate" => $rstInput['c_rate']
                );
            }
            
            $this->response($this->json(array("result"=>$result)), 200);
        } catch(Exception $e) {
            $error = array($e->getMessage());
            $this->response($this->json($error), 417);
        }   
    }

    public function saveInput()
    {
        try {

            $connect = $GLOBALS['conn'] ?? null;
            if (!$connect) {
                throw new Exception("DB connection not found");
            }

            // =========================
            // INPUT
            // =========================
            $uid         = (int)($_POST['uid'] ?? 0);
            $customerUid = (int)($_POST['customeruid'] ?? 0);
            $driverUid   = (int)($_POST['driveruid'] ?? 0);   // member uid (legacy)
            $druid       = (int)($_POST['druid'] ?? 0);       // driver uid (new)
            $creatorUid  = trim($_POST['createruid'] ?? '');

            $orderdate   = preg_replace('/[^0-9]/', '', $_POST['orderdate'] ?? '');
            $visitdate   = preg_replace('/[^0-9]/', '', $_POST['visitdate'] ?? '');
            $jobtype     = $_POST['jobtype'] ?? 'UCO';

            $quantity    = (int)($_POST['quantity'] ?? 0);
            $sludge      = trim($_POST['sludge'] ?? '');
            $paymenttype = trim($_POST['paymenttype'] ?? '');
            $payamount   = trim($_POST['payamount'] ?? '');
            $payeename   = trim($_POST['payeename'] ?? '');
            $paystatus   = trim($_POST['paystatus'] ?? '');
            $note        = trim($_POST['note'] ?? '');

            // =========================
            // VALIDATION
            // =========================
            if ($customerUid <= 0) {
                throw new Exception("invalid customeruid");
            }

            if ($visitdate === '' || strlen($visitdate) !== 8) {
                throw new Exception("invalid visitdate");
            }

            if ($orderdate === '' || strlen($orderdate) !== 8) {
                throw new Exception("invalid orderdate");
            }

            $paystatusSTR = ($paymenttype === 'CA') ? $paystatus : '';

            // =========================
            // CUSTOMER LOAD (최소 정보만)
            // =========================
            $sqCus = qry("
                SELECT
                    c_uid,
                    c_accountno
                FROM tbl_customer
                WHERE c_uid = '{$customerUid}'
                LIMIT 1
            ");
            $customer = fetch_array($sqCus);

            if (!$customer || empty($customer['c_accountno'])) {
                throw new Exception("Customer not found");
            }

            // =========================
            // EXISTING DAILY (for update)
            // =========================
            $existing = null;

            if ($uid > 0) {
                $sqDaily = qry("
                    SELECT *
                    FROM tbl_daily
                    WHERE d_uid = '{$uid}'
                    LIMIT 1
                ");
                $existing = fetch_array($sqDaily);

                if (!$existing) {
                    throw new Exception("Daily record not found");
                }
            }

            $now14 = date('YmdHis');

            // =========================
            // PAYLOAD (최소값만)
            // =========================
            $payload = [
                'd_uid'         => $uid ?: null,
                'd_customeruid' => $customerUid,
                'd_accountno'   => $customer['c_accountno'],
                'd_orderdate'   => $visitdate,          // 완료 기준
                'd_driveruid'   => $driverUid,
                'd_druid'       => $druid,

                'd_visit'       => 'Y',
                'd_visitdate'   => $visitdate . '000000',
                'd_status'      => 'F',
                'd_jobtype'     => 'UCO',

                'd_quantity'    => $quantity,
                'd_sludge'      => $sludge,

                'd_paymenttype' => $paymenttype,
                'd_payamount'   => $payamount,
                'd_payeename'   => $payeename,
                'd_paystatus'   => $paystatusSTR,

                'd_inputdate'   => $now14,
                'd_is_transfer' => 'N',
                'd_level'       => $_SESSION['ss_LEVEL'],
            ];
            
            // note → daily.php에서 처리됨
            if ($note !== '') {
                $payload['d_pickupnote'] = $note;
            }

            // 신규 생성 시만
            if ($uid <= 0) {
                $payload['d_ordertype']   = 'N';
                $payload['d_createruid']  = $creatorUid;
                $payload['d_createddate'] = $now14;
            }

            // =========================
            // SIGN FILE 처리
            // =========================
            $folderPath = getenv("DOCUMENT_ROOT") . "/upload_sign/" . $customerUid;

            if (is_dir($folderPath)) {
                $files = scandir($folderPath);
                $tmpFilename = "T_" . $visitdate;

                foreach ($files as $file) {
                    if (strstr($file, $tmpFilename)) {

                        $newName = str_replace("T_", "", $file);

                        if ($file !== $newName) {
                            @rename($folderPath . "/" . $file, $folderPath . "/" . $newName);
                        }

                        $payload['d_payeesign'] = $newName;
                        break;
                    }
                }
            }

            // =========================
            // SAVE
            // =========================
            $opt = [];

            if ($existing) {
                $opt['match_uid'] = $uid;
                $opt['old_key'] = [
                    'd_orderdate' => $existing['d_orderdate'],
                    'd_accountno' => $existing['d_accountno'],
                    'd_jobtype'   => $existing['d_jobtype'],
                ];
                $opt['allow_update'] = true;
            }
            
            $afterData = $this->dailyService->saveDaily($payload, $opt);

            // =========================
            // RESPONSE
            // =========================
            $this->response($this->json([
                "msg" => "Input has been successfully saved.",
                "d_uid" => $afterData['d_uid'] ?? $uid
            ]), 200);

            return;

        } catch (Exception $e) {

            $error = [$e->getMessage()];
            $this->response($this->json($error), 417);
        }
    }


      public function inqMapCenter(){
        try {
            $geo = array(
                "lat" => '43.732188',
                "lon" => '-79.571618'
            );
            $sqCenter = qry("SELECT
                                m_geolat,
                                m_geolon
                            FROM
                                tbl_member
                            WHERE
                                m_currentdriver=".(int)$_POST['driver']);
            if(db_num_rows($sqCenter) > 0) {
                $rstCenter = fetch_array($sqCenter);
                if($rstCenter['m_geolat'] !== null && $rstCenter['m_geolon'] !== null) {
                    $geo = array(
                        "lat" => $rstCenter['m_geolat'],
                        "lon" => $rstCenter['m_geolon']
                    );
                }
            }
            
            $this->response($this->json(array("geo"=>$geo)), 200);
        } catch(Exception $e) {
            $error = array($e->getMessage());
            $this->response($this->json($error), 417);
        }   
      }


			///////////////////////
			// Get Pickup Quantity
			///////////////////////
						
      public function inqPickupQty(){
        try {
        	
						$_POST['route_date'] = str_replace("-","",$_POST['route_date']);
					
		    		$sqQuantity = qry("SELECT
		                            SUM(d_quantity) as pickupquantity
		                        FROM
		                            tbl_daily
		                        WHERE 
		                        		d_status = 'F' AND d_orderdate = '".$_POST['route_date']."' 
		                        		AND d_druid = '".$_POST['driver']."' ");

						$rstQuantity = fetch_array($sqQuantity);
						
						$curPickupQty = number_format((int)$rstQuantity['pickupquantity']);
			
            
            $this->response($this->json(array("curPickupQty"=>$curPickupQty)), 200);
        } catch(Exception $e) {
            $error = array($e->getMessage());
            $this->response($this->json($error), 417);
        }   
      }

}

$api = new API;
$api->processApi();



?>
