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

// 기능 제한 (Admin : 1, Staff : 5, Accounting : 6, Driver : 9 만 가능)
$permit = array("1", "3", "5", "6", "7", "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();
}



$APPLYDATE = "20231122000000";

$add_srchquery = "";
$add_query = "";
$add_subqry = "";
$add_hsubqry = "";
$add_dsubqry = "";

// 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 ($startYear == "" || $startMonth == "") {
	$startYear = date('Y');
	$startMonth = date('m');
}
// ---- cutoff_date 계산 (Balance 기준일) ----
$selectedYM = $startYear . '-' . $startMonth;
$nowYM      = date('Y-m');

if ($selectedYM == $nowYM) {
    $cutoff_ymd = date('Ymd'); // 이번달 조회면 "오늘"
} else {
    // 그 달 말일
    $cutoff_ymd = date('Ymd', strtotime($startYear . '-' . $startMonth . '-01 last day of this month'));
}

$apply_ymd = substr($APPLYDATE, 0, 8);           // '20231122'
$cutoff_visit_to = $cutoff_ymd . "235959";       // tbl_daily용 (방문일 datetime)

// 
if ($searchDriver == "") $searchDriver = "ALL";

if ($startYear != "" && $startMonth != "") $add_subqry = " AND (d_orderdate LIKE '$startYear$startMonth%') ";
else $add_subqry = "AND (d_orderdate LIKE '".date('Y').date('m')."%') ";

if ($searchDriver != "") {
	if ($searchDriver == "ALL") {
		$add_subqry .= "";
		$add_hsubqry .= "";
		$add_dsubqry .= "";
	}
	else {
		$add_subqry .= " AND m_uid = '".$searchDriver."' ";
		$add_hsubqry .= " AND h_driveruid = '".$searchDriver."' ";
		$add_dsubqry .= " AND d_driveruid = '".$searchDriver."' ";
	}
}
else {
	$add_subqry .= "";
	$add_hsubqry .= "";
	$add_dsubqry .= "";
}
// 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 (d_driveruid = m_uid) 
						WHERE d_orderdate >= '".substr($APPLYDATE,0,8)."' AND d_orderdate <= '".date('Ymd')."' ". $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_driveruid, m_initial
					FROM tbl_daily 
					INNER JOIN tbl_member ON (d_driveruid = m_uid) 
					WHERE d_orderdate >= '".substr($APPLYDATE,0,8)."' AND d_orderdate <= '".date('Ymd')."' ". $add_subqry . "
					GROUP BY d_orderdate,d_driveruid " . $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_driveruid = '".$d_driveruid."' ";
	$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_driveruid = '".$d_driveruid."' 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_driveruid = '".$d_driveruid."' 
								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_driveruid = '".$d_driveruid."' 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_driveruid = '".$d_driveruid."' 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_driveruid = '".$d_driveruid."' 
								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_driveruid = '".$d_driveruid."' 
								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_driveruid = '".$d_driveruid."' 
								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, '.', ',');
	
	
	if ($d_orderdate < substr($APPLYDATE,0,8)) {
		$openingbalance = "0.00";
		$balance = "0.00";
	}
	
	$strList .= "
            <tr>
              <td>$list_number</td>
              <td>$d_orderdateSTR</td>
              <td>$m_initial</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>              
            </tr>

	";

	$list_number--;
	
}


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

// Get Cash In, Return, Gas SUM
$qry_sum = "SELECT 
							SUM(h_balance_in) AS CASHINSUM, 
							SUM(h_balance_r) AS CASHRETURNSUM,
							SUM(h_balance_g) AS GASSUM
						FROM  tbl_memberhis 
						WHERE h_date LIKE '".$startYear.$startMonth."%' ". $add_hsubqry
						;
//echo "LIST_TOT[$qry_sum]<br>";							
$rt_sum = $jdb->fQuery($qry_sum, "fetch query error");

$getCASHINSUM = number_format(floatval($rt_sum['CASHINSUM']), 2, '.', ',');
$getCASHRETURNSUM = number_format(floatval($rt_sum['CASHRETURNSUM']), 2, '.', ',');
$getGASSUM = number_format(floatval($rt_sum['GASSUM']), 2, '.', ',');

