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

// Order List 기능 제한 (Admin : 1, Staff : 5, Accounting : 6, Driver : 9 만 가능)
$permit = array("1", "5", "6", "9");
if (in_array($_SESSION['ss_LEVEL'], $permit)) {
    //$setTag = "ENABLED";
}
else {
		//$setTag = "DISABLED";	
		$msg = "Sorry, You don't have permission. Please contact Administrator.";
		$func -> modalMsg ($msg, "/index_intranet.php");
		exit();
}

$time_start = microtime(true);

$APPLYDATE = "20260316000000";

$add_srchquery = "";
$add_query = "";

// searching
if($key_word) {

	$key_wordStr = urldecode(trim($key_word));
	//$add_srchquery .= " AND  ((m_userid LIKE '%$key_wordStr%') OR (m_firstname LIKE '%$key_wordStr%') OR (m_cell LIKE '%$key_wordStr%'))";
}

// sorting
if($switch) {
	$switched = $func -> switchOrder($switch, $switched);
	$add_query .= " ORDER BY $switch $switched ";
	$switched = $switch . "^" . $switched;
}else if($switched) {
	$switched1 = explode("^", $switched);
	$add_query .= " ORDER BY $switched1[0] $switched1[1] ";
} else {
	$add_query .= " ORDER BY d_orderdate DESC, m_initial ASC ";
}

$getSWHStr = $switched;

/*
SELECT COUNT(*) FROM (
select d_orderdate, m_initial from tbl_daily 
INNER JOIN tbl_member ON (d_driveruid = m_uid) 
group by d_orderdate,d_driveruid
order by d_orderdate DESC, m_initial ASC
) as ORDERLIST
*/
//SELECT d_orderdate,m_initial,d_driveruid, COUNT(*) FROM tbl_daily 
//INNER JOIN tbl_member ON (d_driveruid = m_uid) 
//GROUP BY d_orderdate,d_driveruid
//ORDER BY d_orderdate DESC, m_initial ASC

if ($_SESSION['ss_LEVEL'] == 9) $add_subqry = " m_uid = '".$_SESSION['ss_UID']."' AND d_druid = '".$_SESSION['ss_DRUID']."' ";
else $add_subqry = "(d_druid = m_currentdriver) ";

// For Test
//$add_subqry = " AND m_uid = '17' ";

//total record
$query = "SELECT COUNT(*) FROM (
						SELECT d_orderdate, m_initial from tbl_daily 
							INNER JOIN tbl_member ON ". $add_subqry . "
						GROUP BY d_orderdate,d_driveruid
						ORDER BY d_orderdate DESC, m_initial ASC
					) AS ORDERLIST ";

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

//페이징변수설정
if(!$page) $page = 1;

if(!$list_count) $list_count = $INIT_PAGECNT; //출력리스트 갯수
if(!$page_count) $page_count = $INIT_PAGEVIEWCNT; //출력페이지 갯수

$list_number = $total_count - (($page-1)*$list_count);
$start_number = $list_count * ($page-1);

$add_query .= " LIMIT $start_number, $INIT_PAGECNT";
$query = "SELECT d_orderdate, d_druid, d_drinitial, COUNT(*) AS siteno, 
					COUNT(CASE WHEN d_status = 'F' then 1 ELSE NULL END) AS nowsiteno,
					SUM(d_estquantity) AS todayestqty, SUM(d_quantity) AS todayqty 
					FROM tbl_daily 
					INNER JOIN tbl_member ON ". $add_subqry . "
					GROUP BY d_orderdate,d_drinitial " . $add_allquery . $add_srchquery . $add_query;
