<?
// 보여지는 quantity 는 내일 기준임. Forecasting date를 뒤로 바꿔도 내일것으로 보여짐.
// 오더장에 들어갈때는 Forecasting date 에 맞춰져서 저장됨
// 이유는 forecast 를 내일 기준으로 데이터가 생성되기 때문에 오늘 forecast 나 2일 이후의 quantity 는 틀림
// 드라이버가 forecast 기능 사용시 이미 위의 내용 전달하고 컨폼받음

// Level 9 이하만 사용 가능
$func->checkLevelModal(9);

if($orderdate == "") {
	$msg = "Invalid data. Please try again.";
	$func -> modalMsg ($msg, "/index_intranet.php?view=forecast");
	exit();
}
	
// Forecast 기능 제한 (Admin : 1, Staff : 5, Driver : 9 만 가능)
$permit = array("1", "5", "9");
if (in_array($_SESSION['ss_LEVEL'], $permit)) {
    $setTag = "ENABLED";
}
else $setTag = "DISABLED";	

// 환경변수 테이블에서 리스팅 값 가져옴
$qry_cfg = "SELECT * FROM tbl_config WHERE cfg_uid = 1 ";
$rt_cfg = $jdb->fQuery($qry_cfg, "fetch query error");

if ($_SESSION['ss_LEVEL'] == 9) $listCnt = $rt_cfg['cfg_drivercnt'];
else $listCnt = $rt_cfg['cfg_forecastcnt'];
if ($listCnt == 0) $listCnt = 10000;

// searching
if($key_word) {

	$key_wordStr = urldecode(trim($key_word));
	$add_srchquery .= " AND  ((c_accountno LIKE '%$key_wordStr%') OR (c_name LIKE '%$key_wordStr%') OR (c_address LIKE '%$key_wordStr%') 
											OR (c_phone LIKE '%$key_wordStr%') OR (c_cell LIKE '%$key_wordStr%') OR (c_email LIKE '%$key_wordStr%') 
											OR (c_payableto LIKE '%$key_wordStr%') OR (c_rate LIKE '%$key_wordStr%')
											OR (c_location LIKE '%$key_wordStr%') OR (c_city LIKE '%$key_wordStr%')
											OR (c_postal LIKE '%$key_wordStr%') OR (c_contractby LIKE '%$key_wordStr%')
											OR (c_salesperson LIKE '%$key_wordStr%') OR (c_salesmethod LIKE '%$key_wordStr%')
											OR (c_paymenttype LIKE '%$key_wordStr%')) ";
}

// Order By

if ($sortorder == "RA") {
			$add_switch_query .= " ORDER BY c_name ASC, ";
} else if ($sortorder == "RD") {
			$add_switch_query .= " ORDER BY c_name DESC, ";
} else if ($sortorder == "AA") {
			$add_switch_query .= " ORDER BY TRIM(SUBSTRING(c_address,LOCATE(' ',c_address)+1)) ASC, 
											CAST(TRIM(LEFT(c_address,LOCATE(' ',c_address) - 1)) AS SIGNED) ASC, ";
} else if ($sortorder == "AD") {
			$add_switch_query .= " ORDER BY TRIM(SUBSTRING(c_address,LOCATE(' ',c_address)+1)) DESC, 
											CAST(TRIM(LEFT(c_address,LOCATE(' ',c_address) - 1)) AS SIGNED) DESC, ";
} else $add_switch_query = " ORDER BY ";

if (!$c_areaall) {
	if(is_array($c_area))	{
		$count_a = count($c_area);
		for($ia = 0; $ia < $count_a; $ia ++) {
				$areaQRY .= "a_text = '".$c_area[$ia]."' OR ";
				
				$areaSTR .= $c_area[$ia]." / ";
		}
	} 
	else {
		$areaQRY = "";
		$areaSTR = "ALL";
	}

	if ($count_a > 0) {
		$areaQRY = substr($areaQRY, 0, -4);
		$areaQRY = " AND c_city IN (SELECT a_city FROM tbl_area WHERE ".$areaQRY.")";
		
		$areaSTR = substr($areaSTR, 0, -2);
	}
	
}
else {
	$areaQRY = "";
	$areaSTR = "ALL";
}


if(is_array($c_maincontainer))	{
	$count = count($c_maincontainer);
	for($i = 0; $i < $count; $i ++) {
			$containerQRY .= "c_maincontainer = '".$c_maincontainer[$i]."' OR ";
			
			$containerSTR .= $c_maincontainer[$i]." / ";
	}
}
else $containerQRY = "";

if ($count > 0) {
	$containerQRY = substr($containerQRY, 0, -4);
	$containerQRY = " AND (".$containerQRY.")";
	
	$containerSTR = substr($containerSTR, 0, -2);
}
//echo "[$areaSTR][$areaQRY]<br><br>[$containerSTR][$containerQRY]";


//$c_fullquantityR = $c_fullquantity;

// Get Area Info
$qry_area = "SELECT * FROM tbl_area GROUP BY a_text ORDER BY a_text ASC ";
$rt_area = $jdb->nQuery($qry_area, "list error"); 

$area_cnt=1;
while($lt_area=mysqli_fetch_array($rt_area, MYSQLI_ASSOC)) {
	
	if ($area_cnt%6 == 0) $areaSTR = "<br>";
	else $areaSTR = "";

	//if ($c_areaall) $checkedFlag = "checked";
	//else {
		if(is_array($c_area))	{
			$count_a = count($c_area);
			for($ia = 0; $ia < $count_a; $ia ++) {
					if ($c_area[$ia] == $lt_area['a_text']) {
						$checkedFlag = "checked";
						break;
					}
					else $checkedFlag = "";
			}
		} 
	//}
	//echo "[".$c_area[$ia]."][".$lt_area['a_text']."][$checkedFlag]<br>";
	$a_textSTR .= "
                  <label class='container-chk'>".$lt_area['a_text']."
                    <input type='checkbox' name='c_area[]' id='c_area_".$lt_area['a_uid']."' value=\"".$lt_area['a_text']."\" ".$checkedFlag.">
                    <span class='checkmark'></span>
                  </label>".$areaSTR;
	$checkedFlag = "";
	$area_cnt++;
}

if ($c_fullcycle) {
	$fullcycleQRY = " AND (c_fullcycle >= $c_fullcycle) ";
	$fullcycleSTR = $c_fullcycle;
}
else $fullcycleSTR = 0;

// 날짜간 일수 계산
$getPeriodOrderTmp  = new DateTime($orderdate);
$getPeriodNowTmp  = new DateTime(date("Y-m-d"));

$dDiffTmp = $getPeriodNowTmp->diff($getPeriodOrderTmp);
$dDiff = $dDiffTmp->format('%r%a');

// 이미 Forecast Batch 에서 내일일자로 c_fullquantitydaily 저장됨 (2024.01.16)
$dDiff = $dDiff -1;


