<?php

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

// get the config file
include_once("../public/config.php");

//here the db files that include in the file
include("../public/include_dao.php");
//MCheck
require_once('../models/dao/MCheckDAO.class.php');
require_once('../models/dto/MCheck.class.php');
require_once('../models/mysql/MCheckMySqlDAO.class.php');
require_once('../models/mysql/ext/MCheckMySqlExtDAO.class.php');
//MProducthistory
require_once('../models/dao/MProducthistoryDAO.class.php');
require_once('../models/dto/MProducthistory.class.php');
require_once('../models/mysql/MProducthistoryMySqlDAO.class.php');
require_once('../models/mysql/ext/MProducthistoryMySqlExtDAO.class.php');

/* //Supplier
  require_once('../models/dao/SupplierDAO.class.php');
  require_once('../models/dto/Supplier.class.php');
  require_once('../models/mysql/SupplierMySqlDAO.class.php');
  require_once('../models/mysql/ext/SupplierMySqlExtDAO.class.php'); */

//MComreceipt
require_once('../models/dao/MComreceiptDAO.class.php');
require_once('../models/dto/MComreceipt.class.php');
require_once('../models/mysql/MComreceiptMySqlDAO.class.php');
require_once('../models/mysql/ext/MComreceiptMySqlExtDAO.class.php');

//MComreceiptdetail
require_once('../models/dao/MComreceiptdetailDAO.class.php');
require_once('../models/dto/MComreceiptdetail.class.php');
require_once('../models/mysql/MComreceiptdetailMySqlDAO.class.php');
require_once('../models/mysql/ext/MComreceiptdetailMySqlExtDAO.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');



//get the do the action
$do = $_GET['do'];

//here the global templates
$smarty->display("header.html");
//$smarty->display("maintennanceHeader.html");
//here goes the instances and general variables
//$mCheckDAO = new MCheckMySqlDAO();
$mCheckEX = new MCheckMySqlExtDAO();

$MProductHistory = new MProducthistory();
$MProductHistoryDAO = new MProducthistoryMySqlDAO();
$mProductHistoryEX = new MProducthistoryMySqlExtDAO();

//$supplierDAO = new SupplierMySqlDAO();

$MComreceipt = new MComreceipt();
$MComreceiptDAO = new MComreceiptMySqlDAO();
$MComreceiptEX = new MComreceiptMySqlExtDAO();


//Client
$Client = new Client();
$ClientDAO = new ClientMySqlDAO();
$ClientEX = new ClientMySqlExtDAO();


$MComreceiptDetailEX = new MComreceiptdetailMySqlExtDAO();
//check and use the condetion that suite this action
/* if (empty($do)||$do=="all") {


  $clientsData = getclient();
  $smarty->assign("clientsData", $clientsData);

  $checkData=$mCheckEX->queryByBranchEX2($_SESSION['branchId']);
  foreach($checkData as $row)
  {
  $data =$mProductHistoryEX->GetStatusOfSerialWithMaxDate($row->ourSerial);
  /*print_r('<pre>');
  print_r($data);
  print_r('</pre>'); */
/* 	$row->productHistoryStatus = $data->status;
  $row->stageFrom = $data->stageFrom;
  $row->m_stageTitle = $data->stageTitle;

  $myInitialCost=$MComreceiptDetailEX->getInitialCostByOurserialEX($row->ourSerial);
  $row->Initialcost = $myInitialCost;
  }

  //$suppliers=$supplierDAO->queryAll();
  $today = date("Y-m-d");
  $smarty->assign("today",$today);
  //$smarty->assign("suppliers",$suppliers);
  $smarty->assign("itr",count($checkData));
  $smarty->assign("checkData",$checkData);
  /*print_r('<pre>');
  print_r($checkData);
  print_r('</pre>'); */

/* if((!empty($clientid))  || (!empty($startDate) && !empty($endDate)) )
  {
  $message = " اسم العميل ".$clientname. "التاريخ: من: ".$startDate." إلى: ".$endDate;
  $smarty->assign("message",$message);

  show($clientid,$startDate, $endDate);
  }
  else
  {
  //showall();
  $today = date("Y-m-d");
  show($clientid,$today,$today);
  }

  $smarty->assign("title1",'الصيانة');
  $smarty->assign("title2",' تقرير التسليم');
  $smarty->assign("title3",' عرض المنتجات');
  $smarty->assign("link",'#');
  $smarty->display("maintennanceHeader.html");

  $smarty->display("deleveryReportView/deleveryReport.html");
  } */