//echo "[$query]";

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

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

	//$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];
	
	$d_orderdateSTR = $func -> convertFormat ($d_orderdate, 3);
	
	$todayqtySTR = number_format(floatval($todayqty));
	$todayestqtySTR = number_format(floatval($todayestqty));
	
	//$qry_driver = "SELECT m_firstname, m_lastname FROM tbl_member WHERE m_uid = '$c_driveruid' ";
	//$rt_driver = $jdb->fQuery($qry_driver, "fetch query error");
	
	// tbl_memberhis 에 해당일,해당드라이버가 있는지 확인해서 있으면 update, 없으면 create
	$qry_day = "SELECT COUNT(h_uid) FROM tbl_memberhis 
							WHERE h_date = '".$d_orderdate."' AND h_druid = '".$d_druid."' ";
	$rt_cnt_day = $jdb->rQuery($qry_day, "fetch query error");

	
	$h_departuretime = "-";
	$h_arrivaltime = "-";
	$h_balance_o = "-";
	$h_balance_in = "-";
	$h_balance_out = "-";
	$h_balance_t = "-";
	$h_balance_g = "-";
	
	if ($rt_cnt_day > 0) {
			$dailymode = "update";
			
			// Get Information
			$qry = "SELECT * FROM tbl_memberhis 
								WHERE h_druid = '".$d_druid."' AND h_date = '".$d_orderdate."' 
								ORDER BY h_uid DESC LIMIT 1 ";
			$rt=$jdb->fQuery($qry, "fetch query error");
			//echo"$query";

			for($i=0; $i<sizeof($rt); $i++)
			{
				//list($key, $value) = each($result);
				foreach ( (Array) $rt as $key => $value )			
					$$key = $value;
			}
			
			$h_commentSTR = str_replace("\\", "", $h_comment);
	}
	else $dailymode = "create";

	// Get Cash Out Today
	$qry_cashouttoday = "SELECT SUM(d_payamount) FROM tbl_daily 
						WHERE d_druid = '".$d_druid."' 
								AND (d_visitdate LIKE '".$d_orderdate."%')
								AND d_paystatus = 'P' AND d_status = 'F' ";
								
	$cashoutTODAY = $jdb->rQuery($qry_cashouttoday, "fetch query error");
	//echo"<br>[$qry_cashouttoday]<br>";

	// Get Cash In Today
	$qry_cashintoday = "SELECT h_balance_in FROM tbl_memberhis 
						WHERE h_druid = '".$d_druid."' AND (h_date = $d_orderdate) ORDER BY h_uid DESC LIMIT 1 ";
								
	$cashinTODAY = $jdb->rQuery($qry_cashintoday, "fetch query error");
	//echo"[$qry_cashintoday]<br>";

	// Get Cash Retrun Today
	$qry_cashrttoday = "SELECT h_balance_r FROM tbl_memberhis 
						WHERE h_druid = '".$d_druid."' AND (h_date = $d_orderdate) ORDER BY h_uid DESC LIMIT 1 ";
								
	$cashrtTODAY = $jdb->rQuery($qry_cashrttoday, "fetch query error");
	//echo"[$qry_cashintoday]<br>";
		
	// Get Cash Out Total SUM (해당월)
	$qry_cashout = "SELECT SUM(d_payamount) FROM tbl_daily 
						WHERE d_druid = '".$d_druid."' 
								AND (d_visitdate >= '".$APPLYDATE."' AND d_visitdate < ".$d_orderdate."000000)
								AND d_paystatus = 'P' AND d_status = 'F' ";
								
	$cashoutSUM = $jdb->rQuery($qry_cashout, "fetch query error");
	//echo"[$qry_cashout]<br>";

	// Get Cash Return Total SUM (해당월)
	$qry_cashrt = "SELECT SUM(h_balance_r) FROM tbl_memberhis 
						WHERE h_druid = '".$d_druid."' 
								AND (h_date >= '".substr($APPLYDATE,0,8)."' AND h_date < $d_orderdate) ";
								
	$cashrtSUM = $jdb->rQuery($qry_cashrt, "fetch query error");
	//echo"[$qry_cashrt]<br>";
	
	// Get Cash In Total SUM (해당월 ,해당일 포함)
	$qry_cashin = "SELECT SUM(h_balance_in) FROM tbl_memberhis 
						WHERE h_druid = '".$d_druid."' 
								AND (h_date >= '".substr($APPLYDATE,0,8)."' AND h_date < $d_orderdate) ";
								
	$cashinSUM = $jdb->rQuery($qry_cashin, "fetch query error");
	//echo"[$qry_cashin]<br>";
	
	$balance = floatval($cashinSUM) + floatval($cashinTODAY) - floatval($cashrtTODAY) - floatval($cashoutTODAY) - floatval($cashrtSUM) - floatval($cashoutSUM);
	$openingbalance = floatval($cashinSUM) - floatval($cashrtSUM) - floatval($cashoutSUM);

	$cashoutTODAY = number_format(floatval($cashoutTODAY), 2, '.', ',');
	$cashrtTODAY = number_format(floatval($cashrtTODAY), 2, '.', ',');
	$balance = number_format(floatval($balance), 2, '.', ',');
	$openingbalance = number_format(floatval($openingbalance), 2, '.', ',');
	$h_balance_in = number_format(floatval($h_balance_in), 2, '.', ',');

	$cashoutSUM = number_format(floatval($cashoutSUM), 2, '.', ',');
	$cashinSUM = number_format(floatval($cashinSUM), 2, '.', ',');
	
	$strList .= "

            <tr>
              <td>$list_number</td>
              <td onclick=\"location.href='/index_intranet.php?view=order_driver&d_druid=$d_druid&d_orderdate=$d_orderdate&page=$page&key_word=$key_word&column=$column&switched=$getSWHStr&sorting_type=$sorting_type&switch=$switch'\" style='cursor:pointer;cursor:hand;'><b class='customer-info-detail'>$d_orderdateSTR</b></td>
              <td>$d_drinitial</td>
              <td><!--font color=red>$nowsiteno</font>/-->$siteno</td>
              <td>$h_departuretime</td>
              <td>$h_arrivaltime</td>
              <td style=\"text-align:right; padding-right:20px; color:#2A9B56\">$todayestqtySTR</td>
              <td style=\"text-align:right; padding-right:20px; color:#FF8205\">$todayqtySTR</td>
              <td style=\"text-align:right; padding-right:20px;\">$openingbalance</td>
              <td style=\"text-align:right; padding-right:20px;\">$h_balance_in</td>
              <td style=\"text-align:right; padding-right:20px;\">$cashoutTODAY</td>
              <td style=\"text-align:right; padding-right:20px;\">$cashrtTODAY</td>
              <td style=\"text-align:right; padding-right:20px;\">$balance</td>
              <td style=\"text-align:right; padding-right:20px;\">$h_balance_g</td>
              <td>
                  <button type=\"button\" class=\"dailyRecordClass btn icon-modify\" data-bs-toggle=\"modal\" data-bs-target=\"#myModalDailyRecord\" data-modeid=\"$dailymode\" data-uid=\"$h_uid\" data-driverid=\"$d_driveruid\" data-druid=\"$d_druid\" data-dateid=\"$d_orderdate\" data-modify-type=\"standard-access\">
                    <i class=\"bi bi-pencil-square icon-edit\"></i>
                  </button>
              </td>
            </tr>

	";

	$list_number--;
	
}


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