if ($c_fullquantity_a != "" || $c_fullquantity_b != "" ) {


	if ($c_fullquantity_a != "" && $c_fullquantity_b == "" ) {
			$fullquantityQRY = " AND ((c_fullquantity+($dDiff * c_fullquantitydaily)) >= $c_fullquantity_a) ";
		
	}
	else if ($c_fullquantity_a == "" && $c_fullquantity_b != "" ) {
			$fullquantityQRY = " AND ((c_fullquantity+($dDiff * c_fullquantitydaily)) < $c_fullquantity_b) ";
	}
	else {
			$fullquantityQRY = " AND (((c_fullquantity+($dDiff * c_fullquantitydaily)) >= $c_fullquantity_a) 
													 AND ((c_fullquantity+($dDiff * c_fullquantitydaily)) < $c_fullquantity_b)) ";
	}
	
	//$fullquantityQRY = " AND ((c_fullquantity+($dDiff * c_fullquantitydaily)) >= $c_fullquantity) ";
	//$fullquantitySTR = $c_fullquantity;
	$add_query_order = $add_switch_query." (c_fullquantity+($dDiff * c_fullquantitydaily)) DESC";
}
else {
	//$fullquantitySTR = 0;
	$add_query_order = $add_switch_query. " (c_fullquantity+($dDiff * c_fullquantitydaily)) DESC";
}

if ($c_driveruid) {
	$driveruidQRY = " AND (c_driveruid = '".$c_driveruid."') ";
	$org_driveruid = $c_driveruid;
}

if ($c_newaccount) {
	$tmpSTR = "-".$c_newaccount." days"; 
	$getnewaccountDay = date('Ymd', strtotime($tmpSTR)); 
	$newaccountQRY = " AND (c_contractdate >= '".$getnewaccountDay."') ";
}

if ($c_dormantaccount) {
	$tmpSTR = "-".$c_dormantaccount." days"; 
	$getdormantaccountDay = date('Ymd', strtotime($tmpSTR)); 
	$dormantaccountQRY = " AND (c_lastpickupdate <= '".$getdormantaccountDay."') ";
}


// 전체를 보이게 해달라는 요청으로 c_schedule 조건을 뺌 (2024.03.06)
// 대신 리스트에서 S 로 표시

if ($c_type_w == "W" && $c_type_p == "P") 	$typeQRY = " ";
else if ($c_type_w == "W" && $c_type_p != "P") $typeQRY = " AND (c_schedule = 'None' OR c_schedule = 'Will Call') ";
else if ($c_type_w != "W" && $c_type_p == "P") $typeQRY = " AND (c_schedule != 'Will Call') ";
else	$typeQRY = " AND (c_schedule = 'None') ";

// 전체를 보이게 하려면 아래를 주석처리 (2024.03.06)
// 주석 처리하지 않으면 오더장이 생성된 계정은 리스트에서 보이지 않음
//$orderflagQRY = " AND c_orderflag = 0 ";
if ($c_type_o == "O") $orderflagQRY = " AND c_orderflag = 0 ";
else $orderflagQRY = " ";;

$qry_driver = "SELECT m_initial, m_firstname, m_lastname, m_currentdriver FROM tbl_member WHERE m_uid = '$c_driveruid' ";
$rt_driver = $jdb->fQuery($qry_driver, "fetch query error");
	
// $query = "SELECT * FROM tbl_sampletypes 
// INNER JOIN tbl_members ON (tbl_sampletypes.t_uid = tbl_members.m_gid) 
// where tbl_members.m_uid != ''  
// ORDER BY tbl_members.m_uid DESC ";

// 중복 제거
$uids_R = [];
$uids_P = [];
$qryR_dupQRY = "";
if ($c_type_r == 'R') {
	$orderdate = str_replace("-", "", $orderdate);
	$qryR_dupQRY = " and c_uid not in (";
	$qryR_dup = "SELECT * FROM tbl_request WHERE r_driveruid ='$c_driveruid' AND r_status = 'A' AND r_requestdate = '$orderdate'";
	$result=$jdb->nQuery($qryR_dup, "list error");
	while($list=mysqli_fetch_array($result, MYSQLI_ASSOC)) {
		for($i=0; $i<sizeof($list); $i++) {
			foreach ( (Array) $list as $key => $value )
			$$key = $value;
		}
		$qryR_dupQRY = $qryR_dupQRY . $r_customeruid . ',';
		$uids_R[] = $r_customeruid;
	}
	$qryR_dupQRY = $qryR_dupQRY . '0) '; // 의미없는 uid 추가
}
$qryS_dupQRY = "";
if ($c_type_p == 'P') {
	$getWeekDay = strtoupper(date('D', strtotime($orderdate)));
	$orderdate = str_replace("-", "", $orderdate);
	$qryS_dupQRY = " and c_uid not in (";
	$qryS_dup = "SELECT * FROM tbl_customer 
					WHERE c_driveruid ='$org_driveruid' AND c_status = 'A' 
					AND (c_schedulebasic = '$orderdate' OR (c_schedule = '1W' AND c_scheduleday LIKE '%".$getWeekDay."%'))";
	$result=$jdb->nQuery($qryS_dup, "list error");
	while($list=mysqli_fetch_array($result, MYSQLI_ASSOC)) {
		for($i=0; $i<sizeof($list); $i++) {
			foreach ( (Array) $list as $key => $value )
			$$key = $value;
		}
		$qryS_dupQRY = $qryS_dupQRY . $c_uid . ',';
		$uids_P[] = $c_uid;
	}
	$qryS_dupQRY = $qryS_dupQRY . '0) '; // 의미없는 uid 추가
}
$uids_R = array_values(array_unique($uids_R));
$uids_P = array_values(array_unique($uids_P));

$containerMap_R = [];

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

    $sql = "
        SELECT cc_customer_uid, cc_type, cc_owner_type, cc_is_used, 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
    ";

    $res = $jdb->nQuery($sql, "Load R containers error");

    while ($row = mysqli_fetch_assoc($res)) {
        $containerMap_R[$row['cc_customer_uid']][] = $row;
    }
}

$containerMap_P = [];

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

    $sql = "
        SELECT cc_customer_uid, cc_type, cc_owner_type, cc_is_used, 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
    ";

    $res = $jdb->nQuery($sql, "Load P containers error");

    while ($row = mysqli_fetch_assoc($res)) {
        $containerMap_P[$row['cc_customer_uid']][] = $row;
    }
}

//total record
$query = "SELECT COUNT(c_uid) FROM tbl_customer
					WHERE c_uid <> '' AND c_status = 'A' " . $orderflagQRY. $driveruidQRY . $typeQRY . $add_srchquery . $newaccountQRY . $dormantaccountQRY . $fullcycleQRY . $fullquantityQRY . $containerQRY . $areaQRY . $qryR_dupQRY . $qryS_dupQRY;

//if ($qrySTR) {
//		$qrySTRSTR = base64_decode($qrySTR);
//		$query = "SELECT COUNT(c_uid) FROM tbl_customer
//							WHERE c_uid <> '' AND c_status = 'A' AND c_orderflag = 0 AND c_schedule = 'None' " . $qrySTRSTR;
//}

