<?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
// GOES HERE ....................
include("../public/include_dao.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');

//Shippercompanie
require_once('../models/dao/ShippercompaniesDAO.class.php');
require_once('../models/dto/Shippercompanie.class.php');
require_once('../models/mysql/ShippercompaniesMySqlDAO.class.php');
require_once('../models/mysql/ext/ShippercompaniesMySqlExtDAO.class.php');

//Representativecompany
require_once('../models/dao/RepresentativecompanyDAO.class.php');
require_once('../models/dto/Representativecompany.class.php');
require_once('../models/mysql/RepresentativecompanyMySqlDAO.class.php');
require_once('../models/mysql/ext/RepresentativecompanyMySqlExtDAO.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');

//MInsurance
require_once('../models/dao/MInsuranceDAO.class.php');
require_once('../models/dto/MInsurance.class.php');
require_once('../models/mysql/MInsuranceMySqlDAO.class.php');
require_once('../models/mysql/ext/MInsuranceMySqlExtDAO.class.php');

//Save
require_once('../models/dao/SaveDAO.class.php');
require_once('../models/dto/Save.class.php');
require_once('../models/mysql/SaveMySqlDAO.class.php');
require_once('../models/mysql/ext/SaveMySqlExtDAO.class.php');
//Savedaily
require_once('../models/dao/SavedailyDAO.class.php');
require_once('../models/dto/Savedaily.class.php');
require_once('../models/mysql/SavedailyMySqlDAO.class.php');
require_once('../models/mysql/ext/SavedailyMySqlExtDAO.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');

//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 :- propertiesCTRL

  OPERTATION in Controller

  1-display add form
  2- add in properity tbl
  3- select data from usergroup tbl
  4-add in relusergroupproperties tbl
  5-display sucess or error

  ======================== */


//here the global templates
$smarty->display("header.html");
//$smarty->display("maintennanceHeader.html");
//$smarty->display("quciktask.html");
//here goes the instances and general variables
$MComReceiptDetailEX = new MComreceiptdetailMySqlExtDAO();

$ShipperCompanieDAO = new ShippercompaniesMySqlDAO();
$RepresentativeCompanyDAO = new RepresentativecompanyMySqlDAO();



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

$MInsurance = new MInsurance();
$MInsuranceDAO = new MInsuranceMySqlDAO();
$MInsuranceEX = new MInsuranceMySqlExtDAO();

//Save
$save = new Save();
$saveDAO = new SaveMySqlDAO();
$saveExt = new SaveMySqlExtDAO();
//Savedaily
$saveDaily = new Savedaily();
$saveDailyDAO = new SavedailyMySqlDAO();
$saveDailyExt = new SavedailyMySqlExtDAO();

$MComreceiptEX = new MComreceiptMySqlExtDAO();

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

    // here the function that do the action
    $data = $MComReceiptDetailEX->getSupplierVSNoOfProducts($_SESSION['branchId']);
    $smarty->assign("data", $data);

    /* print_r('<pre>');
      print_r($data);
      print_r('</pre>'); */


    $smarty->assign("title1", 'الصيانة');
    $smarty->assign("title2", 'إدارة الضمان');
    $smarty->assign("title3", 'ضمان ذهاب');
    $smarty->assign("link", '#');
    $smarty->display("maintennanceHeader.html");


    //here the smarty templates
    $smarty->display("insuranceGoView/insuranceGOPrepare.html");
} elseif ($do == "send") {
    $supplierid = $_GET["supplierid"];
    $ShipperCompanies = $ShipperCompanieDAO->queryAll();
    $RepresentativeCompanies = $RepresentativeCompanyDAO->queryAll();
    $productsData = $MComReceiptDetailEX->getProductsToGo2($supplierid, $_SESSION['branchId']);
    $smarty->assign("productsData", $productsData);
    $smarty->assign("itr", count($productsData));

    $smarty->assign("ShipperCompanies", $ShipperCompanies);
    $smarty->assign("RepresentativeCompanies", $RepresentativeCompanies);
    $smarty->display("insuranceGoView/insuranceGO.html");
} elseif ($do == "add") {
    try {
        add();
        $note = " تمت العملية بنجاح";
    } catch (Exception $e) {
        $note = "لقد حدث خطأ اثناء اجراء العملية";
    }
    $url = "insuranceGo.php?do=all";
    $smarty->assign('urldirect', $url);
    $smarty->assign('msgnote', $note);
    $smarty->display("notes2.html");
} elseif ($do == "sucess") {

    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {

    //here the smarty templates
    $smarty->display("error.html");
}






//here the global templates

$smarty->assign("customInsuranceGo", 1);
$smarty->assign("customValidation", 1);
$smarty->assign("GeneralSearch", 1);
$smarty->display("footer.html");

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

function add() {
    global $MInsuranceEX;
    global $MComreceiptEX;
    $itr = $_POST["hidden_itr"];
    $mydate = $_POST["mydate"];
    $companyId = $_POST["companyId"];
    $representativeId = $_POST["representativeId"];
    $Policyholder = $_POST["Policyholder"];
    if (!isset($Policyholder) || empty($Policyholder)) {
        $Policyholder = '';
    }
    for ($i = 1; $i <= $itr; $i++) {
        $ourserial = $_POST["ourserial" . $i];
        //$cost=$_POST["cost"];
        $cost = $_POST["cost" . $i];

        if (isset($ourserial) && !empty($ourserial) && isset($cost) && !empty($cost) && isset($companyId) && $companyId != -1 && isset($representativeId) && $representativeId != -1) {
            //print_r('ourserial='.$ourserial.'</br>');
            $insuranceId = $MInsuranceEX->getinsuranceIdUsingourserial($ourserial);

            $saveData = getSaveValueAndMins($_SESSION['saveid'], $cost);
            $saveId = $saveData[0];
            $saveValuebefore = $saveData[1];
            $saveValueafter = $saveData[2];

            //update saveFrom value after add transfer
            updateSave($saveId, $saveValueafter);

            //insert into savedaily tbl from savefrom
            insertSavedaily($saveValuebefore, $cost, 1, $saveId, "شحن ذهاب", $insuranceId, $saveValueafter, "insuranceGo.php");

            updateInsuranceGo($ourserial, 7, 10, $Policyholder, $companyId, $representativeId, $cost, $mydate);

            insertProductHistory($ourserial, 7, 10, $cost, '', 0);
            updateCurrentStage(10, $ourserial);

            //اثر فى اجمالى الفاتورة totalCost
            $result = $MComreceiptEX->getClientIdUsingOurSerial($ourserial);
            $clientId = $result->clientid;
            $comRecID = $result->id;
            increaseComRecIDTotalCost($comRecID, $cost);
        }
    }
}

function increaseComRecIDTotalCost($comRecID, $changeAmount) {
    global $MComreceiptEX;

    $totalCost = $MComreceiptEX->getTotalCostComRecIDTotalCost($comRecID);
    $totalCostNew = $totalCost + $changeAmount;
    $MComreceiptEX->increaseComRecIDTotalCost($comRecID, $totalCostNew);
}

function updateInsuranceGo($ourSerial, $stageIdBefore, $currentStage, $shipNameGo, $shipCompanyGo, $shipPersonalGo, $shipCostGo, $date) {
    global $MInsurance;
    global $MInsuranceEX;

    $MInsuranceEX->updateInsuranceGoEX($stageIdBefore, $currentStage, $shipNameGo, $shipCompanyGo, $shipPersonalGo, $shipCostGo, $date, $ourSerial);
}

function updateCurrentStage($currentstage, $ourserial) {
    global $MComReceiptDetailEX;

    $MComReceiptDetailEX->updateCurrentStageUsingOurSerial($currentstage, $ourserial);
}

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 getSaveValueBefore($saveid) {

    //to use the variable out side the funcion
    global $save;
    global $saveDAO;

    $saveData = $saveDAO->load($saveid);
    $saveValuebefore = $saveData->savecurrentvalue;

    return $saveValuebefore;
}

// get initialvalue and mins from save tbl
function getSaveValueAndMins($saveid, $savevaluechanged) {
    global $save;
    global $saveDAO;

    $saveData = $saveDAO->load($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore - $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter);
}

// update in Save tbl
function updateSave($saveid, $savevalueafter) {
    global $save;
    global $saveExt;

    //update initialvalue in Save tbl
    $save->savecurrentvalue = $savevalueafter;
    $save->userid = $_SESSION['userid'];
    $save->saveid = $saveid;

    $saveExt->updateSaveValue($save);
}

// insert in Savedaily tbl
function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename) {
    global $saveDaily;
    global $saveDailyDAO;

    //insert in Savedaily tbl
    $saveDaily->savedailydate = date("Y-m-d H:i:s");
    $saveDaily->userid = $_SESSION['userid'];
    $saveDaily->savedailysavebefore = $savedailysavebefore;
    $saveDaily->savedailychangeamount = $savedailychangeamount;
    $saveDaily->savedailychangetype = $savedailychangetype;
    $saveDaily->saveid = $saveid;
    $saveDaily->processname = $processname;
    $saveDaily->savedailymodelid = $savedailymodelid;
    $saveDaily->savedailysaveafter = $savedailysaveafter;
    $saveDaily->tablename = $tablename;

    $saveDailyDAO->insert($saveDaily);
}

?>