<?php

//the global file operation
include("../public/impOpreation.php");
//global varable
global $showoutside;

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.php");

//here the db files that include in the file
include("../public/include_dao.php");

//Tamweenbill
require_once('../models/dao/TamweenbillDAO.class.php');
require_once('../models/dto/Tamweenbill.class.php');
require_once('../models/mysql/TamweenbillMySqlDAO.class.php');
require_once('../models/mysql/ext/TamweenbillMySqlExtDAO.class.php');
//Tamweenda3mstatus
require_once('../models/dao/Tamweenda3mstatusDAO.class.php');
require_once('../models/dto/Tamweenda3mstatu.class.php');
require_once('../models/mysql/Tamweenda3mstatusMySqlDAO.class.php');
require_once('../models/mysql/ext/Tamweenda3mstatusMySqlExtDAO.class.php');
//Tamweenremainstatus
require_once('../models/dao/TamweenremainstatusDAO.class.php');
require_once('../models/dto/Tamweenremainstatu.class.php');
require_once('../models/mysql/TamweenremainstatusMySqlDAO.class.php');
require_once('../models/mysql/ext/TamweenremainstatusMySqlExtDAO.class.php');
//Client
require_once('../models/dao/ClientDAO.class.php');
require_once('../models/dto/Client.class.php');
require_once('../models/mysql/ClientMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientMySqlExtDAO.class.php');

require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');

//get the do the action
$do = $_GET['do'];
$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");
/* ======================
  Controller Name :-
  ======================== */

//here the global templates
$smarty->display("header.html");

//Tamweenbill
$tamweenBill = new Tamweenbill();
$tamweenBillDAO = new TamweenbillMySqlDAO();
$tamweenBillEX = new TamweenbillMySqlExtDAO();
//Tamweenda3mstatus
$tamweenDa3mStatus = new Tamweenda3mstatu();
$tamweenDa3mStatusDAO = new Tamweenda3mstatusMySqlDAO();
$tamweenDa3mStatusEX = new Tamweenda3mstatusMySqlExtDAO();
//Tamweenremainstatus
$tamweenRemainStatus = new Tamweenremainstatu();
$tamweenRemainStatusDAO = new TamweenremainstatusMySqlDAO();
$tamweenRemainStatusEX = new TamweenremainstatusMySqlExtDAO();

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();
//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientEX = new ClientMySqlExtDAO();

//check and use the condition that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");