$total_count=$jdb->rQuery($query, "record query error");
//echo "<br><br><br><br>[c_type_w=$c_type_w][c_type_p=$c_type_p][c_type_o=$c_type_o][$total_count][$query]<br>";

$add_query .= " LIMIT ".$listCnt;
$query = "SELECT * FROM tbl_customer
					WHERE c_uid <> '' AND c_status = 'A' " . $orderflagQRY. $driveruidQRY . $typeQRY . $add_srchquery . $newaccountQRY . $dormantaccountQRY . $fullcycleQRY . $fullquantityQRY . $containerQRY . $areaQRY . $qryR_dupQRY . $qryS_dupQRY . 
					$add_query_order . $add_query;

//if ($qrySTR) {
//		$query = "SELECT * FROM tbl_customer
//							WHERE c_uid <> '' AND c_status = 'A' AND c_orderflag = 0 AND c_schedule = 'None' " . $qrySTRSTR . $add_query_order . $add_query;
//}

//echo "[$query]<br>";

//if (!$qrySTR) {
//		$qrySTR = base64_encode($driveruidQRY . $newaccountQRY . $dormantaccountQRY . $fullcycleQRY . $fullquantityQRY . $containerQRY . $areaQRY);
//}

$result=$jdb->nQuery($query, "list error");

// container
$rows = [];
$customer_uids = [];
while ($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
    $customer_uids[] = (int)$r['c_uid'];
}
$customerContainerMap = [];
$customer_uids = array_values(array_unique($customer_uids));
if ($customer_uids) {
    $in = implode(',', $customer_uids);
    $sql_cc = "
      SELECT cc_customer_uid, cc_type, cc_owner_type, cc_is_used, 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
    ";

    $rc = $jdb->nQuery($sql_cc, "Load customer containers error");

    while ($c = mysqli_fetch_assoc($rc)) {
        $cu = (int)$c['cc_customer_uid'];
        if (!isset($customerContainerMap[$cu])) $customerContainerMap[$cu] = [];
        $customerContainerMap[$cu][] = $c;
    }
}

$totalrowcnt = 1;
$list_number = 1;

foreach ($rows as $list) {
	for($i=0; $i<sizeof($list); $i++) {
		//list($key, $value) = each($list);
		foreach ( (Array) $list as $key => $value )
		$$key = $value;
	}

	//$logindateStr = $func -> convertFormat ($MLOGINDATE, 1);
	//$signupdateStr = $func -> convertFormat ($MSIGNUPDATE, 1);
		
	//$qry = "SELECT CNAME  FROM tbl_company WHERE CUID = '$MCOMPANY' ";
	//$rtd=$jdb->fQuery($qry, "fetch query error"); 
	//if ($MCOMPANY == "0" || $MCOMPANY == "") $companyStr = "-";
	//else $companyStr = $rtd[CNAME];
	
	//$c_phone = preg_replace('/[^A-Za-z0-9\-]/', '', $c_phone);
	//$c_phoneSTR = substr ($c_phone, 0, 3)."-".substr ($c_phone, 3, 3)."-".substr ($c_phone, 6, 4);
	
	$c_nameSTR = str_replace("\\", "", $c_name);
	$c_addressSTR = str_replace("\\", "", $c_address);
	$customerContainers = $customerContainerMap[$c_uid] ?? [];
	ob_start();
	include $_SERVER['DOCUMENT_ROOT'].'/lib/customer_container_chips.php';
	$containerChipsHtml = ob_get_clean();
	$c_lastpickupdateSTR = $func -> convertFormat ($c_lastpickupdate, 3);
	$c_fullquantitydateSTR = $func -> convertFormat ($c_fullquantitydate, 3);
	$c_fullquantityActual = round(floatval($c_fullquantity + ($dDiff * $c_fullquantitydaily)));
	$c_fullquantitySTR = number_format($c_fullquantityActual);
	
	if ($c_fullcycleflag == 1) {
		$c_fullcycleSTR = $c_fullcycleforced;
		$c_fullcycleCSS = "style='color:red;'";
	}
	else {
		$c_fullcycleSTR = $c_fullcycle;
		$c_fullcycleCSS = "";
	}
	

	if ($setTag == "") {
		$OPTIONstr = "<a class=\"deleteClass btn-member\" data-toggle=\"modal\" data-target=\"#myModalDelete\" data-id=\"$c_uid\"><i class=\"bi bi-x-circle icon-delete\"></i></a>";
		//$OPTIONTITLEstr = "OPTION";
	}
	else {
		$OPTIONstr = "";
		//$OPTIONTITLEstr = "";
	}


	///////////////////////
	// Get This/Last year Quantity
	///////////////////////
	$getThisYear = date("Y");
	$getLastYear = date("Y", strtotime('last year'));
	
	//echo "<br><br><br><br>[$get1Mon][$get2Mon][$get3Mon]";

	$qry_sum = "SELECT 
								SUM(CASE WHEN d_visitdate like '".$getThisYear."%' THEN d_quantity ELSE 0 END) AS THISYEAR, 
								SUM(CASE WHEN d_visitdate like '".$getLastYear."%' THEN d_quantity ELSE 0 END) AS LASTYEAR
							FROM  tbl_daily 
							WHERE d_customeruid = '".$c_uid."' AND d_status = 'F' ";
//echo "LIST_TOT[$qry_sum]<br>";							
	$rt_sum = $jdb->fQuery($qry_sum, "fetch query error");
	
	$getThisYearQ = number_format(floatval($rt_sum['THISYEAR']));
	$getLastYearQ = number_format(floatval($rt_sum['LASTYEAR']));

	$driverPopup = "<a data-toggle='modal' class='customerShortInfo' data-target='#myModalcustomerShortInfo' data-id=\"$c_uid\" data-history-type='standard-access'>&#10067;</a>";

	if ($c_schedule == 'Will Call') { 
		$list_numberSTR = "W";
		$classSTR = "bg-will-call";
	}
	else if ($c_schedule != 'Will Call' && $c_schedule != 'None' ) { 
		$list_numberSTR = "S";
		$classSTR = "bg-period-reg";
	}
	else {
		$list_numberSTR = $list_number;
		$classSTR = "";
	}
	
	$strList .= "
		    <tr class='$classSTR' data-id=\"$c_uid\" data-name=\"".htmlspecialchars($c_nameSTR, ENT_QUOTES)."\" data-name>
              <td>                            
                <label class='container-chk'>
                  <!--input type='checkbox' checked='checked'-->
                  <input type='checkbox' name='selectaccountno[]' data-price=\"$c_fullquantityActual\" class='custom-checkbox' id='selectaccountno".$c_uid."' value=\"N|".$c_accountno."\">
                  <span class='checkmark'></span>
                </label>
              </td>            
              <td>$list_numberSTR</td>
              <td><a class='restaurant-link' onclick=\"javascript:window.open('/index_intranet.php?view=customer_detail&mode=update&c_uid=$c_uid&page=$page&key_word=$key_word&column=$column&switched=$getSWHStr&sorting_type=$sorting_type&switch=$switch','_blank');\" style='cursor:pointer;cursor:hand;'><b class='customer-info-detail'>$c_nameSTR</b></a>&nbsp;&nbsp; $driverPopup</td>
              <td>$c_accountno</td>
              <td>$containerChipsHtml</td>
              <td>$c_paymenttype</td>
              <td>$c_rate</td>
              <td>$c_addressSTR</td>
              <td>$c_city</td>
              <td style=\"text-align: right;margin-right: 20px;\">$getLastYearQ</td>
              <td style=\"text-align: right;margin-right: 20px;\">$getThisYearQ</td>
              ";

	if ($_SESSION['ss_LEVEL'] == 9) {
			$strList .= "		
              <td style=\"text-align: right;margin-right: 20px;\">$c_fullcycleSTR</td>
              ";
	} else {     
			$strList .= "				         
              <td style=\"text-align: right;margin-right: 20px; padding-top: 2px; padding-bottom: 2px;\">

              		<input type='text' id=c_fullcycle_".$c_uid." name=c_fullcycle_".$c_uid." data-id=".$c_uid." ".$c_fullcycleCSS." class='updatecycle_form' required='required' value=".$c_fullcycleSTR." size=3 >


<script>

$('#c_fullcycle_".$c_uid."').on('change', function () { // changed
		var ii = $(this).data('id');
		var cc = document.getElementById('c_fullcycle_".$c_uid."').value;
		//alert(cc);exit;
		
    $.ajax({
        type: 'POST',
        url: '/lib/lib_updatecycle.php',
        data: { c_uid : ii, c_fullcycle : cc },
		    success: function(response){ 
					//alert(response);
					
          var rt = response.split('|');
          
					if (rt[0].trim().match('OK')) {
						//alert(rt[1]);

            document.getElementById('c_fullcycle_".$c_uid."').style.color = 'red';
						
						$('.myModalPopup-body').html('Successfully Updated');
						$('.myModalPopup-body').css('background-color', '#2A9B56');
            $('#myModalPopup').modal('show'); 

				    setTimeout(function () {
				        $('#myModalPopup').modal('hide'); 
				    }, 900);   
				    
						//showPopup();
						
						//setTimeout(function() {
					    	//$('.popup').fadeOut();
					  //  	hidePopup();
						//}, 2000);

					} else {
						if (rt[2] == 1) {
								document.getElementById('c_fullcycle_".$c_uid."').value = rt[1];
								document.getElementById('c_fullcycle_".$c_uid."').style.color = 'red';
						}
						else if (rt[2] == 0) {
								document.getElementById('c_fullcycle_".$c_uid."').value = rt[1];
						}

						$('.myModalPopup-body').html('Update Failed');
						$('.myModalPopup-body').css('background-color', '#F43700');
            $('#myModalPopup').modal('show'); 

				    setTimeout(function () {
				        $('#myModalPopup').modal('hide'); 
				    }, 1800);   						
					}

          //$('#myModalPopup').modal('show'); 
          					
		    }
    });
});

</script>
              </td>";

	}

              
	$strList .= "		              
              <td>$c_lastpickupdateSTR</td>
              <!--td>$c_fullquantitydateSTR</td-->
              <td style=\"text-align: right;margin-right: 20px;\">$c_fullquantitySTR</td>

            </tr>

	";

	$list_number++;
	$totalrowcnt++;
}