// Get Cash Out SUM
$qry_cashouttoday = "SELECT SUM(d_payamount) FROM tbl_daily 
										WHERE (d_visitdate LIKE '".$startYear.$startMonth."%' )
										" . $add_dsubqry . "
										AND d_paystatus = 'P' AND d_status = 'F' ";
							
$getCASHOUTSUM = $jdb->rQuery($qry_cashouttoday, "fetch query error");
$getCASHOUTSUM = number_format(floatval($getCASHOUTSUM), 2, '.', ',');

// ---- Total Balance (as of cutoff) 계산 ----
// Cash In (누적)
$qry_total_in = "SELECT SUM(h.h_balance_in)
					FROM tbl_memberhis h
					INNER JOIN tbl_member m ON (h.h_driveruid = m.m_uid)
					WHERE m.m_level = 9
					AND m.m_status = 'A'
					AND h.h_date >= '".$apply_ymd."'
					AND h.h_date <= '".$cutoff_ymd."'
					".$add_hsubqry;
$total_in = $jdb->rQuery($qry_total_in, "fetch query error");

// Cash Return (누적)
$qry_total_rt = "SELECT SUM(h_balance_r)
					FROM tbl_memberhis h
					INNER JOIN tbl_member m ON (h.h_driveruid = m.m_uid)
					WHERE m.m_level = 9
					AND m.m_status = 'A'
					AND h.h_date >= '".$apply_ymd."'
					AND h.h_date <= '".$cutoff_ymd."'
					".$add_hsubqry;
$total_rt = $jdb->rQuery($qry_total_rt, "fetch query error");

// Cash Out (누적)  ※ d_visitdate 는 ymdHis 이라 cutoff는 235959까지
$qry_total_out = "SELECT SUM(d.d_payamount)
					FROM tbl_daily d
					INNER JOIN tbl_member m ON (d.d_driveruid = m.m_uid)
					WHERE m.m_level = 9
					AND m.m_status = 'A'
					AND d.d_visitdate >= '".$APPLYDATE."'
					AND d.d_visitdate <= '".$cutoff_visit_to."'
					".$add_dsubqry."
					AND d.d_paystatus = 'P'
					AND d.d_status = 'F'";

$total_out = $jdb->rQuery($qry_total_out, "fetch query error");

// Total Balance = In - Return - Out
$getTOTALBALANCE = floatval($total_in) - floatval($total_rt) - floatval($total_out);
$getTOTALBALANCE = number_format($getTOTALBALANCE, 2, '.', ',');
	
// Get Driver Info
$qry_driver = "SELECT * FROM tbl_member WHERE m_level = 9 AND m_status = 'A' ORDER by m_initial ASC ";
$rt_driver = $jdb->nQuery($qry_driver, "list error"); 

$c_driveruidSTR = "
								<option value='ALL' $selectStr>ALL</option>";
								
while($lt_driver=mysqli_fetch_array($rt_driver, MYSQLI_ASSOC)) {

	if ($lt_driver['m_uid'] == $searchDriver) { 
			$selectStr = "selected";
			$getDriverInitial = $lt_driver['m_initial'];
	}
	else $selectStr = "";
	
	$c_driveruidSTR .= "
								<option value='".$lt_driver['m_uid']."' $selectStr>".$lt_driver['m_initial']."</option>";
								
}

//echo "<br><br><br><br><br>###[$searchDriver]###";