//    $month = filter_input(INPUT_POST, 'month');
//    if (empty($month)) {
//        $month = date("Y-m");
//        $from = $month . "-01";
//        $daysInMonth = cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'));
//        $to = $month . "-" . $daysInMonth;
//    } else {
//        $from = $month . "-01";
//        $monthExplode = explode("-", $month);
//        $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $monthExplode[1], $monthExplode[0]);
//        $to = $month . "-" . $daysInMonth;
//    }

    $from = filter_input(INPUT_POST, 'from');
    $to = filter_input(INPUT_POST, 'to');

    $message = '';
    if (empty($from) && empty($to)) {
//        $from = date('Y-m-1');
//        $daysInMonth = cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'));
//        $to = date('Y-m-' . $daysInMonth);
        $from = $to = date('Y-m-d');
    }
    if (!empty($from) && !empty($to)) {
        $searchMonth = date('Y-m', strtotime($from));
        $searchMonthExplode = explode('-', $from);
        $searchMonthDays = cal_days_in_month(CAL_GREGORIAN, $searchMonthExplode[1], $searchMonthExplode[0]);

        $allDays = getDaysBetween2DatesIncludeAllMonth($from, $to);
        $smarty->assign("allDays", $allDays);

        $message = "من : $from الى : $to";
        $from = $from . " 00:00:00";
        $to = $to . " 23:59:59"; //" 23:59:59" this part to include all day in period =>$period = new DatePeriod(
        $noOfDays = 0;
        $period = new DatePeriod(
                new DateTime($from), new DateInterval('P1D'), new DateTime($to)
        );
        foreach ($period as $key => $value) {
            //var_dump($value->format('Y-m-d')); //this is the dates bettween
            $noOfDays++;
        }
        $message .= " , عدد الايام : $noOfDays";

        $smarty->assign("noOfDays", $noOfDays);

        $queryStringTamweenBill = " and billdate >= '" . $from . "' and billdate <= '" . $to . "' ";




        $fromExploded = explode('-', $from);
        $fromExploded[2] = "01";
        $from = implode('-', $fromExploded) . " 00:00:00";

        $toExploded = explode('-', $to);
        $toExploded[2] = cal_days_in_month(CAL_GREGORIAN, $toExploded[1], $toExploded[0]);
        $to = implode('-', $toExploded) . " 23:59:59";
        $queryStringTamweenBillAllMonth = " and billdate >= '" . $from . "' and billdate <= '" . $to . "' ";

        $reportData = $tamweenBillEX->getTakenDa3mReport($queryStringTamweenBillAllMonth, $queryStringTamweenBill);
        foreach ($reportData as $value) {
            $value->noOfDaysCalc = $searchMonthDays; //$noOfDays;
            if ($searchMonth == date('Y-m', strtotime($value->addDate))) {
                $value->noOfDaysCalc = ($searchMonthDays + 1) - (int) (explode('-', $value->addDate)[2]); //+1 to have day added in calculation
            }
        }

        $smarty->assign("reportData", $reportData);
    }
    $smarty->assign("message", $message);
    //here the smarty templates
    $smarty->display("tamweenreportsview/dailyinperiod.html");
} elseif ($do == "clientda3minperiod") {
    //here the permssion check
    include_once("../public/authentication.php");

    $allClients = $clientDAO->queryByCondition(0);
    $smarty->assign("allClients", $allClients);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $from = filter_input(INPUT_POST, 'from');
    $to = filter_input(INPUT_POST, 'to');
    $clientid = (int) filter_input(INPUT_POST, 'clientid');



    //set default values
    $message = '';
    if (empty($from) && empty($to)) {
        $from = $to = date('Y-m-d');
    }
    if (empty($clientid) || $clientid < 0) {
        $clientid = -2;
        $message .= "كل العملاء  - ";
    } elseif ($clientid > 0) {
        $client = $clientDAO->load($clientid);
        $queryStringTamweenBill .=" and tamweenbill.clientid = $clientid ";
        $message .= "عميل : $client->clientname  - ";
    }

    $searchMonth = date('Y-m', strtotime($from));
    $searchMonthExplode = explode('-', $from);
    $searchMonthDays = cal_days_in_month(CAL_GREGORIAN, $searchMonthExplode[1], $searchMonthExplode[0]);


    $message .= "الفترة من : $from الى : $to";
    $allDays = getDaysBetween2DatesIncludeAllMonth($from, $to);
    $smarty->assign("allDays", $allDays);
    ////////
    $from = $from . " 00:00:00";
    $to = $to . " 23:59:59"; //" 23:59:59" this part to include all day in period =>$period = new DatePeriod(
    $noOfDays = 0;
    $period = new DatePeriod(
            new DateTime($from), new DateInterval('P1D'), new DateTime($to)
    );
    foreach ($period as $key => $value) {
        //var_dump($value->format('Y-m-d')); //this is the dates bettween
        $noOfDays++;
    }

    $smarty->assign("noOfDays", $noOfDays);


    $queryStringTamweenBill .= " and billdate >= '" . $from . "' and billdate <= '" . $to . "' ";
    $reportData = $tamweenBillEX->getTakenDa3mReport22($queryStringTamweenBill);

    $totalShare = getTotalShare($reportData, $allDays, $searchMonth, $searchMonthDays);
    $smarty->assign("totalShare", $totalShare);
    $smarty->assign("message", $message);
    $smarty->assign("reportData", $reportData);
    ///////
    //here the smarty templates
    $smarty->display("tamweenreportsview/clientda3minperiod.html");
} elseif ($do == "clientremain") {
    //here the permssion check
    include_once("../public/authentication.php");

    $month = filter_input(INPUT_POST, 'month');
    if (empty($month)) {
        $month = date("Y-m");
        $from = $month . "-01";
        $daysInMonth = cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'));
        $to = $month . "-" . $daysInMonth;
    } else {
        $from = $month . "-01";
        $monthExplode = explode("-", $month);
        $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $monthExplode[1], $monthExplode[0]);
        $to = $month . "-" . $daysInMonth;
    }