if( $total_count < 1 ) {
	$strList = "
		<tr><td colspan='16' align=center height='30'><B>No Data</B></td></tr>
		";
}

//echo "<br><br><br><br><br><br><br>";

/////////////////////////
// ADD REQUESTED DATA
/////////////////////////

if ($c_type_r == 'R') {
			$orderdate = str_replace("-", "", $orderdate);
			$qry_r = "SELECT * FROM tbl_request
								WHERE r_druid ='".$rt_driver['m_currentdriver']."' AND r_status = 'A' AND r_requestdate = '$orderdate'
								ORDER BY r_uid DESC";
			//echo "Request[$qry_r]<br>";

			$rt_r=$jdb->nQuery($qry_r, "list error");

			while($list=mysqli_fetch_array($rt_r, MYSQLI_ASSOC)) {
						for($i=0; $i<sizeof($list); $i++) {
							//list($key, $value) = each($list);
							foreach ( (Array) $list as $key => $value )
							$$key = $value;
						}

						$qry_rc = "SELECT * FROM tbl_customer WHERE c_uid = '$r_customeruid'";
						$rt_rc = $jdb->fQuery($qry_rc, "query error");
						
						//echo "[$qry_rc]";
						for($i=0; $i<sizeof($rt_rc); $i++) {
							//list($key, $value) = each($result);
							foreach ( (Array) $rt_rc as $key => $value )		
							$$key = $value;
						}
						
						$c_nameSTR = str_replace("\\", "", $c_name);
						$c_addressSTR = str_replace("\\", "", $c_address);
						$c_containerSTR = str_replace("\\", "", $c_container);
						$c_lastpickupdateSTR = $func -> convertFormat ($c_lastpickupdate, 3);
						$c_fullquantitydateSTR = $func -> convertFormat ($c_fullquantitydate, 3);
						//$c_fullquantitySTR = number_format(floatval($c_fullquantity));
						$c_fullquantityActual = round(floatval($c_fullquantity + ($dDiff * $c_fullquantitydaily)));
						$c_fullquantitySTR = number_format($c_fullquantityActual);
						$customerContainers = $containerMap_R[$c_uid] ?? [];
						ob_start();
						include $_SERVER['DOCUMENT_ROOT'].'/lib/customer_container_chips.php';
						$containerChipsHtml = ob_get_clean();
							
						///////////////////////
						// Get This/Last year Quantity
						///////////////////////
						$getThisYear = date("Y");
						$getLastYear = date("Y", strtotime('last year'));
						
						//echo "<br><br><br><br>[$get1Mon][$get2Mon][$get3Mon]";

						$qry_sum = "SELECT 
													SUM(CASE WHEN d_visitdate like '".$getThisYear."%' THEN d_quantity ELSE 0 END) AS THISYEAR, 
													SUM(CASE WHEN d_visitdate like '".$getLastYear."%' THEN d_quantity ELSE 0 END) AS LASTYEAR
												FROM  tbl_daily 
												WHERE d_customeruid = '".$r_customeruid."' AND d_status = 'F' ";
					//echo "LIST_TOT[$qry_sum]<br>";							
						$rt_sum = $jdb->fQuery($qry_sum, "fetch query error");
						
						$getThisYearQ = number_format(floatval($rt_sum['THISYEAR']));
						$getLastYearQ = number_format(floatval($rt_sum['LASTYEAR']));

						$driverPopup = "<a data-toggle='modal' class='customerShortInfo' data-target='#myModalcustomerShortInfo' data-id=\"$c_uid\" data-history-type='standard-access'>&#10067;</a>";

						$strList_r .= "
								<tr class='bg-request' data-id=\"$c_uid\" data-name=\"".htmlspecialchars($c_nameSTR, ENT_QUOTES)."\" data-name>
					              <td>                            
					                <label class='container-chk'>
					                  <!--input type='checkbox' checked='checked'-->
					                  <input type='checkbox' name='selectaccountno[]' data-price=\"$c_fullquantityActual\" class='custom-checkbox' id='selectaccountno".$c_uid."' value=\"R|".$c_accountno."|".$r_uid."\">
					                  <span class='checkmark'></span>
					                </label>
					              </td>		            
					              <td>R</td>
					              <td><a class='restaurant-link' onclick=\"javascript:window.open('/index_intranet.php?view=customer_detail&mode=update&c_uid=$c_uid&page=$page&key_word=$key_word&column=$column&switched=$getSWHStr&sorting_type=$sorting_type&switch=$switch','_blank');\" style='cursor:pointer;cursor:hand;'><b class='customer-info-detail'>$c_nameSTR</b></a>&nbsp;&nbsp; $driverPopup</td>
					              <td>$c_accountno</td>
					              <td>$containerChipsHtml</td>
					              <td>$c_paymenttype</td>
					              <td>$c_rate</td>
					              <td>$c_addressSTR</td>
					              <td>$c_city</td>
					              <td style=\"text-align: right;margin-right: 20px;\">$getLastYearQ</td>
					              <td style=\"text-align: right;margin-right: 20px;\">$getThisYearQ</td>
					              <td style=\"text-align: right;margin-right: 20px;\">$c_fullcycle</td>
					              <td>$c_lastpickupdateSTR</td>
					              <!--td>$c_fullquantitydateSTR</td-->
					              <td style=\"text-align: right;margin-right: 20px;\">$c_fullquantitySTR</td>

					            </tr>

						";
						
						$totalrowcnt++;
				
			}
}