if (empty($do) || $do == "all") {
    include_once("../public/authentication.php");

    $clientsData = getclient();
    $smarty->assign("clientsData", $clientsData);

    $clientname = $_REQUEST['clientid'];
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $recitID = $_POST["recitID"];
    if ((!empty($clientname)) || (!empty($startDate) && !empty($endDate))) {
        $message = " اسم العميل " . $clientname . "التاريخ: من: " . $startDate . " إلى: " . $endDate;
        $smarty->assign("message", $message);

        show($clientname, $startDate, $endDate, $recitID);
    } else {
        //showall();
        $today = date("Y-m-d");
        //show($clientname,$today,$today);
    }

    $smarty->assign("title1", 'الصيانة');
    $smarty->assign("title2", ' تقرير التسليم');
    $smarty->assign("title3", ' عرض المنتجات');
    $smarty->assign("link", '#');
    $smarty->display("maintennanceHeader.html");

    $smarty->display("deleveryReportView/deleveryReport.html");
} elseif ($do == "delever") {
    try {
        $itr = $_POST["itr"];
        for ($i = 1; $i <= $itr; $i++) {
            $done = $_POST["done" . $i];
            $ourSerial = $_POST["ourSerial" . $i];
            if (isset($done) && !empty($done) && isset($ourSerial) && !empty($ourSerial)) {
                //print_r($_POST["ourSerial".$i].'<br/>');
                //insert in ProductHistory
                insertProductHistory($ourSerial, 6, 11, 0, '', 0);
                updateCurrentStage(11, $ourSerial);

                $flag = checkIfComReceiptDone($ourSerial);
                if ($flag == 0) {
                    markAsDone($ourSerial);
                }

                //del in mcheck
                $mCheckEX->deleteUsingOurSerial($ourSerial);
            }
        }

        $note = " تمت العملية بنجاح";
        $url = "deleveryReportController.php?do=all";
        $smarty->assign('urldirect', $url);
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } catch (Exception $e) {
        $note = " لقد حدث خطأ";
        $url = "deleveryReportController.php?do=all";
        $smarty->assign('urldirect', $url);
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    }
} elseif ($do == "deleverandPay") {
    try {
        $itr = $_POST["itr"];
        for ($i = 1; $i <= $itr; $i++) {
            $done = $_POST["done" . $i];
            $ourSerial = $_POST["ourSerial" . $i];
            //$RecId=$MComreceiptDetailEX->getReceiptId($ourSerial);
            if (isset($done) && !empty($done) && isset($ourSerial) && !empty($ourSerial)) {
                //print_r($_POST["ourSerial".$i].'<br/>');
                //insert in ProductHistory
                insertProductHistory($ourSerial, 6, 11, 0, '', 0);
                updateCurrentStage(11, $ourSerial);

                $flag = checkIfComReceiptDone($ourSerial);
                if ($flag == 0) {
                    markAsDone($ourSerial);
                }

                //del in mcheck
                $mCheckEX->deleteUsingOurSerial($ourSerial);
            }
        }

        $note = " تمت العملية بنجاح";
        //$url = "receiptController.php?do=addrecept&receptid="+receptnumber;
        $url = "receiptController.php";
        $smarty->assign('urldirect', $url);
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } catch (Exception $e) {
        $note = " لقد حدث خطأ";
        $url = "deleveryReportController.php?do=all";
        $smarty->assign('urldirect', $url);
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    }
}
//here the global templates
//$smarty->assign("customValidation",1);
$smarty->assign("customDeleveryReport", 1);
$smarty->assign("GeneralSearch", 1);
$smarty->display("footer.html");

////****************************  Functions  ********************///
function updateCurrentStage($currentstage, $ourSerial) {
    global $MComreceiptDetailEX;
    $MComreceiptDetailEX->updateCurrentStageUsingOurSerial($currentstage, $ourSerial);
}