//    $from = filter_input(INPUT_POST, 'from');
//    $to = filter_input(INPUT_POST, 'to');
//    $message = '';
//    if (empty($from) && empty($to)) {
//        $from = date('Y-m-1');
//        $daysInMonth = cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'));
//        $to = date('Y-m-' . $daysInMonth);
//    }
    if (!empty($from) && !empty($to)) {
        $searchMonth = date('Y-m', strtotime($from));
        $searchMonthExplode = explode('-', $from);
        $searchMonthDays = cal_days_in_month(CAL_GREGORIAN, $searchMonthExplode[1], $searchMonthExplode[0]);

        //get firstDayOfMonthSelected
        $x = explode('-', $from);
        $x[2] = "01";
        $firstDayOfMonthSelected = (implode('-', $x));
        $smarty->assign("firstDayOfMonthSelected", $firstDayOfMonthSelected);
        $joinRemainStatusQueryString = " and tamweenremainstatus.month = '" . $firstDayOfMonthSelected . "' and tamweenremainstatus.del = 0 ";

        $message = "من : $from الى : $to";
        $from = $from . " 00:00:00";
        $to = $to . " 23:59:59"; //" 23:59:59" this part to include all day in period =>$period = new DatePeriod(
        $noOfDays = 0;
        $period = new DatePeriod(
                new DateTime($from), new DateInterval('P1D'), new DateTime($to)
        );
        foreach ($period as $key => $value) {
            //var_dump($value->format('Y-m-d')); //this is the dates bettween
            $noOfDays++;
        }
        $message .= " , عدد الايام : $noOfDays";

        $smarty->assign("noOfDays", $noOfDays);

        $queryStringTamweenBill = " and billdate >= '" . $from . "' and billdate <= '" . $to . "' ";
        $reportData = $tamweenBillEX->getTakenDa3mReport3($queryStringTamweenBill, $joinRemainStatusQueryString);
        foreach ($reportData as $value) {
            $value->noOfDaysCalc = $noOfDays;
            if ($searchMonth == date('Y-m', strtotime($value->addDate))) {
                $value->noOfDaysCalc = ($searchMonthDays + 1) - (int) (explode('-', $value->addDate)[2]); //+1 to have day added in calculation
            }
        }
        $smarty->assign("reportData", $reportData);
    }
    $smarty->assign("message", $message);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    //here the smarty templates
    $smarty->display("tamweenreportsview/clientremain.html");
} elseif ($do == "clientremainsave") {
    //here the permssion check
    include_once("../public/authentication.php");
    try {
        saveStatus();
        header("location:?do=clientremain");
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
} elseif ($do == "sucess") {
//here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
//here the smarty templates
    $smarty->display("error.html");
}



$smarty->assign("customValidation", 1);
$smarty->assign("customTamween", 1);

//here the global templates
$smarty->display("footer.html");

/* ===============================
  function in this CONTROLLER
  ================================ */

function saveStatus($param) {
    global $tamweenRemainStatus;
    global $tamweenRemainStatusDAO;

    $itr = (int) filter_input(INPUT_POST, 'itr');
    $month = filter_input(INPUT_POST, 'firstDayOfMonthSelected');

    for ($i = 1; $i <= $itr; $i++) {
        $tamweenremainstatusid = (int) filter_input(INPUT_POST, 'tamweenremainstatusid' . $i);
        $clientid = (int) filter_input(INPUT_POST, 'clientid' . $i);
        $remainstatus = (int) filter_input(INPUT_POST, 'remainstatus' . $i);
        if ($clientid > 0 && !empty($month)) {
            $tamweenRemainStatus->clientid = $clientid;
            $tamweenRemainStatus->month = $month;
            $tamweenRemainStatus->remainstatus = $remainstatus;
            $tamweenRemainStatus->userid = $_SESSION['userid'];
            $tamweenRemainStatus->sysdate = date('Y-m-d H:i:s');
            $tamweenRemainStatus->del = 0;

            if ($tamweenremainstatusid > 0) {
                $tamweenRemainStatus->id = $tamweenremainstatusid;
                $tamweenRemainStatusDAO->update($tamweenRemainStatus);
            } else {
                $tamweenRemainStatusDAO->insert($tamweenRemainStatus);
            }
        }
    }
}

function getDaysBetween2DatesIncludeAllMonth($from, $to) {
    //this function to get days between two dates as months
    //eg "2021-01-20" to "2021-02-03" means to have the very start of from      to the very end of to
    //it will be like "2021-01-01" to "2021-02-28"
    $fromExploded = explode('-', $from);
    $fromExploded[2] = "01";
    $from = implode('-', $fromExploded);

    $toExploded = explode('-', $to);
    $toExploded[2] = cal_days_in_month(CAL_GREGORIAN, $toExploded[1], $toExploded[0]);
    $to = implode('-', $toExploded);



    $from = $from . " 00:00:00";
    $to = $to . " 23:59:59"; //" 23:59:59" this part to include all day in period =>$period = new DatePeriod(
    $noOfDays = 0;
    $period = new DatePeriod(
            new DateTime($from), new DateInterval('P1D'), new DateTime($to)
    );
    foreach ($period as $key => $value) {
        //var_dump($value->format('Y-m-d')); //this is the dates bettween
        $noOfDays++;
    }
    return $noOfDays;
}

function getTotalShare($reportData, $allDays, $searchMonth, $searchMonthDays) {

    $clientData = array();
    foreach ($reportData as $value) {
        $clientData[$value->clientid] = array('noOfPersonsDa3m' => $value->noOfPersonsDa3m, 'addDate' => $value->addDate);
    }

    //$totalNoOfPersonsDa3m = 0;
    $totalShare = 0;
    foreach ($clientData as $key => $value) {
        $totalNoOfPersonsDa3m = $value['noOfPersonsDa3m']; //+= $value['noOfPersonsDa3m'];

        $value['noOfDaysCalc'] = $searchMonthDays; //$noOfDays;
        if ($searchMonth == date('Y-m', strtotime($value['addDate']))) {
            $value['noOfDaysCalc'] = ($searchMonthDays + 1) - (int) (explode('-', $value['addDate'])[2]); //+1 to have day added in calculation
        }
        $totalShare += 5 * $value['noOfDaysCalc'] * $totalNoOfPersonsDa3m;
    }

    //$totalShare = 5 * $allDays * $totalNoOfPersonsDa3m;
    return $totalShare;
}

?>