//echo "<br><br><br><br>[".date('D')."][".strtoupper(date('D'))."][$ttt]";

/////////////////////////
// ADD SCHEDULED DATA
/////////////////////////
// Pick Up 입력시 tbl_customer 의 c_schedulebasic 에 다음 픽업일자 넣어줌.
// c_schedulebasic 존재하고 orderdate 일자와 동일하면 보여줌


if ($c_type_p == 'P') {
		
		/*
		select c_accountno,c_schedule,c_scheduleday
		from tbl_customer where c_schedule > '1W' AND c_schedule <= '6W' 
		Order by c_schedule asc
		*/

		$getWeekDay = strtoupper(date('D', strtotime($orderdate)));
		$orderdate = str_replace("-", "", $orderdate);

		$qry_s = "SELECT * FROM tbl_customer 
							WHERE c_driveruid ='$org_driveruid' AND c_status = 'A' 
							AND (c_schedulebasic = '$orderdate' OR (c_schedule = '1W' AND c_scheduleday LIKE '%".$getWeekDay."%'))
							ORDER BY c_uid DESC";
		//echo "<br><br><br><br><br>Scheduled[$qry_s]<br>";

		$rt_s=$jdb->nQuery($qry_s, "list error");

		
		while($list=mysqli_fetch_array($rt_s, MYSQLI_ASSOC)) {
					for($i=0; $i<sizeof($list); $i++) {
						//list($key, $value) = each($list);
						foreach ( (Array) $list as $key => $value )
						$$key = $value;
					}
					
					$c_nameSTR = str_replace("\\", "", $c_name);
					$c_addressSTR = str_replace("\\", "", $c_address);
					$c_containerSTR = str_replace("\\", "", $c_container);
					$c_lastpickupdateSTR = $func -> convertFormat ($c_lastpickupdate, 3);
					$c_fullquantitydateSTR = $func -> convertFormat ($c_fullquantitydate, 3);

					//$c_fullquantitySTR = number_format(floatval($c_fullquantity));
					$c_fullquantityActual = round(floatval($c_fullquantity + ($dDiff * $c_fullquantitydaily)));
					$c_fullquantitySTR = number_format($c_fullquantityActual);
					$customerContainers = $containerMap_P[$c_uid] ?? [];
					ob_start();
					include $_SERVER['DOCUMENT_ROOT'].'/lib/customer_container_chips.php';
					$containerChipsHtml = ob_get_clean();

					///////////////////////
					// Get This/Last year Quantity
					///////////////////////
					$getThisYear = date("Y");
					$getLastYear = date("Y", strtotime('last year'));
					
					//echo "<br><br><br><br>[$get1Mon][$get2Mon][$get3Mon]";

					$qry_sum = "SELECT 
												SUM(CASE WHEN d_visitdate like '".$getThisYear."%' THEN d_quantity ELSE 0 END) AS THISYEAR, 
												SUM(CASE WHEN d_visitdate like '".$getLastYear."%' THEN d_quantity ELSE 0 END) AS LASTYEAR
											FROM  tbl_daily 
											WHERE d_customeruid = '".$c_uid."' AND d_status = 'F' ";
				//echo "LIST_TOT[$qry_sum]<br>";							
					$rt_sum = $jdb->fQuery($qry_sum, "fetch query error");
					
					$getThisYearQ = number_format(floatval($rt_sum['THISYEAR']));
					$getLastYearQ = number_format(floatval($rt_sum['LASTYEAR']));
					
					$driverPopup = "<a data-toggle='modal' class='customerShortInfo' data-target='#myModalcustomerShortInfo' data-id=\"$c_uid\" data-history-type='standard-access'>&#10067;</a>";

					$strList_s .= "
							<tr class='bg-period' data-id=\"$c_uid\" data-name=\"".htmlspecialchars($c_nameSTR, ENT_QUOTES)."\" data-name>
				              <td>                            
				                <label class='container-chk'>
				                  <!--input type='checkbox' checked='checked'-->
				                  <input type='checkbox' name='selectaccountno[]' data-price=\"$c_fullquantityActual\" class='custom-checkbox' id='selectaccountno".$c_uid."' value=\"S|".$c_accountno."\">
				                  <span class='checkmark'></span>
				                </label>
				              </td>		            
				              <td>S</td>
				              <td><a class='restaurant-link' onclick=\"javascript:window.open('/index_intranet.php?view=customer_detail&mode=update&c_uid=$c_uid&page=$page&key_word=$key_word&column=$column&switched=$getSWHStr&sorting_type=$sorting_type&switch=$switch','_blank');\" style='cursor:pointer;cursor:hand;'><b class='customer-info-detail'>$c_nameSTR</b></a>&nbsp;&nbsp; $driverPopup</td>
							  <td>$c_accountno</td>
				              <td>$containerChipsHtml</td>
				              <td>$c_paymenttype</td>
				              <td>$c_rate</td>
				              <td>$c_addressSTR</td>
				              <td>$c_city</td>
				              <td style=\"text-align: right;margin-right: 20px;\">$getLastYearQ</td>
				              <td style=\"text-align: right;margin-right: 20px;\">$getThisYearQ</td>
				              <td style=\"text-align: right;margin-right: 20px;\">$c_fullcycle</td>
				              <td>$c_lastpickupdateSTR</td>
				              <!--td>$c_fullquantitydateSTR</td-->
				              <td style=\"text-align: right;margin-right: 20px;\">$c_fullquantitySTR</td>

				            </tr>

					";
					
					$totalrowcnt++;
		}
}


