<?

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

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

for($i=0; $i<sizeof($_POST); $i++) {
	list($key, $value) = each($_POST);
	$$key = $value;

	if(is_array($value))
	{
		$count = 10;
		for($i = 0; $i < $count; $i ++) {
			if ($value[$i]) echo "ARRAY[$key][$value[$i]]<br>";
		}
	}
	else 	echo "[$key][$value]<br>";
	//print_r($_POST);
}

//exit;
*/

// Download 기능 제한 (Admin : 1, Manager : 3, Staff : 5 만 가능)
$permit = array("1", "5", "6", "7", "9");
if (in_array($_SESSION['ss_LEVEL'], $permit)) {
    $setTag = "ENABLED";
}
else $setTag = "DISABLED";	

//$add_query .= "tbl_groups   INNER JOIN naloxca_bbs.tbl_customer ON (tbl_groups.g_uid = tbl_customer.m_gid) ";
$add_srchquery = "";
$add_query = "";


// searching
if($searchtype == "R" && $key_word) {

	$key_wordStr = urldecode(trim($key_word));
	$add_srchquery .= " AND  ((d.d_name LIKE '%$key_wordStr%') OR (d.d_accountno LIKE '%$key_wordStr%') OR (d.d_address LIKE '%$key_wordStr%'))";
}
else if ($searchtype == "D" && $searchDriver) {
	//$add_srchquery .= " AND  d.d_driveruid = '$searchDriver' ";
}

// Search Date
if(strlen($searchDate) == 10) {
	$searchDateSTR = str_replace("-", "", $searchDate);
	$add_srchquery .= " AND (d.d_visitdate LIKE '$searchDateSTR%') ";
}

// 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.d_visitdate DESC, d.d_name ASC ";
}

$getSWHStr = $switched;

// $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 ";

if ($searchtype == "D" && $searchDriver) {
	$qrySTR = " AND (d.d_driveruid = '".$searchDriver."') ";
}

if ($_SESSION['ss_LEVEL'] == 9) {
	$qrySTR = " AND (d.d_driveruid = '".$_SESSION['ss_UID']."') ";
}


// Account Status
$cstatus = 'T';

if ($cstatus == 'T') $status_query = " AND (c.c_status = 'A' OR c.c_status = 'I') ";
else if ($cstatus == 'I') $status_query = " AND (c.c_status = 'I') ";
else {
	$cstatus = 'A';
	$status_query = " AND (c.c_status = 'A') ";
}

// 모든 경우에 receipt 는 다보여져야 함 (2023.12.05)
$status_query = "";

// CASH 계정에서 다른 계정으로 Payment 변경시 안보이는 문제 (2024.01.12)
// 아래 query에서 AND d.d_paymenttype = 'CA' 제거함

//total record
$query = "SELECT count(d.d_accountno) 
					FROM tbl_daily d
					WHERE d.d_customeruid != '' AND d.d_status = 'F' AND d.d_paystatus = 'P' ". $qrySTR. "
						AND d.d_customeruid IN (SELECT c.c_uid FROM tbl_customer c WHERE (c.c_uid = d.d_customeruid) ".$status_query. ") " . $add_allquery . $add_srchquery . $add_query;

/*
SELECT count(distinct d.d_accountno) 
FROM tbl_daily d
INNER join tbl_customer c ON (d.d_customeruid = c.c_uid)
WHERE d.d_customeruid != '' AND d.d_status = 'F' 
ORDER BY MAX(d.d_visitdate) DESC, d.d_accountno DESC 

SELECT count(distinct d.d_accountno) 
FROM tbl_daily d
INNER join tbl_customer c ON (d.d_driveruid = c.c_driveruid)
WHERE d.d_customeruid != '' AND d.d_status = 'F' AND d.d_driveruid = '17' 
ORDER BY MAX(d.d_visitdate) DESC, d.d_accountno DESC 
*/

$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);

// CASH 계정에서 다른 계정으로 Payment 변경시 안보이는 문제 (2024.01.12)
// 아래 query에서 AND d.d_paymenttype = 'CA' 제거함

