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

/*
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";
}

$time_start = microtime(true);

$add_srchquery = "";
$isSearchPerformed = false;

// searching logic
if($searchtype == "R" && trim($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%'))";
    $isSearchPerformed = true;
} else if ($searchtype == "D" && $searchDriver) {
    $isSearchPerformed = true;
}

// sorting
if($switch) {
    $switched = $func -> switchOrder($switch, $switched);
    $sort_sql = " ORDER BY $switch $switched "; 
    $switched = $switch . "^" . $switched;
} else if($switched) {
    $switched1 = explode("^", $switched);
    $sort_sql = " ORDER BY $switched1[0] $switched1[1] ";
} else {
    $sort_sql = " ORDER BY max_visitdate DESC, d.d_accountno DESC ";
}

$getSWHStr = $switched;

// 레벨 9 처리
if ($_SESSION['ss_LEVEL'] == 9) {
    $searchDriver = $_SESSION['ss_UID'];
    $isSearchPerformed = true; 
}

// 검색 조건 설정
$qrySTR = " (c.c_uid = d.d_customeruid) ";
if ($searchDriver) {
    $qrySTR .= " AND (c.c_driveruid = '$searchDriver') ";
}

// Account Status
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') ";
}

// 날짜 변수
$get1Mon = date("Ym");
$get1_12Mon = date("Y");
$dt = new DateTime(); $day = $dt->format('j');
$dt->modify('first day of -1 month'); $dt->modify('+' . (min($day, $dt->format('t')) - 1) . ' days');
$get2Mon = $dt->format('Ym');
$dt = new DateTime(); $dt->modify('first day of -2 month'); $get3Mon = $dt->format('Ym');
$dt = new DateTime(); $dt->modify('first day of -3 month'); $get4Mon = $dt->format('Ym');

$strList = "";
$total_count = 0;

if ($isSearchPerformed) {
    // 1. 전체 카운트
    $query_cnt = "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_status = 'F' AND $qrySTR $status_query $add_srchquery";
    $total_count = $jdb->rQuery($query_cnt, "Count Error");

    if(!$page) $page = 1;
    if(!$list_count) $list_count = (int)$INIT_PAGECNT;
    if($list_count <= 0) $list_count = 20;
    $start_number = $list_count * ($page-1);

    // 2. 메인 리스트 쿼리
    $query = "SELECT 
                d.d_accountno, 
                MAX(d.d_visitdate) as max_visitdate,
                c.c_name, c.c_address, c.c_accountno, c.c_paymentcycle, c.c_paymenttype, c.c_sludge, c.c_rate, c.c_uid,
                m.m_initial, m.m_region,
                SUM(CASE WHEN d.d_visitdate LIKE '$get1Mon%' THEN d.d_quantity ELSE 0 END) AS MON_1,
                SUM(CASE WHEN d.d_visitdate LIKE '$get2Mon%' THEN d.d_quantity ELSE 0 END) AS MON_2,
                SUM(CASE WHEN d.d_visitdate LIKE '$get3Mon%' THEN d.d_quantity ELSE 0 END) AS MON_3,
                SUM(CASE WHEN d.d_visitdate LIKE '$get4Mon%' THEN d.d_quantity ELSE 0 END) AS MON_4,
                SUM(CASE WHEN d.d_visitdate LIKE '$get1_12Mon%' THEN d.d_quantity ELSE 0 END) AS YEAR_1
              FROM tbl_daily d
              INNER JOIN tbl_customer c ON d.d_customeruid = c.c_uid
              LEFT JOIN tbl_member m ON c.c_driveruid = m.m_uid
              WHERE d.d_status = 'F' AND $qrySTR $status_query $add_srchquery
              GROUP BY 
                d.d_accountno, c.c_name, c.c_address, c.c_accountno, c.c_paymentcycle, 
                c.c_paymenttype, c.c_sludge, c.c_rate, c.c_uid, m.m_initial, m.m_region
              $sort_sql
              LIMIT $start_number, $list_count";

    $result = $jdb->nQuery($query, "Main List Error");
    $list_number = $total_count - (($page-1)*$list_count);

    if ($result) {
        while($list = mysqli_fetch_assoc($result)) {
            $max_nameSTR = str_replace("\\", "", $list['c_name']);
            $max_addressSTR = str_replace("\\", "", $list['c_address']);
            $max_accountnoSTR = str_replace("\\", "", $list['c_accountno']);
            $max_cycle = $arrPaymentCycle[str_replace("\\", "", $list['c_paymentcycle'])];
            $max_paymenttype = str_replace("\\", "", $list['c_paymenttype']);
            $max_sludgeSTR = preg_replace('/[^A-Za-z0-9\-]/', '', $list['c_sludge']);

            $get1MonQ = number_format(floatval($list['MON_1']));
            $get2MonQ = number_format(floatval($list['MON_2']));
            $get3MonQ = number_format(floatval($list['MON_3']));
            $get4MonQ = number_format(floatval($list['MON_4']));
            $get2_4MonQ = number_format(floatval($list['MON_2'] + $list['MON_3'] + $list['MON_4']));
            $get1_12MonQ = number_format(floatval($list['YEAR_1']));

            $strList .= "
                <tr>
                  <td>$list_number</td>
                  <td onclick=\"location.href='/index_intranet.php?view=oilhistory_detail&d_customeruid=".$list['c_uid']."&searchtype=$searchtype&searchDriver=$searchDriver&page=$page&key_word=".urlencode($key_word)."&cstatus=$cstatus&switched=$getSWHStr'\" style='cursor:pointer;'><b class='customer-info-detail'>$max_nameSTR</b></td>
                  <td>$max_accountnoSTR </td>
                  <td>$max_paymenttype </td>
                  <td>".$list['c_rate']." </td>
                  <td>$max_sludgeSTR </td>
                  <td>$max_cycle </td>
                  <td>$max_addressSTR </td>
                  <td>".$list['m_region']." </td>
                  <td>".$list['m_initial']." </td>
                  <td style='text-align: right;'>$get1MonQ </td>
                  <td style='text-align: right;'>$get2MonQ </td>
                  <td style='text-align: right;'>$get3MonQ </td>
                  <td style='text-align: right;'>$get4MonQ </td>
                  <td style='text-align: right;'>$get2_4MonQ </td>
                  <td style='text-align: right;'>$get1_12MonQ </td>
                </tr>";
            $list_number--;
        }
    }
}

if(!$isSearchPerformed) {
    $strList = "<tr><td colspan='16' align=center height='100' style='color:#888; font-size:18px;'>Please search for a restaurant or select a driver.</td></tr>";
} else if ($total_count < 1) {
    $strList = "<tr><td colspan='16' align=center height='30'><B>No Data</B></td></tr>";
}

// 상단 통계
if ($isSearchPerformed && $searchDriver && ($searchtype == "D" || $_SESSION['ss_LEVEL'] == 9)) {
    $qry_stats = "SELECT 
                    SUM(CASE WHEN d_visitdate LIKE '$get1Mon%' THEN d_quantity ELSE 0 END) AS T1,
                    SUM(CASE WHEN d_visitdate LIKE '$get1Mon%' AND d_form_eu != '' AND d_form_eu <= d_orderdate THEN d_quantity ELSE 0 END) AS E1,
                    SUM(CASE WHEN d_visitdate LIKE '$get2Mon%' THEN d_quantity ELSE 0 END) AS T2,
                    SUM(CASE WHEN d_visitdate LIKE '$get2Mon%' AND d_form_eu != '' AND d_form_eu <= d_orderdate THEN d_quantity ELSE 0 END) AS E2,
                    SUM(CASE WHEN d_visitdate LIKE '$get3Mon%' THEN d_quantity ELSE 0 END) AS T3,
                    SUM(CASE WHEN d_visitdate LIKE '$get3Mon%' AND d_form_eu != '' AND d_form_eu <= d_orderdate THEN d_quantity ELSE 0 END) AS E3,
                    SUM(CASE WHEN d_visitdate LIKE '$get4Mon%' THEN d_quantity ELSE 0 END) AS T4,
                    SUM(CASE WHEN d_visitdate LIKE '$get4Mon%' AND d_form_eu != '' AND d_form_eu <= d_orderdate THEN d_quantity ELSE 0 END) AS E4,
                    SUM(CASE WHEN d_visitdate LIKE '$get1_12Mon%' THEN d_quantity ELSE 0 END) AS TY,
                    SUM(CASE WHEN d_visitdate LIKE '$get1_12Mon%' AND d_form_eu != '' AND d_form_eu <= d_orderdate THEN d_quantity ELSE 0 END) AS EY
                  FROM tbl_daily d
                  INNER JOIN tbl_customer c ON d.d_customeruid = c.c_uid
                  WHERE c.c_driveruid = '$searchDriver' $status_query AND d.d_status = 'F'";
    $rs_stats = $jdb->fQuery($qry_stats, "Stats Error"); 
    
    $get1MonTOT = number_format(floatval($rs_stats['T1'])); $get1MonEU = number_format(floatval($rs_stats['E1']));
    $get2MonTOT = number_format(floatval($rs_stats['T2'])); $get2MonEU = number_format(floatval($rs_stats['E2']));
    $get3MonTOT = number_format(floatval($rs_stats['T3'])); $get3MonEU = number_format(floatval($rs_stats['E3']));
    $get4MonTOT = number_format(floatval($rs_stats['T4'])); $get4MonEU = number_format(floatval($rs_stats['E4']));
    $get1_12MonTOT = number_format(floatval($rs_stats['TY'])); $get1_12MonEU = number_format(floatval($rs_stats['EY']));
    
    $qry_dvr_info = "SELECT m_initial, m_region FROM tbl_member WHERE m_uid = '$searchDriver'";
    $rt_dvr = $jdb->fQuery($qry_dvr_info, "Driver Info Error");
}

// 드라이버 셀렉트박스 목록
$qry_driver = "SELECT * FROM tbl_member WHERE m_level = 9 AND m_regionuid != '' ORDER by m_region ASC ";
$rt_driver = $jdb->nQuery($qry_driver, "Driver List Error"); 
$c_driveruidSTR = "";
while($lt_driver = @mysqli_fetch_assoc($rt_driver)) {
    $selectStr = ($lt_driver['m_uid'] == $searchDriver) ? "selected" : "";
    $c_driveruidSTR .= "<option value='".$lt_driver['m_uid']."' $selectStr>".$lt_driver['m_region']." (".$lt_driver['m_initial'].")</option>";
}

if ($searchtype == 'D') $setDisplayRStr = " style='DISPLAY:none'";
else if ($searchtype == 'R' || $searchtype == '') $setDisplayDStr = " style='DISPLAY:none'";

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

<SCRIPT language=javascript>
function viewCont(){
    var obj = document.getElementById("searchtype").value; 
    if (obj == 'R') {
        document.getElementById("driverfnc").style.display="none";
        document.getElementById("restnamefnc").style.display="inline";
    } else if (obj == 'D') {
        document.getElementById("driverfnc").style.display="inline";
        document.getElementById("restnamefnc").style.display="none";
    }
}
</SCRIPT>

<SCRIPT TYPE="TEXT/JAVASCRIPT">
$(document).ready(function(){
    $("#form_cstatus").change(function(){
        document.getElementById("searchtypeaccount").value = document.getElementById("searchtype").value; 
        $('#form_cstatus').submit();
    }); 
});
</SCRIPT>

<main id="main" class="main">
    <div class="breadcrumbs">
      <div class="container">
        <div class="d-flex justify-content-between align-items-center">
          <h2>OIL HISTORY</h2>
          <ol>
            <li><a href="index_intranet.php">HOME</a></li>
            <li>OIL HISTORY</li>
          </ol>
        </div>
      </div>
    </div>

    <section class="page">
      <div class="container" data-aos="fade-up">
        <div class="wrap-border">
            <FORM METHOD=POST NAME=form2 action='<?=$_SERVER["PHP_SELF"]?>' class="form-customer">
            <INPUT TYPE=HIDDEN NAME=view VALUE='oilhistory_list'>
            <input type=hidden name=cstatus value="<?=$cstatus?>">
            <table class="table-search-customer">
              <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":"";?>>Region (Driver)</option>
                    <? } ?>
                  </select>
                </td>
                <td class="td-title">
                    <div id="restnamefnc" <?=$setDisplayRStr?>>
                        <div class="search-container">
                            <input name="key_word" id="key_word" type="text" placeholder="Search.." value="<?=$key_word?>">
                            <button type="submit"><i class="bi-search"></i></button>
                        </div>
                    </div>
                    </FORM>
                    <div id="driverfnc" <?=$setDisplayDStr?>>
                        <FORM METHOD=POST NAME=form3 action='<?=$_SERVER["PHP_SELF"]?>'>
                        <INPUT TYPE=HIDDEN NAME=view VALUE='oilhistory_list'>
                        <input type=hidden name=cstatus value="<?=$cstatus?>">
                        <INPUT TYPE=HIDDEN NAME=searchtype VALUE='D'>
                            <select name="searchDriver" id="searchDriver" class="custom-select" onChange="this.form.submit()">
                            <option value=''>Select</option>
                            <?=$c_driveruidSTR?>
                            </select>       
                        </FORM> 
                    </div>
                </td>
                <td style="text-align:left;padding-right:20px;">
                    <div class="search-container">
                        <FORM method=post id="form_cstatus" name="form_cstatus" action='<?=$_SERVER["PHP_SELF"]?>' class="form-forecast-search">
                            <input type=hidden name=view value='oilhistory_list'>
                            <input type=hidden name=switched value="<?=$getSWHStr?>">
                            <input type=hidden name=page value="<?=$page?>">
                            <input type=hidden name=key_word value="<?=$key_word?>">
                            <input type=hidden name=column value="<?=$column?>">
                            <input type=hidden name=sorting_type value="<?=$sorting_type?>">
                            <input type=hidden name=switch value="<?=$switch?>">
                            <INPUT TYPE=HIDDEN NAME=searchtype id=searchtypeaccount VALUE='<?=$searchtype?>'>
                            <input TYPE=hidden NAME=searchDriver VALUE="<?=$searchDriver?>">
                            <select name="cstatus" id="cstatus" class="custom-select1">
                              <option value='A' <?=($cstatus == "A")?"selected":"";?>>Active Account</option>
                              <option value='I' <?=($cstatus == "I")?"selected":"";?>>Inactive Account</option>
                              <option value='T' <?=($cstatus == "T")?"selected":"";?>>All Account</option>
                            </select>    
                        </FORM>    
                    </div>                        
                </td>
                <td align="right">
                    <? 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="OILHISTORYSUM">
                    <input TYPE=hidden NAME=searchtype VALUE="<?=$searchtype?>">
                    <input TYPE=hidden NAME=searchDriver VALUE="<?=$searchDriver?>">
                    <input type=hidden name=cstatus value="<?=$cstatus?>">
                    <button type='submit' class="btn-add text-center">DOWNLOAD</button>
                    </FORM>
                    <? } ?>
                </td>
              </tr>
            </table>
        </div>
        <? if ($isSearchPerformed && $searchDriver && (($searchtype == "D" && $setTag == "ENABLED") || ($_SESSION['ss_LEVEL'] == 9))) { ?>
        <div class="container section-oil-history-details" data-aos="fade-up">
          <h5 class="h5-title">Region (Driver) : <span><?=$rt_dvr['m_region']?> (<?=$rt_dvr['m_initial']?>)</span></h5>
          <table class="tb-info-box oil-qty-tb">
            <tr>
              <td class="td-title-info">Period</td>
              <td class="td-title-info">1M</td>
              <td class="td-title-info">2M</td>
              <td class="td-title-info">3M</td>
              <td class="td-title-info">4M</td>
              <td class="td-title-info">Yearly</td>
            </tr>
            <tr>
              <td class="td-text-info">ISCC Oil Quantity</td>
              <td class="td-text-info"><span><?=$get1MonTOT?></span> / <span class="sp-oil"><?=$get1MonEU?></span></td>
              <td class="td-text-info"><span><?=$get2MonTOT?></span> / <span class="sp-oil"><?=$get2MonEU?></span></td>
              <td class="td-text-info"><span><?=$get3MonTOT?></span> / <span class="sp-oil"><?=$get3MonEU?></span></td>
              <td class="td-text-info"><span><?=$get4MonTOT?></span> / <span class="sp-oil"><?=$get4MonEU?></span></td>
              <td class="td-text-info"><span><?=$get1_12MonTOT?></span> / <span class="sp-oil"><?=$get1_12MonEU?></span></td>
            </tr>
          </table>
        </div>
        <? } ?>

        <div class="wrap-overflow forecast-info">
          <table class="tb-list">
            <tr>
                <th>No</th>
                <th class="td-restaurant">Restaurant Name</th>
                <th class="oil-account">Account</th>
                <th class="oil-payment">Payment</th>
                <th class="oil-rate">Rate</th>
                <th class="oil-sludge">Sludge</th>
                <th class="oil-pcycle">P. Cycle</th>
                <th class="td-address">Address</th>
                <th class="oil-driver">Region</th>
                <th>Driver</th>
                <th class="oil-1m">1M</th>
                <th class="oil-2m">2M</th>
                <th class="oil-3m">3M</th>
                <th class="oil-4m">4M</th>
                <th class="oil-2m4m">2-4M</th>
                <th class="oil-yearly">Yearly</th>
            </tr>
            <?=$strList?>
          </table>
        </div>

        <div class="container-inner">
          <div class="pagination">
            <?
            if ($total_count > 0) {
                $page_string = "view=$view&searchtype=$searchtype&searchDriver=$searchDriver&key_word=".urlencode($key_word)."&cstatus=$cstatus&switched=$getSWHStr";
                $paging = new PAGE('page',$total_count,$list_count,$page_count,$page,$page_string,'#c71930','','','#c71930','');
            }
            ?>
          </div>
        </div>
      </div>
    </section>
</main>

<?
$time_htmlend = microtime(true);
$timehtmlStr = " [".round(($time_htmlend - $time_start),2)."]";
@addLog ("add", "OIL HISTORY LIST".$timeStr.$timehtmlStr, "VIEW", $lguserid, "Query end", $lgno);
?>