//echo "<br><br><br><br>[".date('D')."][".strtoupper(date('D'))."][$ttt]";


addLog ("add", "FORECAST LIST", "VIEW", $lguserid, $query, $lgno);


?>  


<? include getenv("DOCUMENT_ROOT")."/include/message_js.php"; ?>


<script type="text/javascript">

$(document).ready(function(){

	var clicked = false;
	var checkallflag = 0;
	var sumall = 0;
	
	$("#checkalloption").on("click", function() {
			$("#orderoil_table input:checkbox").prop("checked", !clicked);
			clicked = !clicked;
			
			if (clicked) checkallflag=1;
			
			//this.innerHTML = clicked ? 'Deselect' : 'Select';
			//$.fn.getEstimateSum ();
			//alert('Hi');
			//let sum = 0
			
			sumall = 0;
			
			$("#orderoil_table input:checkbox").each(function() 
			{   
			    if($(this).is(':checked')) {
			      sumall = sumall +Number($(this).data('price')); 
			      //alert($(this).val());
			    }
			    
			    estimatetotal.innerHTML = sumall.toLocaleString("en-US");
			});
						
	});
		
		
	$(function () {    	
			let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
			let estimatetotal = document.getElementById("estimatetotal")
			//let customProductPricing = document.getElementById("customProductPricing")
			let sum = 0


			$("#checkalloption").on("click", function() {
					//$("#orderoil_table input:checkbox").prop("checked", !clicked);
					if (clicked) { 
							//alert("hhh");
							sum = 0;
							$("#orderoil_table input:checkbox").each(function() 
							{   
							    if($(this).is(':checked')) {
							      sum = sum +Number($(this).data('price')); 
							      //alert($(this).val());
							    }
							});
					} 
					else sum = 0;
			});


			for (let i = 0; i < addonCheckboxes.length; i++) {

			  addonCheckboxes[i].addEventListener("change", function(e) {

			    console.log(e.target.dataset.price)
			    
			    if (addonCheckboxes[i].checked != false) {
			      
			      sum = sum +Number(e.target.dataset.price) 
			    } else {
			      sum =  sum -Number(e.target.dataset.price) 
			    }
			    
			    estimatetotal.innerHTML = sum.toLocaleString("en-US");
			    
			  })

			}
	});
	
});
</script>


<script type="text/javascript">
$(document).ready(function(){

		// Decimal (ex 11, 11.0)
		$("#c_fullquantity_a, #c_fullquantity_b, #c_fullcycle").on("input", function(evt) {
				var self = $(this);
				self.val(self.val().replace(/[^0-9\.]/g, ''));
				if ((evt.which != 46 || self.val().indexOf('.') != -1) && (evt.which < 48 || evt.which > 57)) 
				{
				 evt.preventDefault();
				}
		});
			
		/* $("#checkAll").click(function () {
		     $('input:checkbox').not('#notcheckbox').prop('checked', this.checked);
		 });
		*/
		$("#checkallarea").click(function () {
		   $('#checkboxarea input:checkbox').not('this').prop('checked', this.checked);
		});

		$("#checkallbin").click(function () {
		   $('#checkboxbin input:checkbox').not('this').prop('checked', this.checked);
		});


});


		
</script>


<script>
$(document).ready(function(){
    
    $("#form_search").change(function(){
        //$(this).css("background-color", "#FFD2A6");
        $('#form_search').submit();
    });

		$('.customerShortInfo').click(function(){
		 
		   var ccuid = $(this).data('id');

		   // AJAX request
		   $.ajax({
				    url: 'lib/shortInfo_lib.php',
				    type: 'post',
				    data: {c_uid: ccuid},
				    success: function(response){ 
				      // Add response in Modal body
				      $('.modal-content-modifycustomerShortInfo').html(response);

				      // Display Modal
				      //$('#myModalModify').modal('show'); 
				    }
			});
		});    
		
});

</script>


  <main id="main" class="main">

    <!-- ======= Breadcrumbs ======= -->
    <div class="breadcrumbs">
      <div class="container">

        <div class="d-flex justify-content-between align-items-center">
          <h2>FORECAST</h2>
          <ol>
            <li><a href="index.html">HOME</a></li>
            <li>FORECAST</li>
          </ol>
        </div>

      </div>
    </div><!-- End Breadcrumbs -->

    <section class="page">


      <div class="container" data-aos="fade-up">

        <!-- New -->
        <div class="wrap-border">
          <div style="display: flex; justify-content: space-between; align-items: center;">
			<div style="text-align: left; width: 220px">
				<? if ($_SESSION['ss_LEVEL'] < 7) { ?>
				<form name="exportorder" id="exportorder" method="POST" action="/doc/export_process.php" style="margin: 0;">
				<input type="hidden" name="mode" value="export">
				<input type="hidden" name="actionStr" value="FORECAST">
				
				<input type="hidden" name="listCnt" value="<?=$listCnt?>">
				<input type="hidden" name="orderflagQRY" value="<?=$orderflagQRY?>">
				<input type="hidden" name="driveruidQRY" value="<?=$driveruidQRY?>">
				<input type="hidden" name="typeQRY" value="<?=$typeQRY?>">
				<input type="hidden" name="add_srchquery" value="<?=$add_srchquery?>">
				<input type="hidden" name="newaccountQRY" value="<?=$newaccountQRY?>">
				<input type="hidden" name="dormantaccountQRY" value="<?=$dormantaccountQRY?>">
				<input type="hidden" name="dormantaccountQRY" value="<?=$dormantaccountQRY?>">
				<input type="hidden" name="fullcycleQRY" value="<?=$fullcycleQRY?>">
				<input type="hidden" name="fullquantityQRY" value="<?=$fullquantityQRY?>">
				<input type="hidden" name="containerQRY" value="<?=$containerQRY?>">
				<input type="hidden" name="areaQRY" value="<?=$areaQRY?>">
				<input type="hidden" name="add_query_order" value="<?=$add_query_order?>">
				<input type="hidden" name="add_query" value="<?=$add_query?>">
				<input type="hidden" name="getThisYear" value="<?=$getThisYear?>">
				<input type="hidden" name="getLastYear" value="<?=$getLastYear?>">

				<input type="hidden" name="c_type_r" value="<?=$c_type_r?>">
				<input type="hidden" name="c_type_p" value="<?=$c_type_p?>">
				<input type="hidden" name="c_type_w" value="<?=$c_type_w?>">
				<input type="hidden" name="org_driveruid" value="<?=$org_driveruid?>">
				<input type="hidden" name="orderdate" value="<?=$orderdate?>">

				<button type="submit" class="btn-add text-center">DOWNLOAD</button>
				</form>
				<? } ?>
			</div>
			<div style="text-align: right;">
				<span class="box-will-call">Will Call</span>
				<span class="box-period">Scheduled</span>
				<span class="box-request">Request</span>
			</div>
          </div>
        </div><!--wrap-border-->
        <!-- New -->

