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

header("Content-type: application/vnd.ms-excel"); 
header("Content-Disposition: attachment; filename=".date('YmdHis')."_exportdata.xls"); 
header("Content-Description: PHP4 Generated Data"); 

echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";

$func->checkLevelModal(7);

/* ============================================================
   Workbook / Worksheet / Table OPEN
   ============================================================ */
echo "<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" ";
echo "xmlns:o=\"urn:schemas-microsoft-com:office:office\" ";
echo "xmlns:x=\"urn:schemas-microsoft-com:office:excel\" ";
echo "xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" ";
echo "xmlns:html=\"http://www.w3.org/TR/REC-html40\">\n";

echo "<Worksheet ss:Name=\"reportdata\">\n";
echo "<Table>\n";



if ($actionStr == "CUSTOMER") {

    // Header row
    echo "<Row>";
    for ($ii = 0; $ii < sizeof($export_customer); $ii++) {
        foreach ($customerArray as $key => $value) {
            if ($key == $export_customer[$ii]) {
                echo "<Cell><Data ss:Type=\"String\">$value</Data></Cell>\n";
            }
        }
    }
    echo "</Row>\n";

    // Customer list
    $query = "SELECT * FROM tbl_customer WHERE c_uid != '' ORDER BY c_uid DESC";
    $result = $jdb->nQuery($query, "list error");

    $cnt = 0;

    while ($list = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

        echo "<Row>";
        $strNote = "";

        foreach ($export_customer as $col) {

            if ($col == 'c_maincontainer') {
                echo "<Cell><Data ss:Type=\"String\">" . $arrBin[$list[$col]] . "</Data></Cell>\n";
            }

            else if ($col == 'c_driveruid') {
                $qry_driver = "SELECT m_initial FROM tbl_member WHERE m_uid = " . $list[$col];
                $rt_driver = $jdb->fQuery($qry_driver, "query error");
                echo "<Cell><Data ss:Type=\"String\">" . $rt_driver['m_initial'] . "</Data></Cell>\n";
            }

            else if ($col == 'c_area') {
                $qry_city = "SELECT a_text FROM tbl_area WHERE a_city = '" . $list['c_city'] . "'";
                $rt_city = $jdb->fQuery($qry_city, "query error");
                echo "<Cell><Data ss:Type=\"String\">" . $rt_city['a_text'] . "</Data></Cell>\n";
            }

            else if (
                $col == 'c_form_eu' ||
                $col == 'c_form_corsia' ||
                $col == 'c_contractdate' ||
                $col == 'c_installdate' ||
                $col == 'c_schedulebasic' ||
                $col == 'c_fpickup' ||
                $col == 'c_removaldate' ||
                $col == 'c_createddate' ||
                $col == 'c_deleteddate' ||
                $col == 'c_forceddate' ||
                $col == 'c_fullquantitydate' ||
                $col == 'c_lastpickupdate' ||
                $col == 'c_lastpaiddate' ||
                $col == 'c_orderdate' ||
                $col == 'c_inactivedate' ||
                $col == 'c_exchangedate' ||
                $col == 'c_switchformdate'
            ) {
                if (trim($list[$col]) == "N/A") $toDateStr = $list[$col];
                else if (trim($list[$col]) != "") $toDateStr = $func->convertFormat($list[$col], 3);
                else $toDateStr = "";

                echo "<Cell><Data ss:Type=\"String\">" . $toDateStr . "</Data></Cell>\n";
            }

            else if ($col == 'n_customeruid') {

                $query_note = "
                    SELECT * FROM tbl_note
                    WHERE n_customeruid = '" . $list['c_uid'] . "' 
                      AND n_status != 'D'
                    ORDER BY n_uid DESC
                ";

                $result_note = $jdb->nQuery($query_note, "note error");

                while ($list_note = mysqli_fetch_array($result_note, MYSQLI_ASSOC)) {

                    $n_noteSTR = str_replace("\\", "", strip_tags(trim($list_note['n_note'])));
                    $n_createddateSTR = $func->convertFormat($list_note['n_createddate'], 1);

                    $qry_writer = "SELECT m_firstname, m_lastname FROM tbl_member WHERE m_uid = '" . $list_note['n_memberuid'] . "'";
                    $rt_writer = $jdb->fQuery($qry_writer, "writer error");

                    $strNote .= "[" . $n_createddateSTR . "/" .
                        $rt_writer['m_firstname'] . " " . $rt_writer['m_lastname'] . "] " .
                        $n_noteSTR . "&#10;";
                }

                echo "<Cell><Data ss:Type=\"String\">" . $strNote . "</Data></Cell>\n";
            }

            else {
                echo "<Cell><Data ss:Type=\"String\">" . $list[$col] . "</Data></Cell>\n";
            }
        }

        echo "</Row>\n";

        if (($cnt++ % 300) == 0) flush(); // 300 raw 씩 출력
    }
} else if ($actionStr == "OILHISTORY") { 

			// customer
			$query = "SELECT * FROM tbl_customer ORDER BY c_accountno DESC ";
			$result = $jdb->nQuery($query, "list error");

			/* -------- HEADER ROW -------- */
			echo "<Row>";
			$sludgeFlag = 0;
			
			// column header
			for ($ii = 0; $ii < sizeof($export_oil); $ii++) {
				foreach ($oilhistoryArray as $key => $value) {
					if ($key == $export_oil[$ii]) {
						if ($key != "d_inputdate" && $key != "d_quantity" && $key != "d_sludge") {
							echo "<Cell><Data ss:Type=\"String\">$value</Data></Cell>\n";
						}
						if ($key == "d_sludge") $sludgeFlag = 1;
					}
				}
			}
			
			// date repeat
			$oil_period_toSTR = $oil_period_to . " 23:59:59";
			$period = new DatePeriod(
				new DateTime($oil_period_from),
				new DateInterval('P1D'),
				new DateTime($oil_period_toSTR)
			);

			// date header
			foreach ($period as $key => $value) {
				echo "<Cell><Data ss:Type=\"String\">" . $value->format('Y-m-d') . "</Data></Cell>\n";
				if ($sludgeFlag == 1) {
					echo "<Cell><Data ss:Type=\"String\">" . $value->format('Y-m-d') . "</Data></Cell>\n";
				}
			}

			echo "</Row>\n";

			/* -------- CUSTOMER LOOP -------- */
			$oil_period_toTMP = str_replace("-", "", $oil_period_to);
    		$oil_period_fromTMP = str_replace("-", "", $oil_period_from);

			$cnt = 0;

			while ($cus = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

			echo "<Row>";

			/* ===== customer information ===== */
			foreach ($export_oil as $col) {

				if ($col == 'c_maincontainer') {
					echo "<Cell><Data ss:Type=\"String\">" . $arrBin[$cus[$col]] . "</Data></Cell>\n";
				}

				else if ($col == 'c_driveruid') {
					$qry_driver = "SELECT m_initial FROM tbl_member WHERE m_uid = " . $cus[$col];
					$rt_driver = $jdb->fQuery($qry_driver, "query error");
					echo "<Cell><Data ss:Type=\"String\">" . $rt_driver['m_initial'] . "</Data></Cell>\n";
				}

				else if ($col == 'c_area') {
					$qry_city = "SELECT a_text FROM tbl_area WHERE a_city = '" . $cus['c_city'] . "'";
					$rt_city = $jdb->fQuery($qry_city, "query error");
					echo "<Cell><Data ss:Type=\"String\">" . $rt_city['a_text'] . "</Data></Cell>\n";
				}

				// date format
				else if (
					$col == 'c_form_eu' || $col == 'c_form_corsia' || $col == 'c_contractdate' ||
					$col == 'c_installdate' || $col == 'c_schedulebasic' || $col == 'c_fpickup' ||
					$col == 'c_removaldate' || $col == 'c_createddate' || $col == 'c_deleteddate' ||
					$col == 'c_forceddate' || $col == 'c_fullquantitydate' ||
					$col == 'c_lastpickupdate' || $col == 'c_lastpaiddate' ||
					$col == 'c_orderdate' || $col == 'c_inactivedate' ||
					$col == 'c_exchangedate' || $col == 'c_switchformdate'
				) {

					if (trim($cus[$col]) == "N/A") $toDateStr = $cus[$col];
					else if (trim($cus[$col]) != "") $toDateStr = $func->convertFormat($cus[$col], 3);
					else $toDateStr = "";

					echo "<Cell><Data ss:Type=\"String\">" . $toDateStr . "</Data></Cell>\n";
				}

				else if ($col != "d_inputdate" && $col != "d_quantity" && $col != "d_sludge") {
					echo "<Cell><Data ss:Type=\"String\">" . $cus[$col] . "</Data></Cell>\n";
				}
			}


			/* ===== Oil History ===== */
			$qry_oil = "SELECT * FROM tbl_daily 
						WHERE d_customeruid = '{$cus['c_uid']}' AND d_status = 'F'
						AND (d_orderdate BETWEEN '$oil_period_fromTMP' AND '$oil_period_toTMP')";

			$rt_oil = $jdb->nQuery($qry_oil, "list error");

			$oilData = [];
			$sludgeData = [];

			while ($oil = mysqli_fetch_array($rt_oil, MYSQLI_ASSOC)) {
				$oilData[$oil['d_orderdate']] = $oil['d_quantity'];

				if ($sludgeFlag == 1) {
					$sludgeData[$oil['d_orderdate']] = $oil['d_sludge'];
				}
			}


			/* ===== dialy ===== */
			foreach ($period as $key => $value) {

				$d = $value->format('Ymd');

				if (isset($oilData[$d])) {
					echo "<Cell><Data ss:Type=\"Number\">" . $oilData[$d] . "</Data></Cell>\n";
				} else {
					echo "<Cell><Data ss:Type=\"String\"></Data></Cell>\n";
				}

				if ($sludgeFlag == 1) {
					if (isset($sludgeData[$d])) {
						echo "<Cell><Data ss:Type=\"String\">" . $sludgeData[$d] . "</Data></Cell>\n";
					} else {
						echo "<Cell><Data ss:Type=\"String\"></Data></Cell>\n";
					}
				}
			}

			echo "</Row>\n";


        	if (($cnt++ % 300) == 0) flush(); // 300 raw 씩 출력
    }


} else if ($actionStr == "ORDER") { 

    $d_orderdate = str_replace("-", "", $d_orderdate);

    // Header row
    echo "<Row>";
    foreach ($orderArray as $key => $value) {
        echo "<Cell><Data ss:Type=\"String\">" . $value . "</Data></Cell>\n";
    }
    echo "</Row>\n";

    $add_query = " ORDER BY d_ordertype DESC, d_name ASC ";

    $query = "SELECT * FROM tbl_daily
              WHERE d_orderdate = '$d_orderdate' 
                AND d_driveruid = '$d_driveruid' " . $add_query;

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

    $cnt = 0;

    while ($list = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

        // Map columns to variables ($d_name, $d_maincontainer, ...)
        foreach ((array)$list as $key => $value) {
            $$key = $value;
        }

        $d_nameSTR            = str_replace("\\", "", $d_name);
        $d_maincontainerSTR   = $arrBin[$d_maincontainer];

        $qry_driver   = "SELECT m_initial FROM tbl_member WHERE m_uid = " . $d_driveruid;
        $rt_driver    = $jdb->fQuery($qry_driver, "query error");
        $d_driveruidSTR = $rt_driver['m_initial'];

        $d_containerSTR      = str_replace("\\", "", $d_container);
        $d_locationSTR       = str_replace("\\", "", $d_location);
        $d_paymenttypeSTR    = $arrPaymenttype[$d_paymenttype];
        $d_addressSTR        = str_replace("\\", "", $d_address);
        $d_citySTR           = str_replace("\\", "", $d_city);
        $d_lastpickupdateSTR = $func->convertFormat($d_lastpickupdate, 3);
        $d_visitdateSTR      = $func->convertFormat($d_visitdate, 3);

        $d_paystatusSTR = $arrPaidStatus[$d_paystatus];
        if ($d_paystatus == "P") {
            $d_paystatusSTR = $d_paystatusSTR . " ($" . $d_payamount . ")";
        }

        $d_estquantitySTR = number_format(floatval($d_estquantity));
        $d_quantitySTR    = number_format(floatval($d_quantity));

        // This year / last year quantity
        $getThisYear = date("Y");
        $getLastYear = date("Y", strtotime('last year'));

        $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 = '" . $d_customeruid . "' 
              AND d_status = 'F'
        ";

        $rt_sum       = $jdb->fQuery($qry_sum, "fetch query error");
        $getThisYearQ = number_format(floatval($rt_sum['THISYEAR']));
        $getLastYearQ = number_format(floatval($rt_sum['LASTYEAR']));

        if ($d_fullcycleflag == 1) {
            $d_fullcycleSTR = $d_fullcycleforced;
        } else {
            $d_fullcycleSTR = $d_fullcycle;
        }

        // Data row
        echo "<Row>";
        foreach ($orderArray as $key => $value) {
            // $key is something like 'd_nameSTR', 'd_driveruidSTR', etc.
            $cellValue = isset($$key) ? $$key : "";
            echo "<Cell><Data ss:Type=\"String\">" . $cellValue . "</Data></Cell>\n";
        }
        echo "</Row>\n";

        $list_number--;

        if (($cnt++ % 300) == 0) flush(); // 300 raw 씩 출력
    }
} else if ($actionStr == "OILHISTORYSUM") {

    // Header row
    echo "<Row>";
    foreach ($oilHistorySUMArray as $key => $value) {
        echo "<Cell><Data ss:Type=\"String\">" . $value . "</Data></Cell>\n";
    }
    echo "</Row>\n";

    if ($searchtype == "D" && $searchDriver) {
        $qrySTR = " (c.c_driveruid = '" . $searchDriver . "') ";
    } else {
        $qrySTR = " (c.c_uid = d.d_customeruid) ";
    }

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

    $add_srchquery = "";
    $add_query .= " ORDER BY MAX(d.d_visitdate) DESC, d.d_accountno DESC ";

    $query = "
        SELECT *, MAX(d.d_uid) AS maxuid
        FROM tbl_daily d
        WHERE d.d_customeruid != '' 
          AND d.d_status = 'F'
          AND d.d_customeruid IN (
                SELECT c.c_uid 
                FROM tbl_customer c 
                WHERE " . $qrySTR . $status_query . "
          ) 
          " . $add_srchquery . "
        GROUP BY d.d_accountno
        " . $add_query;

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

    while ($list = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

        foreach ((array)$list as $key => $value) {
            $$key = $value;
        }

        $qry_maxuid = "SELECT * FROM tbl_daily WHERE d_uid = '$maxuid'";
        $rt_maxuid = $jdb->fQuery($qry_maxuid, "fetch query error");

        $max_sludgeSTR = preg_replace('/[^A-Za-z0-9\-]/', '', $rt_maxuid['d_sludge']);
        $max_sludgeSTR = ($max_sludgeSTR != "") ? $max_sludgeSTR . "%" : "";

        $max_nameSTR = str_replace("\\", "", $rt_maxuid['d_name']);
        $max_addressSTR = str_replace("\\", "", $rt_maxuid['d_address']);
        $max_accountnoSTR = str_replace("\\", "", $rt_maxuid['d_accountno']);

        $max_cycle = str_replace("\\", "", $rt_maxuid['d_cycle']);
        $max_paymenttype = str_replace("\\", "", $rt_maxuid['d_paymenttype']);
        $max_rateSTR = $rt_maxuid['d_rate'];

        $qry_dvr = "SELECT m_initial FROM tbl_member WHERE m_uid = '" . $rt_maxuid['d_driveruid'] . "'";
        $rt_dvr = $jdb->fQuery($qry_dvr, "fetch query error");
        $max_driverSTR = $rt_dvr['m_initial'];

        $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();
        $day = $dt->format('j');
        $dt->modify('first day of -2 month');
        $dt->modify('+' . (min($day, $dt->format('t')) - 1) . ' days');
        $get3Mon = $dt->format('Ym');

        $dt = new DateTime();
        $day = $dt->format('j');
        $dt->modify('first day of -3 month');
        $dt->modify('+' . (min($day, $dt->format('t')) - 1) . ' days');
        $get4Mon = $dt->format('Ym');

        $qry_sum = "
            SELECT 
                SUM(CASE WHEN d_visitdate LIKE '" . $get1Mon . "%' THEN d_quantity ELSE 0 END) AS MON_1,
                SUM(CASE WHEN d_visitdate LIKE '" . $get2Mon . "%' THEN d_quantity ELSE 0 END) AS MON_2,
                SUM(CASE WHEN d_visitdate LIKE '" . $get3Mon . "%' THEN d_quantity ELSE 0 END) AS MON_3,
                SUM(CASE WHEN d_visitdate LIKE '" . $get4Mon . "%' THEN d_quantity ELSE 0 END) AS MON_4,
                SUM(CASE WHEN d_visitdate LIKE '" . $get1_12Mon . "%' THEN d_quantity ELSE 0 END) AS YEAR_1
            FROM tbl_daily
            WHERE d_customeruid = '" . $rt_maxuid['d_customeruid'] . "' 
              AND d_status = 'F'
        ";

        $rt_sum = $jdb->fQuery($qry_sum, "fetch query error");

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

        echo "<Row>";
        foreach ($oilHistorySUMArray as $key => $value) {
            $cellValue = isset($$key) ? $$key : "";
            echo "<Cell><Data ss:Type=\"String\">" . $cellValue . "</Data></Cell>\n";
        }
        echo "</Row>\n";

        if (($cnt++ % 300) == 0) flush(); // 300 raw 씩 출력
    }
} else if ($actionStr == "RECEIPT") {

    echo "<Row>";
    foreach ($receiptArray as $key => $value) {
        echo "<Cell><Data ss:Type=\"String\">" . $value . "</Data></Cell>\n";
    }
    echo "</Row>\n";

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

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

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

    $add_srchquery = "";
    $add_query .= " ORDER BY d.d_visitdate DESC, d.d_name ASC ";

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

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

    $cnt = 0;

    while ($list = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

        foreach ((array)$list as $key => $value) {
            $$key = $value;
        }

        $d_visitdateSTR = $func->convertFormat($d_visitdate, 3);
        $d_nameSTR = str_replace("\\", "", $d_name);
        $d_addressSTR = str_replace("\\", "", $d_address);
        $d_accountnoSTR = str_replace("\\", "", $d_accountno);

        $qry_dvr = "SELECT m_initial FROM tbl_member WHERE m_uid = '" . $d_driveruid . "'";
        $rt_dvr = $jdb->fQuery($qry_dvr, "fetch query error");
        $d_driverSTR = $rt_dvr['m_initial'];

        echo "<Row>";
        foreach ($receiptArray as $colKey => $colValue) {
            $cellValue = isset($$colKey) ? $$colKey : "";
            echo "<Cell><Data ss:Type=\"String\">" . $cellValue . "</Data></Cell>\n";
        }
        echo "</Row>\n";

        if (($cnt++ % 300) == 0) flush(); // 300 raw 씩 출력
    }
} else if ($actionStr == "FORECAST") {

    $list_number = 1;

    echo "<Row>";
    foreach ($forecastArray as $key => $value) {
        echo "<Cell><Data ss:Type=\"String\">" . $value . "</Data></Cell>\n";
    }
    echo "</Row>\n";

    if ($c_type_r == 'R') {

        $orderdate = str_replace("-", "", $orderdate);

        $qry_r = "
            SELECT *
            FROM tbl_request
            WHERE r_driveruid = '$org_driveruid'
              AND r_status = 'A'
              AND r_requestdate = '$orderdate'
            ORDER BY r_uid DESC";

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

        while ($list = mysqli_fetch_array($rt_r, MYSQLI_ASSOC)) {

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

            foreach ((array)$rt_rc as $key => $value) {
                $$key = $value;
            }

            $list_numberSTR = "R";
            $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_fullquantityActual = round(floatval($c_fullquantity + ($dDiff * $c_fullquantitydaily)));
            $c_fullquantitySTR = number_format($c_fullquantityActual);

            $c_fullcycleSTR = $c_fullcycle;
            $getThisYear = date("Y");
            $getLastYear = date("Y", strtotime('-1 year'));

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

            $rt_sum = $jdb->fQuery($qry_sum, "fetch query error");

            $getThisYearQ = number_format(floatval($rt_sum['THISYEAR']));
            $getLastYearQ = number_format(floatval($rt_sum['LASTYEAR']));

            echo "<Row>";
            foreach ($forecastArray as $key => $value) {
                $cellValue = isset($$key) ? $$key : "";
                echo "<Cell><Data ss:Type=\"String\">" . $cellValue . "</Data></Cell>\n";
            }
            echo "</Row>\n";

            flush();
        }
    }

    if ($c_type_p == 'P') {

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

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

        while ($list = mysqli_fetch_array($rt_s, MYSQLI_ASSOC)) {

            foreach ((array)$list as $key => $value) {
                $$key = $value;
            }

            $list_numberSTR = "S";
            $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_fullquantityActual = round(floatval($c_fullquantity + ($dDiff * $c_fullquantitydaily)));
            $c_fullquantitySTR = number_format($c_fullquantityActual);

            $c_fullcycleSTR = $c_fullcycle;
            $getThisYear = date("Y");
            $getLastYear = date("Y", strtotime('-1 year'));

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

            $rt_sum = $jdb->fQuery($qry_sum, "fetch query error");

            $getThisYearQ = number_format(floatval($rt_sum['THISYEAR']));
            $getLastYearQ = number_format(floatval($rt_sum['LASTYEAR']));

            echo "<Row>";
            foreach ($forecastArray as $key => $value) {
                $cellValue = isset($$key) ? $$key : "";
                echo "<Cell><Data ss:Type=\"String\">" . $cellValue . "</Data></Cell>\n";
            }
            echo "</Row>\n";

            flush();
        }
    }

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

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

    while ($list = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

        foreach ((array)$list as $key => $value) {
            $$key = $value;
        }

        if ($c_schedule == 'Will Call') {
            $list_numberSTR = "W";
        } else if ($c_schedule != 'Will Call' && $c_schedule != 'None') {
            $list_numberSTR = "S";
        } else {
            $list_numberSTR = $list_number;
        }

        $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_fullquantityActual = round(floatval($c_fullquantity + ($dDiff * $c_fullquantitydaily)));
        $c_fullquantitySTR = number_format($c_fullquantityActual);

        if ($c_fullcycleflag == 1) {
            $c_fullcycleSTR = $c_fullcycleforced;
        } else {
            $c_fullcycleSTR = $c_fullcycle;
        }

        $getThisYear = date("Y");
        $getLastYear = date("Y", strtotime('-1 year'));

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

        $rt_sum = $jdb->fQuery($qry_sum, "fetch query error");

        $getThisYearQ = number_format(floatval($rt_sum['THISYEAR']));
        $getLastYearQ = number_format(floatval($rt_sum['LASTYEAR']));

        echo "<Row>";
        foreach ($forecastArray as $key => $value) {
            $cellValue = isset($$key) ? $$key : "";
            echo "<Cell><Data ss:Type=\"String\">" . $cellValue . "</Data></Cell>\n";
        }
        echo "</Row>\n";

        $list_number++;
        flush();
    }
}

/* ============================================================
   Closing XML tags
   ============================================================ */

addLog ("add", "EXPORT", $actionStr, $_SESSION['ss_ID'], $query, "");

echo "</Table>\n";
echo "</Worksheet>\n";
echo "</Workbook>\n";

?>