$time_end = microtime(true);
$timeStr = " [".round(($time_end - $time_start),2)."]";

// addLog ("add", "ORDER LIST".$timeStr, "VIEW", $lguserid, $query, $lgno);

?>


<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/timepicker@1.13.18/jquery.timepicker.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/timepicker@1.13.18/jquery.timepicker.css" />


<script>
		
$(document).ready(function(){

		 $('.dailyRecordClass').click(function(){
		   
          var driverid = $(this).data('driverid');
          var dateid = $(this).data('dateid');
          var modeid = $(this).data('modeid');
          var uid = $(this).data('uid');
          var druid = $(this).data('druid');
    
			   // AJAX request
			   $.ajax({
					    url: 'lib/dailyrecord_lib.php',
					    type: 'post',
					    data: {driverid: driverid, dateid: dateid, modeid: modeid, uid: uid, druid: druid},
					    success: function(response){ 
					      // Add response in Modal body
					      $('.modal-content-dailyRecord').html(response);

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


  });
</script>


<SCRIPT LANGUAGE=JAVASCRIPT>
<!--
function goSearch(f){
    var f = document.form1;
    if(trim(f.key_word.value).length < 1){
        alert('Enter keyword.');
        f.key_word.focus();
        return false;
    }
}
//-->
</SCRIPT>


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

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

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

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

    <section class="page">


      <div class="container" data-aos="fade-up">
        <!--div class="wrap-border">
          <form action=""  class="form-customer">
            <table class="table-search-customer">
              <tr>
                <td class="td-title">
                  <select name="name" id="name" class="custom-select">
                    <option value="jk">J.K.</option>
                    <option value="hs">H.S.</option>
                    <option value="Hold">Hold</option>
                  </select>
                </td>
                <td class="td-title">


                    <div class="search-container">
                        <input class="" type="text" placeholder="Search.." name="search">
                        <button type="submit"><i class="bi-search"></i></button>
                    </div>


                </td>
                <td align="right">
                </td>

              </tr>

            </table>
  
           

  
            
            
  
          </form>
        </div>--><!--wrap-border-->
  

  
        

        <div class="wrap-overflow customer-info">
          <table class="tb-list">
            <tr>
              <th>No</th>
              <th>Date</th>
              <th>Driver</th>
              <th>Stie#</th>
              <th>Departure</th>
              <th>Arrival</th>
              <th style="text-align:right; padding-right:20px;">Forecast(L)</th>
              <th style="text-align:right; padding-right:20px;">Actual(L)</th>
              <th style="text-align:right; padding-right:20px;">Opening Balance</th>
              <th style="text-align:right; padding-right:20px;">Cash In</th>
              <th style="text-align:right; padding-right:20px;">Cash Out</th>
              <th style="text-align:right; padding-right:20px;">Cash Return</th>
              <th style="text-align:right; padding-right:20px;">Balance</th>
              <th style="text-align:right; padding-right:20px;">Gas</th>
              <th>Option</th>
            </tr>

<?=$strList?>

<!--
            <tr>
              <td>1</td>
              <td>2022-12-31</td>
              <td>H.S</td>
              <td>20</td>
              <td>7:25</td>
              <td>18:25</td>
              <td>900</td>
              <td>$300.00</td>
              <td>200.00</td>
              <td>$100.00</td>
              <td>$400.00</td>
              <td>$84.99</td>
              <td>
                  <button type="button" class="btn icon-modify" data-bs-toggle="modal" data-bs-target="#modify-modal" data-modify-type="standard-access">
                    <i class="bi bi-pencil-square icon-edit"></i>
                  </button>

              </td>
            </tr>
-->

          </table>
        </div>



        <div class="container-inner">
          <div class="pagination">
            <!--a href="#" ><i class="bi bi-arrow-left"></i></a>
            <a href="#"class="active">1</a>
            <a href="#">2</a>
            <a href="#">3</a>
            <a href="#">4</a>
            <a href="#">5</a>
            <a href="#">6</a>
            <a href="#"><i class="bi bi-arrow-right"></i></a-->

					<?

					$page_string = "view=$view&key_word=$key_word&key_CTGSEQ=$key_CTGSEQ&column=$column&mode=$mode&switched=$getSWHStr";
					$paging = new PAGE('page',$total_count,$list_count,$page_count,$page,$page_string,'#c71930','','','#c71930','');

					?>
	
	          </div>
        </div>


<!--
        <div class="row text-center">
          <div class="col-sm-4 item-inner">
          <a class="btn-sub" href="#">LIST</a>
         </div>
        </div>
-->





      </div>

        

    </section>



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

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



<script>
      /**
 * Request type on click
 */
 on('show.bs.modal', '#myModalDailyRecord', function(event) {
    select('#myModalDailyRecord #modify-type').value = event.relatedTarget.getAttribute('data-modify-type')
  })

</script>

<!-- Modal modify Form -->
<div id="myModalDailyRecord" class="modal fade customer-info">
  <div class="modal-dialog" role="document">
    <div class="modal-content modal-content-dailyRecord">
    	
    </div><!-- modal-content ends -->
  </div><!-- modal-dialog ends -->
</div>
<!-- Modal modify Form Ends -->


<?

$time_htmlend = microtime(true);
$timehtmlStr = " [".round(($time_htmlend - $time_start),2)."]";

addLog ("add", "ORDER LIST".$timeStr.$timehtmlStr, "VIEW", $lguserid, $query, $lgno);

?>