function checkIfComReceiptDone($ourSerial) {
    global $MComreceiptDetailEX;

    $id = $MComreceiptDetailEX->getReceiptId($ourSerial);
    $data = $MComreceiptDetailEX->getCurrentStages($id);

    $flag = 0;
    foreach ($data as $myData) {
        if ($myData->currentstage != 11) {
            $flag = 1;
            return $flag;
        }
    }
}

function markAsDone($ourSerial) {
    global $MComreceiptDetailEX;
    global $MComreceiptEX;

    $id = $MComreceiptDetailEX->getReceiptId($ourSerial);
    $MComreceiptEX->markAsDone($id);
}

function insertProductHistory($ourSerial, $stageFrom, $stageTo, $cost, $comment, $status) {
    global $MProductHistory;
    global $MProductHistoryDAO;

    $MProductHistory->ourSerial = $ourSerial;
    $MProductHistory->stageFrom = $stageFrom;
    $MProductHistory->stageTo = $stageTo;
    $MProductHistory->cost = $cost;
    $MProductHistory->comment = $comment;
    $MProductHistory->status = $status;

    $MProductHistory->userId = $_SESSION['userid'];
    $MProductHistory->productHistoryDate = date("Y-m-d H:i:s");
    $MProductHistory->branchId = $_SESSION['branchId'];
    $MProductHistory->del = 0;

    $MProductHistoryDAO->insert($MProductHistory);
}

function getclient() {
    global $ClientDAO;

    $allclient = $ClientDAO->queryByCondition(0);

    return $allclient;
}

function show($clientid, $startDate, $endDate, $recitID) {
    global $mCheckEX;
    global $MComreceiptDetailEX;
    global $mProductHistoryEX;
    global $smarty;
    global $queryString;
    $queryString = ' WHERE';

    if (isset($clientid) && $clientid != '-1' && $clientid != "all") {
        /* //$clientnamedata=$ClientDAO->load($clientid);
          $message=" اسم العميل ".$clientnamedata->clientname;
          $smarty->assign('message',$message);
         */
        $queryString .= '  m_comreceipt.clientid = ' . $clientid . ' AND';
    }
    if (isset($clientid) && $clientid != "-1" && $clientid == "all") {
        $message = " كل العملاء";
        $smarty->assign('message', $message);
        $queryString .= '  m_comreceipt.clientid > 0  AND';
    }

    if (isset($recitID) && $recitID != "-1") {
        $message = " الفاتورة رقم " . $recitID;
        $smarty->assign('message', $message);
        $queryString .= '  m_comreceipt.clientid > 0  AND';
    }


    if (!empty($startDate) && !empty($endDate)) {

        $message = "  عرض الفواتير من تاريخ " . $startDate . "  الى تاريخ" . $endDate;
        $smarty->assign('message', $message);


        $queryString .= '  m_comreceipt.receiptdat >= "' . $startDate . '" AND m_comreceipt.receiptdat <= "' . $endDate . '" AND';
    }

    $arr = explode(' ', $queryString);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') {//remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        } else if ($lastWord == 'WHERE') {//remove it
            array_pop($arr);
            $queryString = ' ';
        }
        //print("<br>queryString: ".$queryString."<br>");
    }

    $checkData = $mCheckEX->queryByBranchEX2xx($queryString, $_SESSION['branchId']);
    foreach ($checkData as $row) {
        $data = $mProductHistoryEX->GetStatusOfSerialWithMaxDate($row->ourSerial);
        /* print_r('<pre>');
          print_r($data);
          print_r('</pre>'); */
        $row->productHistoryStatus = $data->status;
        $row->stageFrom = $data->stageFrom;
        $row->m_stageTitle = $data->stageTitle;

        $myInitialCost = $MComreceiptDetailEX->getInitialCostByOurserialEX($row->ourSerial);
        $row->Initialcost = $myInitialCost;

        $discount = $MComreceiptDetailEX->getdiscountByOurserialEX($row->ourSerial);
        $row->discount = $discount;
    }

    //$suppliers=$supplierDAO->queryAll();
    //$smarty->assign("suppliers",$suppliers);
    $smarty->assign("itr", count($checkData));
    $smarty->assign("checkData", $checkData);
}

?>