if ($searchDriver == "ALL") $getDriverInitial = "ALL";

	
//  년, 월 표시 로직
for($i='2023'; $i<=date('Y'); $i++) {
	if ($i == $startYear) $setTmp = "selected";
	else if ($startYear == "" && $i == date('Y')) {
		$setTmp = "selected";
		//$startYear = date(Y);
	}
	else $setTmp = "";
	$strYear .= " <option value='$i' $setTmp>$i</option>";
}

			
for($i=1; $i<=12; $i++) {
	$j = sprintf("%02d", $i);
	if ($i == $startMonth) $setTmp = "selected";
	else if ($startMonth == "" && $i == date('m')) {
		$setTmp = "selected";
		//$startMonth = date(m);
	}
	else $setTmp = "";	
	$strMonth .= " <option value='$j' $setTmp>$j</option>";
}


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

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

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

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

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

    <section class="page">


      <div class="expense-wrap" data-aos="fade-up">



        <div class="wrap-border">
          
          <FORM METHOD=POST NAME=form2 action='<?=$_SERVER["PHP_SELF"]?>'>
          	<INPUT TYPE=HIDDEN NAME=view VALUE='report_expense'>
          	
          <table class="table-search-customer-2">
            <tr>
              <td class="td-title">
									<select name="searchDriver" id="searchDriver" class="custom-select">
									<?=$c_driveruidSTR?>
									</select>		
              </td>

              <td class="td-title">
                <select name="startYear" id="startYear" class="custom-select">
                  <?=$strYear?>
                </select>               
              </td>
              
              <td class="td-title">
                <select name="startMonth" id="startMonth" class="custom-select">
                  <?=$strMonth?>
                </select>            
              </td>
              
              <td align="right">
                  <button type="submit" class="btn-add">SEARCH</button>
              </td>

            </tr>

          </table>
  
           

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

        <div class="container section-oil-history-details" data-aos="fade-up">
          <table class="tb-info-box oil-qty-tb">
            <tr>
              <td class="td-title-info">PERIOD</td>
              <td class="td-title-info">DRIVER</td>
              <td class="td-title-info">CASH IN</td>
              <td class="td-title-info">CASH OUT</td>
              <td class="td-title-info">CASH RETURN</td>
			  <td class="td-title-info">BALANCE</td>
              <td class="td-title-info">GAS</td>
            </tr>
            <tr>
              <td class="td-text-info"><?=$startYear?>-<?=$startMonth?></td>
              <td class="td-text-info"><?=$getDriverInitial?></td>
              <td class="td-text-info"><span class="sp-oil"><?=$getCASHINSUM?></span></td>
              <td class="td-text-info"><span class="sp-oil"><?=$getCASHOUTSUM?></span></td>
              <td class="td-text-info"><span class="sp-oil"><?=$getCASHRETURNSUM?></span></td>
			  <td class="td-text-info"><span class="sp-oil"><?=$getTOTALBALANCE?></span></td>
              <td class="td-text-info"><span class="sp-oil"><?=$getGASSUM?></span></td>
            </tr>
          </table>
        </div>
        
        
        <div class="wrap-overflow forecast-info">
          <table class="tb-list">
            <tr>
                <th>No</th>
                <th>Date</th>
                <th>Driver</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>
            </tr>

<?=$strList?>

<!--
            <tr>
              <td>1</td>
              <td>2023-09-20</td>
              <td>D.S</td>
              <td style="text-align:right; padding-right:20px;">$ 200.00</td>
              <td style="text-align:right; padding-right:20px;">$ 200.00</td>
              <td style="text-align:right; padding-right:20px;">$ 200.00</td>
              <td style="text-align:right; padding-right:20px;">$ 200.00</td>
              <td style="text-align:right; padding-right:20px;">$ 200.00</td>
              <td style="text-align:right; padding-right:20px;">$ 200.00</td>              
            </tr>
            
            <tr>
              <td>1</td>
              <td>2023-09-20</td>
              <td>D.S</td>
              <td style="text-align:right; padding-right:20px;">$ 200.00</td>
              <td style="text-align:right; padding-right:20px;">$ 200.00</td>
              <td style="text-align:right; padding-right:20px;">$ 200.00</td>
              <td style="text-align:right; padding-right:20px;">$ 200.00</td>
              <td style="text-align:right; padding-right:20px;">$ 200.00</td>
              <td style="text-align:right; padding-right:20px;">$ 200.00</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&startYear=$startYear&startMonth=$startMonth&searchDriver=$searchDriver";
					$paging = new PAGE('page',$total_count,$list_count,$page_count,$page,$page_string,'#c71930','','','#c71930','');

					?>
					            
          </div>
        </div>



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

    </section>

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