<FORM NAME=orderoil id=orderoil class="orderoil" METHOD=POST ACTION="/lib/user_process.php" >
<input type=hidden name=actionStr value="ORDEROIL">	
<input type=hidden name=mode value="insert">	
<input type=hidden name=orderdate value="<?=$orderdate?>">

        <div class="wrap-overflow forecast-info" >
          <table class="tb-list" id="orderoil_table">
            <tr>
            		<th id="checkalloption">Option</th>
                <th>No</th>
                <th class="td-restaurant">Restaurant Name</th>
                <th class="fore-account">Account</th>
                <th style="width: 200px;" class="fore-container">Container</th>
                <th class="fore-payment">Payment</th>
                <th class="fore-rate">Rate</th>
                <th class="td-address">Address</th>
                <th class="fore-city">City</th>
                <th style="text-align: right;margin-right: 10px;" class="fore-2021"><?=$getLastYear?></th>
                <th style="text-align: right;margin-right: 10px;" class="fore-2023"><?=$getThisYear?></th>
                <th style="text-align: right;margin-right: 10px;" class="fore-cycle">Cycle</th>
                <th class="td-lastpu">Last PU</th>
                <!--th class="td-nextpu">Next PU</th-->
                <th>Liter</th>
                
            </tr>

<?=$strList_r?>
<?=$strList_s?>
<?=$strList?>

          </table>
        </div>

<!-- 따라다니는 배너용 -->
<button type="button" class="sticky-estimate  btn ">
  <span class="txt-estimate">ESTIMATE : <span id="estimatetotal">0</span> L</span>
</button>


        <!--div class="container-inner">
          <p class="estimate-wrap"><span class="txt-estimate">ESTIMATE : <span id="estimatetotal">0</span> L</span></p>
        </div-->
        <br><br>
        <div class="grid-layout-col-2">

<? if ($setTag == "ENABLED") { ?>
              <div class="grid-col-2">
                <button type="submit" id="customer-button-id" class="btn-sub text-center" href="#">ORDER</button>
              </div>
<? } ?>  
              <div class="grid-col-2">
                <a class="btn-sub-white text-center" style="cursor:pointer;cursor:hand;" href="/index_intranet.php?view=forecast">SEARCH AGAIN</a>
              </div>

        </div>

</FORM>

      </div><!--container Ends-->
        

    </section>

  </main><!-- End #main -->

<!-- Filter Navi -->
  <button type="button" data-toggle="modal" data-target="#sidebar-left" class="filter-icon d-flex align-items-center justify-content-center btn btn-primary pull-right">
    <i class="bi bi-filter-left"></i>
  </button>


<!-- Filter -->
<div class="modal fade left" id="sidebar-left" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-sm" role="document">
      <div class="modal-content">
        <div class="modal-header">
            <h4 class="modal-title">Filter</h4>
            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span></button>
        </div>

        <div class="modal-body filter-forecast-body">
            <FORM method=post id="form_search" name="form_search" action='<?=$_SERVER["PHP_SELF"]?>' class="form-forecast-search">
            	<input type=hidden name=view value='forecast_list'>
            	<input type=hidden name="c_driveruid" id="c_driveruid" value='<?=$c_driveruid?>'>
            	<input type=hidden name=orderdate value="<?=$orderdate?>">
            	
              <table class="td-search">

                <tr>
                  <td class="td-title"><label for="Liter">Search</label></td>
                </tr>
                <tr>
                  <td><input type="text" id="key_word" name="key_word" value="<?=$key_word?>" placeholder="Keyword"></td>
                </tr>

                <tr>
                  <td><hr></td>
                </tr>                

                <tr>
                  <td class="td-title"><label for="Liter">Liter</label></td>
                </tr>
                <tr>
                  <td>
                  	<input type="text" id="c_fullquantity_a" name="c_fullquantity_a" value="<?=$c_fullquantity_a?>" placeholder="500">
                  	&nbsp;&#8806; &nbsp;Liter &nbsp;&#60;&nbsp;
                  	<input type="text" id="c_fullquantity_b" name="c_fullquantity_b" value="<?=$c_fullquantity_b?>" placeholder="500">
                  </td>
                </tr>

                <tr>
                  <td><hr></td>
                </tr>   

                <tr>
                  <td class="td-title"><label for="DormantAccount">Order By</label></td>
                </tr>
                <tr>
                  <td id="checkboxorder">
                <select name="sortorder" id="sortorder" class="custom-select" required='required'>
                	<option value=''>Select</option>
                  <option value='RA' <?=($sortorder == "RA")?"selected":"";?>>Restaurant Name - Ascending</option>
                  <option value='RD' <?=($sortorder == "RD")?"selected":"";?>>Restaurant Name - Descending</option>
                  <option value='AA' <?=($sortorder == "AA")?"selected":"";?>>Address - Ascending</option>
                  <option value='AD' <?=($sortorder == "AD")?"selected":"";?>>Address - Descending</option>
                </select>                   	
                  	                  
                  </td>
                </tr>

                <tr>
                  <td><hr></td>
                </tr>
                
                <tr>
                  <td class="td-title"><label for="Area">Type</label></td>
                </tr>
                <tr>
                  <td id="checkboxarea">   

									<label class='container-chk'>Will Call
                    <input type='checkbox' name='c_type_w' id='c_type_w' value="W" <? if($c_type_w=='W') echo "checked" ?>>
                    <span class='checkmark'></span>
                  </label>

									<label class='container-chk'>Scheduled
                    <input type='checkbox' name='c_type_p' id='c_type_p' value="P" <? if($c_type_p=='P') echo "checked" ?>>
                    <span class='checkmark'></span>
                  </label>

									<label class='container-chk'>Request
                    <input type='checkbox' name='c_type_r' id='c_type_r' value="R" <? if($c_type_r=='R') echo "checked" ?>>
                    <span class='checkmark'></span>
                  </label>

									<input type=hidden name=c_type_o value="<?=$c_type_o?>">
									
									<!--label class='container-chk'>Ordered
                    <input type='checkbox' name='c_type_o' id='c_type_o' value="O" <? if($c_type_o=='O') echo "checked" ?>>
                    <span class='checkmark'></span>
                  </label-->
                  
                  </td>
                </tr>
                
                
                <tr>
                  <td><hr></td>
                </tr>
                
                <tr>
                  <td class="td-title"><label for="Area">Area</label></td>
                </tr>
                <tr>
                  <td id="checkboxarea">   

<?=$a_textSTR?>

                  <label class="container-chk">All
                    <input type="checkbox" name="c_areaall" id="checkallarea" value="1">
                    <span class="checkmark"></span>
                  </label>

                  </td>
                </tr>


                <tr>
                  <td><hr></td>
                </tr>

