<?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->getSupplierVSNoOfProducts2($_SESSION['branchId']);
    $smarty->assign("data", $data);

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


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

    $smarty->assign("ShipperCompanies", $ShipperCompanies);
    $smarty->assign("RepresentativeCompanies", $RepresentativeCompanies);
    $smarty->display("insuranceReturnView/insuranceReturn.html");
} elseif ($do == "add") {
    try {
        add();
        $note = " تمت العملية بنجاح";
    } catch (Exception $e) {
        $note = "لقد حدث خطأ اثناء اجراء العملية";
    }
    $url = "insuranceReturn.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("customInsuranceReturn", 1);
$smarty->assign("customValidation", 1);
$smarty->assign("GeneralSearch", 1);
$smarty->display("footer.html");

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

function prepareReturn() {
    $itr = $_POST["hidden_itr"];
    for ($i = 1; $i <= $itr; $i++) {
        $thisGo = $_POST["go" . $i];
        $ourserial = $_POST["ourserial" . $i];
        //$productSerial=$_POST["productSerial".$i];
        if (isset($thisGo) && !empty($thisGo) && isset($ourserial) && !empty($ourserial)/* &&isset($productSerial)&&!empty($productSerial) */) {
            updateInsuranceStages($ourserial, 10, 8);
            insertProductHistory($ourserial, 10, 8, 0, '', 0);
            updateCurrentStage(8, $ourserial);
        }
    }
}

function add() {
    global $MInsuranceEX;
    global $MComreceiptEX;

    $itr = $_POST["hidden_itr"];
    $mydate = $_POST["mydate"];
    if (!isset($mydate) || empty($mydate)) {
        $mydate = date("Y-m-d");
    }
    $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($cost) || empty($cost)) {
            $cost = 0;
        }
        $go = $_POST["go" . $i];
        $type = $_POST["type" . $i];
        $newSN = $_POST["newSN" . $i];
        if (!isset($newSN) || empty($newSN)) {
            $newSN = '';
        }
        $insuranceCost = $_POST["insuranceCost" . $i];
        if (!isset($insuranceCost) || empty($insuranceCost)) {
            $insuranceCost = 0;
        }
        $insuranceDiscount = $_POST["insuranceDiscount" . $i];
        if (!isset($insuranceDiscount) || empty($insuranceDiscount)) {
            $insuranceDiscount = 0;
        }

        if ($type != 0) {
            $newSN = $ourserial;
        }

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

            $finalCost = $cost + $insuranceCost - $insuranceDiscount;
            $saveData = getSaveValueAndMins($_SESSION['saveid'], $finalCost);
            $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, $finalCost, 1, $saveId, "شحن عودة", $insuranceId, $saveValueafter, "insuranceReturn.php");

            updateInsuranceReturn($ourserial, 10, 9, $Policyholder, $companyId, $representativeId, $cost, $mydate, $type, $ourserial, $newSN, $insuranceCost, $insuranceDiscount);
            insertProductHistory($ourserial, 10, 9, $finalCost, '', $isAcccepted);
            updateCurrentStage(9, $ourserial);

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

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 updateInsuranceReturn($ourSerial, $stageIdBefore, $currentStage, $shipNameReturn, $shipCompanyReturn, $shipPersonalReturn, $shipCostReturn, $insuranceDate, $type, $oldSN, $newSN, $insuranceCost, $insuranceDiscount) {
    global $MInsurance;
    global $MInsuranceEX;

    $MInsuranceEX->updateInsuranceReturnEX($ourSerial, $stageIdBefore, $currentStage, $shipNameReturn, $shipCompanyReturn, $shipPersonalReturn, $shipCostReturn, $insuranceDate, $type, $oldSN, $newSN, $insuranceCost, $insuranceDiscount);
}

function updateInsuranceStages($ourSerial, $stageIdBefore, $currentStage) {
    global $MInsurance;
    global $MInsuranceEX;

    $MInsuranceEX->updateInsuranceCurrentStage($stageIdBefore, $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 updateCurrentStage($currentstage, $ourserial) {
    global $MComReceiptDetailEX;

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

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

?>