$add_query .= " LIMIT $start_number, $INIT_PAGECNT";
$query = "SELECT *	FROM  tbl_daily d
					WHERE d.d_customeruid != '' AND d.d_status = 'F' AND d.d_paystatus = 'P' ". $qrySTR. "
					AND d.d_customeruid IN (SELECT c.c_uid FROM tbl_customer c WHERE (c.c_uid = d.d_customeruid) ".$status_query. ") ". $add_srchquery . $add_query;
//echo "<br><br><br><br>[$query]<br><br>";

$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;
	}

	$d_visitdateSTR = $func -> convertFormat ($d_visitdate, 3);

	$qry_maxuid = "SELECT * FROM tbl_customer WHERE c_uid = '$d_customeruid' ";
	$rt_maxuid = $jdb->fQuery($qry_maxuid, "fetch query error");
	//echo "<br><br><br><br><br>[$qry_maxuid]";
	
	$max_sludgeSTR = preg_replace('/[^A-Za-z0-9\-]/', '', $rt_maxuid['c_sludge']);
	if ($max_sludgeSTR != "") $max_sludgeSTR = $max_sludgeSTR;
	else $max_sludgeSTR = "";
	
	$max_nameSTR = str_replace("\\", "", $rt_maxuid['c_name']);
	$max_addressSTR = str_replace("\\", "", $rt_maxuid['c_address']);
	$max_accountnoSTR = str_replace("\\", "", $rt_maxuid['c_accountno']);
	
	$qry_dvr = "SELECT m_initial FROM tbl_member WHERE m_uid = '".$d_driveruid."' ";
	$rt_dvr = $jdb->fQuery($qry_dvr, "fetch query error");

	//$qry_eu = "SELECT c_form_eu FROM tbl_customer WHERE c_driveruid = '".$rt_maxuid['d_driveruid']."' ";
	//$rt_eu = $jdb->fQuery($qry_eu, "fetch query error");

	if ($_SESSION['ss_LEVEL'] <= 6) {
		$putNoteScript = "
		              <button type=\"button\" class=\"receiptNoteClass btn-note\" data-bs-toggle=\"modal\" data-bs-target=\"#myModalReceiptNoteClass\" data-duid=\"$d_uid\" data-receipt-note-type=\"standard-access\">
              <i class=\"bi-sticky icon-rnote\"></i>
              </button>
		";
	}
	else {
		$putNoteScript = "";
	}

	$strList .= "
          <tr>
            <td>$list_number</td>
            <td>$d_visitdateSTR</td>
            <td><b>$max_nameSTR</b></td>
            <td>$max_accountnoSTR</td>
            <td>$max_addressSTR</td>
            <td>".$rt_dvr['m_initial']."</td>
            <td style=\"text-align:right; padding-right:20px;\">$d_quantity</td>
            <td style=\"text-align:right; padding-right:50px;\">$d_payamount</td>
            <td class=\"opt-icon\">

              <button type=\"button\" class=\"receiptClass btn-view\" data-bs-toggle=\"modal\" data-bs-target=\"#myModalReceiptClass\" data-duid=\"$d_uid\" data-receipt-view-type=\"standard-access\">
                <i class=\"bi-search icon-rview\"></i>
              </button>

            </td>
            <td class=\"opt-icon\">
            	
						".$putNoteScript."
              
            </td>
          </tr>
	";

	$list_number--;
}


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


// 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"); 