<? if ($fflag == 1) { ?>
                <tr>
                  <td class="td-title"><label for="Bin">Bin</label></td>
                </tr>
                <tr>
                  <td id="checkboxbin">

<?=$c_maincontainerSTR?>
                  <label class="container-chk">All
                    <input type="checkbox" name="c_maincontainerall" id="checkallbin" value="1">
                    <span class="checkmark"></span>
                  </label>
  
                  </td>
                </tr>


                
                <tr>
                  <td><hr></td>
                </tr>

<? } ?>

                <tr>
                  <td class="td-title"><label for="NewAccount">New Account</label></td>
                </tr>
                <tr>
                  <td>
                    <!--button type="button" class="btn btn-line">Within 30 Days</button>
                    <button type="button" class="btn btn-line">Within 60 Days</button>
                    <button type="button" class="btn btn-line">Within 3 Months</button-->
                    <input type="text" id="c_newaccount" name="c_newaccount" value="<?=$c_newaccount?>" placeholder="500">
                  </td>
                </tr>


                
                <tr>
                  <td><hr></td>
                </tr>


                
                <tr>
                  <td class="td-title"><label for="DormantAccount">Dormant account</label></td>
                </tr>
                <tr>
                  <td>
                    <!--button type="button" class="btn btn-line">Within 30 Days</button>
                    <button type="button" class="btn btn-line">Within 60 Days</button>
                    <button type="button" class="btn btn-line">Within 3 Months</button-->
                    <input type="text" id="c_dormantaccount" name="c_dormantaccount" value="<?=$c_dormantaccount?>" placeholder="500">
                  </td>
                </tr>

                
                <tr>
                  <td><hr></td>
                </tr>


                

                
</FORM>

              </table>
   
        
        </div>

      </div>
    </div>
  </div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="modal fade" id="myModalPopup" tabindex="-1" role="dialog" aria-labelledby="myModalPopup"  style="opacity: 0.5; padding-right: 0px !important;">
  <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
      <div class="modal-content" style="background-color:#F43700 !important; max-width:240px; margin: 0 auto;">
        <div class="myModalPopup-body" style="text-align: center; border-radius: 5px; max-height:60px;	font-size:18px; background-color:#F43700; color: #FFFFFF; font-weight: bold;padding:0.5em 1em; ">

        </div>     	
      </div>
  </div>
</div>



<!-- Modal History Form -->
<div id="myModalQuickPopup" class="modal fade customer-info">
  <div class="modal-dialog" role="document">
    <div class="modal-content modal-content-quickPopup">
    	
    	
    	
      <div class="modal-header">
        <h4 class="modal-title">CUSTOMER INFORMATION</h4>
        <button type="button" class="btn" data-bs-dismiss="modal" aria-label="Close" style="color:#fff;"><i class="bi bi-x"></i></button>
      </div>
      <div class="modal-body">
        <form method="POST" action="#">
          <table class="tb-info-box">

            <tr>
              <td class="td-title-info">Payment</td>
              <td class="td-text-info">
                <input type="number" id="openingBalance" name="openingBalance" placeholder="500.45">
              </td>
            </tr>

            <tr>
              <td class="td-title-info">Comment</td>
              <td class="td-text-info">
                <textarea id="note" class="textarea" name="note" rows="4" cols="20"></textarea>
              </td>
            </tr>

            <tr>
              <td class="td-title-info">Container Location</td>
              <td class="td-text-info">
                <input type="number" id="gas" name="gas" placeholder="60.99">
              </td>
            </tr>

          </table>
          <br>
          <div class="text-center">
          	<button type="button" class="btn-gray width-200" data-dismiss="modal">CLOSE</button>
          </div>
        </form>
      </div>
      
      
    </div><!-- modal-content ends -->
  </div><!-- modal-dialog ends -->
</div>
<!-- Modal History Form Ends -->




<!-- Start of Modal -->

  <!-- Modal -->
  <div class="modal fade customer-info" id="myModalcustomerShortInfo"  aria-labelledby="myModalcustomerShortInfoLabel" aria-hidden="true">
    <div class="modal-dialog" role="document" >
    
      <!-- Modal content-->
      <div class="modal-content modal-content-modifycustomerShortInfo" >

      </div>
      
    </div>
  </div>
  
<!-- End of Modal -->


<div class="offcanvas offcanvas-end" tabindex="-1" id="customerInfoCanvas" data-bs-backdrop="false" data-bs-scroll="true">
  <div class="offcanvas-header" style="background: #2A9B56;">
    <h4 class="offcanvas-title" id="customerCanvasTitle" style="color: #FFFFFF;"></h4>
	<button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas"></button>
  </div>
  <div class="offcanvas-body" id="customerInfoBody">
  </div>
</div>


<script>
$(document).on("click", "label.container-chk, label.container-chk *", function (e) {
    e.stopPropagation();
});

$(document).on("click", "a.restaurant-link", function(e) {
    e.stopPropagation();
});

let openedCid = null;
let panelOpen = false;

const canvasEl = document.getElementById("customerInfoCanvas");
const customerCanvas = new bootstrap.Offcanvas(canvasEl);

$(document).on("click", "tr[data-id]", function () {

    const cid   = $(this).data("id");
    const cname = $(this).data("name");
    const $row  = $(this);

    // 기존 선택 스타일 제거
    $("tr[data-id]").removeClass("selected-row");

    // 동일한 row 클릭 → 패널 닫을 때 선택 해제, 패널 열리면 다시 선택 표시
    if (cid === openedCid) {
        if (panelOpen) {
            customerCanvas.hide();
            openedCid = null;
            return;
        } else {
            customerCanvas.show();
            $row.addClass("selected-row");
            return;
        }
    }

    // 다른 row 선택 → 새 row만 하이라이트
    openedCid = cid;
    $row.addClass("selected-row");

    $("#customerCanvasTitle").text(cname);
    $("#customerInfoBody").html("불러오는 중...");

    customerCanvas.show();

    $.ajax({
        url: "lib/shortInfo_right_lib.php",
        type: "post",
        data: { c_uid: cid },
        success: function (res) {
            $("#customerInfoBody").html(res);
        },
        error: function () {
            $("#customerInfoBody").html("데이터를 불러올 수 없습니다.");
        }
    });
});

// Offcanvas 열림/닫힘 상태 추적
canvasEl.addEventListener("shown.bs.offcanvas", function () {
    panelOpen = true;
});

canvasEl.addEventListener("hidden.bs.offcanvas", function () {
    panelOpen = false;

    // 패널이 닫히면 선택 해제
    $("tr[data-id]").removeClass("selected-row");
    openedCid = null;
});

</script>

<style>
#customerInfoCanvas {
	width: 30%;
	min-width: 400px;
    height: 100vh !important;
    overflow: hidden;
}

.customer-offcanvas-header {
    background: #2A9B56;
    color: #fff;
	overflow: hidden;
}

#customerInfoBody {
    max-height: calc(100vh - 60px);
    overflow: auto !important;
    padding-right: 10px;
}

tr.selected-row {
    outline: 2px solid red !important;
    outline-offset: -2px;
}

tr a {
	color: #212529;
}
</style>