while($lt_driver=mysqli_fetch_array($rt_driver, MYSQLI_ASSOC)) {

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



// 검색시 조건 유지를 위해
if ($searchtype == 'D') $setDisplayRStr = " style='DISPLAY:none'";
else if ($searchtype == 'R' || $searchtype == '') $setDisplayDStr = " style='DISPLAY:none'";

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

?>


	
<SCRIPT language=javascript>
		
function viewCont(){
	  obj = document.getElementById("searchtype").value; 
	  
	//ttt= obj.checked;
	//alert(obj);

	if (obj == 'R') {
		//document.memberInfo.partnerfnc.style.display = "none";
		document.getElementById("driverfnc").style.display="none";
		document.getElementById("restnamefnc").style.display="inline";
		//alert('0');
	}	
	else if ((obj == 'D')) {
		//document.memberInfo.partnerfnc.style.display = "inline";
		document.getElementById("driverfnc").style.display="inline";
		document.getElementById("restnamefnc").style.display="none";
		//alert('4');
	}

}

</SCRIPT>


<SCRIPT TYPE="TEXT/JAVASCRIPT">
$(document).ready(function(){


    $("#form_cstatus").change(function(){
        //$(this).css("background-color", "#FFD2A6");
        document.getElementById("searchtypeaccount").value = document.getElementById("searchtype").value; 
        $('#form_cstatus').submit();
    }); 
		
});

</SCRIPT>

<SCRIPT LANGUAGE=JAVASCRIPT>
<!--
function goKeyword(f){
    var f = document.form1;

			f.searchDate.value = document.getElementById('searchDate').value;
			f.submit();
}

function goDriver(f){
    var f = document.form2;

			f.searchDate.value = document.getElementById('searchDate').value;
			f.submit();
}

function goSearch(f){
    var f = document.form3;

			f.searchtype.value = document.getElementById('searchtype').value;
			f.searchDriver.value = document.getElementById('searchDriver').value;
			f.key_word.value = document.getElementById('key_word').value;
			f.submit();
}
//-->
</SCRIPT>


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

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

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

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

  <section class="page">


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

					<FORM METHOD=POST NAME=form1 action='<?=$_SERVER["PHP_SELF"]?>' class="form-customer">
					<INPUT TYPE=HIDDEN NAME=view VALUE='receipt_list'>
					<INPUT TYPE=HIDDEN NAME=cstatus VALUE="<?=$cstatus?>">
					<INPUT TYPE=HIDDEN NAME=searchDate VALUE=''>
					
          <table class="table-search-receipt">
            <tr>
              <td class="td-title">
                  <select name="searchtype" id="searchtype" class="custom-select" onChange="viewCont();">
                    <option value="R" <?=($searchtype=="R" || $searchtype=="")?"selected":"";?>>Restaurant</option>

<? if ($_SESSION['ss_LEVEL'] != 9) { ?>
                    <option value="D" <?=($searchtype=="D")?"selected":"";?>>Driver</option>
<? } ?>

                  </select>
              </td>
                <td class="td-title">

										<div id="restnamefnc" <?=$setDisplayRStr?>>
		                    <div class="search-container">
		                        <input name="key_word" id="key_word" class="" type="text" value="<?=htmlspecialchars($key_wordStr, ENT_QUOTES)?>" placeholder="Search.."  onChange="goKeyword()">
		                        <button type="submit"><i class="bi-search"></i></button>
		                    </div>
										</div>
    
          </FORM>

										<div id="driverfnc" <?=$setDisplayDStr?>>
													<FORM METHOD=POST NAME=form2 action='<?=$_SERVER["PHP_SELF"]?>'>
													<INPUT TYPE=HIDDEN NAME=view VALUE='receipt_list'>
													<INPUT TYPE=HIDDEN NAME=cstatus VALUE="<?=$cstatus?>">
													<INPUT TYPE=HIDDEN NAME=searchDate VALUE=''>
													<INPUT TYPE=HIDDEN NAME=searchtype VALUE='D'>
																<select name="searchDriver" id="searchDriver" class="custom-select" onChange="goDriver()">
																<option value=''>Select</option>
																<?=$c_driveruidSTR?>
																</select>		
													</FORM>	
										</div>

                </td>              

              <td class="td-title">
													<FORM METHOD=POST NAME=form3 ACTION='<?=$_SERVER["PHP_SELF"]?>'>
													<INPUT TYPE=HIDDEN NAME=view VALUE='receipt_list'>
													<input TYPE=HIDDEN NAME=cstatus VALUE="<?=$cstatus?>">
													<INPUT TYPE=HIDDEN NAME=searchtype VALUE=''>
													<INPUT TYPE=HIDDEN NAME=searchDriver VALUE=''>
													<INPUT TYPE=HIDDEN NAME=key_word VALUE=''>

													<input name="searchDate" id="searchDate" class="custom-select" type="date" placeholder="<?=date('Y-m-d')?>" value="<?=$searchDate?>" onChange="goSearch();">

													</FORM>  	
              </td>
              
              <td align="right">
                  <!--button type="submit" class="btn-add">SEARCH</button-->
									<? if ($_SESSION['ss_LEVEL'] < 7) { ?>
									<FORM NAME=exportorder id=exportorder METHOD=POST ACTION=/doc/export_process.php >
									<input type=hidden name=mode value="export">
									<input type=hidden name=actionStr value="RECEIPT">
									<input TYPE=hidden NAME=searchtype VALUE="<?=$searchtype?>">
									<input TYPE=hidden NAME=searchDriver VALUE="<?=$searchDriver?>">
									<input type=hidden name=cstatus value="<?=$cstatus?>">
									<button type='submit' href="#" class="btn-add text-center">DOWNLOAD</button>
									</FORM>
									<? } ?>                  
              </td>

            </tr>

          </table>


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



      

      <div class="wrap-overflow receipt-info">
        <table class="tb-list">
          <tr>
            <th>No</th>
            <th>Date</th>
            <th>Restaurant Name</th>
            <th>Account</th>
            <th>Address</th>
            <th>Driver</th>
            <th style="text-align:right; padding-right:20px;">Oil Qty.</th>
            <th style="text-align:right; padding-right:50px;">Paid</th>
            <th colspan="2">Option</th>
          </tr>
          

<?=$strList?>

<!--
          <tr>
            <td>1</td>
            <td>Restaurant Name</td>
            <td>GD221150</td>
            <td>145 Kingston Rd.</td>
            <td>D.S</td>
            <td>300.00</td>
            <td>$200.00</td>
            <td class="opt-icon">
              
              <button type="button" class="btn-view" data-bs-toggle="modal" data-bs-target="#receipt-view-modal" data-receipt-view-type="standard-access">
                <i class="bi-search icon-rview"></i>
              </button>

            </td>
            <td class="opt-icon">
            	
              <button type="button" class="btn-note" data-bs-toggle="modal" data-bs-target="#receipt-note-modal" data-receipt-note-type="standard-access">
              <i class="bi-sticky icon-rnote"></i>
              </button>
              
            </td>
          </tr>

          <tr>
            <td>1</td>
            <td>Restaurant Name</td>
            <td>GD221150</td>
            <td>145 Kingston Rd.</td>
            <td>D.S</td>
            <td>300.00</td>
            <td>$200.00</td>
            <td class="opt-icon"><i class="bi-search icon-rview"></i></td>
            <td class="opt-icon"><i class="bi-sticky icon-rnote"></i></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&searchtype=$searchtype&searchDriver=$searchDriver&searchDate=$searchDate&key_word=$key_word&key_CTGSEQ=$key_CTGSEQ&column=$column&mode=$mode&cstatus=$cstatus&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>
		
$(document).ready(function(){

		 $('.receiptClass').click(function(){
		   
          var duid = $(this).data('duid');
    
			   // AJAX request
			   $.ajax({
					    url: 'lib/receipt_lib.php',
					    type: 'post',
					    data: {duid: duid},
					    success: function(response){ 
					      // Add response in Modal body
					      $('.modal-content-receiptClass').html(response);

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


  });
</script>


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



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

		$('.receiptNoteClass').click(function(){
		 
		   var duid = $(this).data('duid');

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

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

</script>


<!-- Modal receipt-note Form -->
<div id="myModalReceiptNoteClass" class="modal fade customer-info">
  <div class="modal-dialog" role="document">
    <div class="modal-content modal-content-receiptNoteClass">

    </div><!-- modal-content ends -->
  </div><!-- modal-dialog ends -->
</div><!-- receipt-note-modal ends -->
      

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