HEX
Server: Apache
System: Linux server1.royalgt4.com 4.18.0-553.89.1.lve.el8.x86_64 #1 SMP Wed Dec 10 13:58:50 UTC 2025 x86_64
User: mostafedeg (1125)
PHP: 5.6.40
Disabled: mail,passthru,parse_ini_file,show_source,eval,assert,pcntl_exec,dl,putenv,proc_open,popen
Upload Files
File: /home/mostafedeg/public_html/erp/controllers/supplierController.php
<?php

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

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

//here the db files that include in the file
include("../public/include_dao.php");
include("../library/uploadImages.php");
include '../library/Classes/PHPExcel/IOFactory.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');

//Supplierdebtchange
require_once('../models/dao/SupplierdebtchangeDAO.class.php');
require_once('../models/dto/Supplierdebtchange.class.php');
require_once('../models/mysql/SupplierdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierdebtchangeMySqlExtDAO.class.php');


//Programsetting
require_once('../models/dao/ProgramsettingsDAO.class.php');
require_once('../models/dto/Programsetting.class.php');
require_once('../models/mysql/ProgramsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProgramsettingsMySqlExtDAO.class.php');

//Productcat
require_once('../models/dao/ProductcatDAO.class.php');
require_once('../models/dto/Productcat.class.php');
require_once('../models/mysql/ProductcatMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatMySqlExtDAO.class.php');

//Typesupplier
require_once('../models/dao/TypesupplierDAO.class.php');
require_once('../models/dto/Typesupplier.class.php');
require_once('../models/mysql/TypesupplierMySqlDAO.class.php');
require_once('../models/mysql/ext/TypesupplierMySqlExtDAO.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');
//Client
require_once('../models/dao/GovernmentDAO.class.php');
require_once('../models/dto/Government.class.php');
require_once('../models/mysql/GovernmentMySqlDAO.class.php');
require_once('../models/mysql/ext/GovernmentMySqlExtDAO.class.php');

require_once('../models/dao/ClientareaDAO.class.php');
require_once('../models/dto/Clientarea.class.php');
require_once('../models/mysql/ClientareaMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientareaMySqlExtDAO.class.php');


//GovernArea
require_once('../models/dao/GoverareaDAO.class.php');
require_once('../models/dto/Goverarea.class.php');
require_once('../models/mysql/GoverareaMySqlDAO.class.php');
require_once('../models/mysql/ext/GoverareaMySqlExtDAO.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');
//Currency
require_once('../models/dao/CurrencyDAO.class.php');
require_once('../models/dto/Currency.class.php');
require_once('../models/mysql/CurrencyMySqlDAO.class.php');
require_once('../models/mysql/ext/CurrencyMySqlExtDAO.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 :- productController

  OPERTATION in Controller

  1- display add form, add supplier cat and supplier with ajax
  2- add in supplier tbl
  2.1- insert into supplier unit tbl
  2.2- insert into storedetail tbl
  2.3- insert new row into storereport tbl
  3- display show and tempdelete
  4- edit supplier
  5- update supplier
  5.1- update supplier tbl with supplierid
  5.2- delete supplier units associated to this supplier from productunit tbl, then insert it again

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

//here the global templates
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} else {
    $smarty->display("header.html");
}

//here goes the instances and general variables
//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();

//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();

//Supplierdebtchange
$Supplierdebtchange = new Supplierdebtchange();
$SupplierdebtchangeDAO = new SupplierdebtchangeMySqlDAO();
$SupplierdebtchangeEX = new SupplierdebtchangeMySqlExtDAO();

//Programsetting
$Programsetting = new Programsetting();
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingEX = new ProgramsettingsMySqlExtDAO();


//Dailyentry
$dailyEntry = new Dailyentry();
$dailyEntryDAO = new DailyentryMySqlDAO();
$dailyEntryEX = new DailyentryMySqlExtDAO();

//Dailyentrycreditor دائن
$dailyEntryCreditor = new Dailyentrycreditor();
$dailyEntryCreditorDAO = new DailyentrycreditorMySqlDAO();
$dailyEntryCreditorEX = new DailyentrycreditorMySqlExtDAO();

//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();
$dailyEntryDebtorDAO = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX = new DailyentrydebtorMySqlExtDAO();

//Productcat
$productCat = new Productcat();
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();


//typeSupplier
$typeSupplier = new Typesupplier();
$TypeSupplierDAO = new TypesupplierMySqlDAO();
$TypeSupplierEX = new TypesupplierMySqlExtDAO();

//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();


//government
$government = new Government();
$governmentDAO = new GovernmentMySqlDAO();
$governmentExt = new GovernmentMySqlExtDAO();

//Clientarea
$Clientarea = new Clientarea();
$ClientareaDAO = new ClientareaMySqlDAO();
$ClientareaEX = new ClientareaMySqlExtDAO();


// GovernArea
$governArea = new Goverarea();
$governAreaDAO = new GoverareaMySqlDAO();
$governAreaExt = new GoverareaMySqlExtDAO();

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();
//Currency
$currency = new Currency();
$currencyDAO = new CurrencyMySqlDAO();
$currencyEX = new CurrencyMySqlExtDAO();

$today = date("Y-m-d H:i:s");

$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);

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

    ##get client serial
    $DBName = ConnectionProperty::getDatabase();
    if ($_SESSION['dbname'] != "" && isset($_SESSION['dbname'])) {
        $DBName = $_SESSION['dbname'];
    }
    $nextId = $supplierExt->getAutoIncrementValue($DBName);
    $smarty->assign("nextId", $nextId);
    $smarty->assign("suplliernegative", $_SESSION['suplliernegative']);


    //get product categories
    $allParents = getProductCatParents();
    $smarty->assign("allParents", $allParents);

    //get product categories
    $alltypes = getTypeSupplier();
    //    var_dump($alltypes);
    $smarty->assign("alltypes", $alltypes);

    $allCurrency = $currencyDAO->queryByConditions(0);
    $smarty->assign("allCurrency", $allCurrency);

    //here the smarty templates
    $smarty->display("supplierview/add.html");
} elseif ($do == "add") {
    include_once("../public/authentication.php");
    try {
        $flag = add();

        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "addexcel") {
    //here the permssion check
    include_once("../public/authentication.php");

    //here the smarty templates
    $smarty->display("supplierview/uploadexcel.html");
} elseif ($do == "addfromexcel") {
    include_once("../public/authentication.php");
    try {
        addFromExcel();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == 'empty') {
    $smarty->assign('msg', 'تم ادخال  اسم المورد  من قبل ');
    $smarty->assign("clientnegative", $_SESSION['clientnegative']);
    $smarty->display("supplierview/add.html");
} elseif ($do == "show") {
    include_once("../public/authentication.php");
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $supplierid = $_REQUEST['supplierid'];
    if (isset($supplierid) && $supplierid != "-1") {
        $messageData = $supplierDAO->load($supplierid);
        $message = "إسم المورد: " . $messageData->suppliername;
        $smarty->assign("message", $message);

        showwithsearch($supplierid);
    } else {
        show();
    }

    $smarty->assign('customUsergroup', 1);
    $smarty->assign("customCheck", 1);
    $smarty->display("supplierview/show.html");
} elseif ($do == "executeOperation") {
    try {
        executeOperation();
        show();
        $smarty->assign("customCheck", 1);

        $smarty->display("supplierview/show.html");
    } catch (Exception $e) {
        $smarty->display("error.html");
    }
} elseif ($do == "returndelete") { //returndelete
    include_once("../public/authentication.php");
    try {
        returndelete();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "tempdelete") { //tempdelete
    include_once("../public/authentication.php");
    try {
        $note = tempdelete();
        if ($note != "success") {
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "editprint") { //edit  supplier
    include_once("../public/authentication.php");
    $loadData = edit();
    $smarty->assign("loadData", $loadData);
    $smarty->assign("customPrint", 1);
    $smarty->display("supplierview/editprint.html");
} elseif ($do == "edit") { //edit  supplier
    include_once("../public/authentication.php");
    $allParents = getProductCatParents();
    $smarty->assign("allParents", $allParents);

    //get product categories
    $alltypes = getTypeSupplier();
    $smarty->assign("alltypes", $alltypes);
    //
    $allCurrency = $currencyDAO->queryByConditions(0);
    $smarty->assign("allCurrency", $allCurrency);

    $loadData = edit();
    $smarty->assign("loadData", $loadData);
    $governArea = $governAreaDAO->load((int) $loadData->goverareaid);
    $Clientarea = $ClientareaDAO->load((int) $governArea->clientareaid);
    $smarty->assign("areaname", $Clientarea->name);
    $government = $governmentDAO->load($governArea->governmentid);
    $smarty->assign("governmentname", $government->governmentname);



    $smarty->display("supplierview/edit.html");
} elseif ($do == "update") { //edit update
    include_once("../public/authentication.php");
    try {
        update();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "deleteFinaly") { //edit update
    include_once("../public/authentication.php");
    try {
        $supplierdeleteValid = deleteFinaly();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            if ($supplierdeleteValid[1] == 0) {
                $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            } elseif ($supplierdeleteValid[1] == 2) {
                $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            } else {
                $data = array('status' => 2, 'message' => "لا يمكن حذف  هذا المورد الا بعد حذف كل البيانات المرتبطه به", 'message_en' => 'Can not delete this supplier until deleting its related data');
            }
            echo json_encode($data);
        } else {
            if ($supplierdeleteValid[1] == 0) {
                header("location:?do=sucess");
            } elseif ($supplierdeleteValid[1] == 2) {

                $url = "supplierController.php?do=show";
                $smarty->assign('urldirect', $url);
                $note = "لقد حدث خطأ اثناء اجراء العملية";
                $smarty->assign('msgnote', $note);
                $smarty->display("notes.html");
            } else {
                $url = "supplierController.php?do=show";
                $smarty->assign('urldirect', $url);
                $note = "لا يمكن حذف  هذا المورد الا بعد حذف كل البيانات المرتبطه به";
                $smarty->assign('msgnote', $note);
                $smarty->display("notes.html");
            }
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "updateDebtsInTermsOfCurrency") {
    try {
        $supplierExt->updateSuppliersDeptInTermsOfTheirCurrency();

        header("location:?do=sucess");
    } catch (Exception $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");
}
//here the global templates
$smarty->assign("customSupplier", 1);

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


if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} else {
    $smarty->display("footer.html");
}

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

// add in supplier tbl
function add() {
    global $supplierDAO;
    global $supplier;

    global $Supplierdebtchange;
    global $SupplierdebtchangeDAO;

    global $today;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;
    global $dailyEntryCreditorDAO;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;

    $suppliername = $_POST["txtName"];
    $supplieraddress = $_POST["txtAddress"];
    $supplierphone = $_POST["txtPhone"];
    $supplierdetails = $_POST["textDetails"];
    $suppliercurrentDebt = $_POST["txtDebt"];
    $suppliercode = $_POST["suppliercode"];
    $goverareaid = $_POST["goverareaid"];
    $namepayeecheck = $_POST["namepayeecheck"];
    $suppliermobile = $_POST["suppliermobile"];
    $warrantyOfficer = $_POST["warrantyOfficer"];
    $warrantymobile = $_POST["warrantymobile"];
    $sellername = $_POST["sellername"];
    $sellermobile = $_POST["sellermobile"];
    $taxnumber = $_POST["taxnumber"];
    $supplierTypeForTree = (int) $_POST["supplierTypeForTree"];
    $sullpierCurrencyid = (int) $_POST["sullpierCurrencyid"];
    $suppliercurrentDebtInCurrency = (float) $_POST["suppliercurrentDebtInCurrency"];

    $suppIsClientToo = (int) $_POST["suppIsClientToo"];
    $client = (int) $_POST["client"];

    $category_id = implode(',', $_POST['category_id']);
    $typesupplier_id = implode(',', $_POST['typesupplier']);
    $supplierdate = $today;

    $checkSupplier = $supplierDAO->queryBySuppliername($suppliername);

    $supplier->suppliername = $suppliername;
    $supplier->supplieraddress = $supplieraddress;
    $supplier->supplierphone = $supplierphone;
    $supplier->supplierdetails = $supplierdetails;
    $supplier->suppliercurrentDebt = $suppliercurrentDebt;
    $supplier->userid = $_SESSION['userid'];
    $supplier->conditions = 0;
    $supplier->supplierdate = $supplierdate;
    $supplier->dailyentryid = 0;
    $supplier->category_id = $category_id;
    $supplier->typesupplier_id = $typesupplier_id;
    $supplier->suppliercode = $suppliercode;
    $supplier->goverareaid = $goverareaid;
    $supplier->namepayeecheck = $namepayeecheck;
    $supplier->suppliermobile = $suppliermobile;
    $supplier->warrantyOfficer = $warrantyOfficer;
    $supplier->warrantymobile = $warrantymobile;
    $supplier->sellername = $sellername;
    $supplier->sellermobile = $sellermobile;
    $supplier->taxnumber = $taxnumber;
    $supplier->supplierTypeForTree = $supplierTypeForTree;
    $supplier->sullpierCurrencyid = $sullpierCurrencyid;
    $supplier->suppliercurrentDebtInCurrency = $suppliercurrentDebtInCurrency;
    $supplier->webApiId = (int) $_POST['webApiId'];

    //Insert
    $supplierid = $supplierDAO->insert($supplier);





    if (!empty($supplierid)) {
        $Supplierdebtchange->comment = "";
        $Supplierdebtchange->processname = "إضافة مورد جديد";
        $Supplierdebtchange->supplierdebtchangeafter = $suppliercurrentDebt;
        $Supplierdebtchange->supplierdebtchangeamount = $suppliercurrentDebt;
        $Supplierdebtchange->supplierdebtchangebefore = 0;
        $Supplierdebtchange->supplierdebtchangedate = $supplierdate;
        $Supplierdebtchange->supplierdebtchangemodelid = $supplierid;
        $Supplierdebtchange->supplierid = $supplierid;
        $Supplierdebtchange->supplierdebtchangetype = 0;
        $Supplierdebtchange->tablename = "supplierController.php";
        $Supplierdebtchange->userid = $_SESSION['userid'];
        $Supplierdebtchange->dailyentryid = 0;
        $Supplierdebtchange->debtchangbeforeInSupplierCurrency = 0;
        $Supplierdebtchange->debtchangamountInSupplierCurrency = $suppliercurrentDebtInCurrency;
        $Supplierdebtchange->debtchangafterInSupplierCurrency = $suppliercurrentDebtInCurrency;

        $SupplierdebtchangeDAO->insert($Supplierdebtchange);
    }

    $linkedClientId = $client;
    if ($suppIsClientToo == 2) { //link to existing client
        CURL_IT2(array('clientid' => $client, 'supplierid' => $supplierid), 'clientControllerAjax.php?do=linkToSupplier');
    } elseif ($suppIsClientToo == 1) {
        $linkedClientId = (int) CURL_IT2(array('txtName' => $supplier->suppliername, 'linkedSupplierId' => $supplierid, 'txtDebt' => 0, 'debtLimit' => 1000, 'store_all' => 1, 'clientareaid' => 0), 'clientController.php?do=addSimpleReturn');
        $linkedClientId = ($linkedClientId < 0) ? 0 : $linkedClientId;
    } else { //link it to no client
        CURL_IT2(array('clientid' => 0, 'supplierid' => $supplierid), 'clientControllerAjax.php?do=linkToSupplier');
    }



    $dailyEntry->entryComment = 'إضافة مورد  ( ' . $suppliername . ' ) ';

    // start Ras L Maaal
    $dailyEntryDebtorArray = array();
    $dailyEntryDebtor->value = $suppliercurrentDebt;
    $dailyEntryDebtor->accountstreeid = 121;
    /// end Ras L Maaal
    //
    /// start L 7sab L da2non
    $dailyEntryCreditorArray = array();
    $dailyEntryCreditor->value = $suppliercurrentDebt;

    if ($supplierTypeForTree == 0)
        $parent = 81;
    elseif ($supplierTypeForTree == 1)
        $parent = 87;

    $treeId = addTreeElement($suppliername, $parent, 1, 0, 1, '', 0, 0);
    $dailyEntryCreditor->accountstreeid = $treeId;
    /// end L 7sab L da2non

    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

    $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $supplierid, "supplierController.php?do=edit&id=$supplierid");
    $did = $returnedData[1];

    $rowData = $supplierDAO->load($supplierid);

    $rowData->treeId = $treeId;
    $rowData->dailyentryid = $did;
    $rowData->linkedClientId = $linkedClientId;


    $supplierDAO->update($rowData);
}

function addFromExcel() {
    global $supplierDAO;
    global $supplier;

    global $Supplierdebtchange;
    global $SupplierdebtchangeDAO;

    global $today;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;
    global $dailyEntryCreditorDAO;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;

    ## upload file temporarely
    $handle = new upload($_FILES['supplierssheet']);
    $excelfileName = uploadfile($handle, "../upload/products");
    $inputFileName = "../upload/products/" . $excelfileName;

    #
    $noDailyEntry = (int) $_POST['noDailyEntry'];

    //Transaction
    $mytransactions = new Transaction();
    try {
        $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        //$objReader->setUTFEncoder('iconv');
        //$objReader::setOutputEncoding('UTF-8');
        $objPHPExcel = $objReader->load($inputFileName);



        //  Get worksheet dimensions
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();

        for ($row = 4; $row <= $highestRow; $row++) {
            //  Read a row of data into an array
            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
            $rowData = $rowData[0];

            $col = 0;
            $suppliername = $rowData[$col]; //$_POST["txtName"];
            $col++;
            $supplieraddress = $rowData[$col]; //$_POST["txtAddress"];
            $col++;
            $supplierphone = $rowData[$col]; //$_POST["txtPhone"];
            $col++;
            $suppliercurrentDebt = $rowData[$col]; //$_POST["txtDebt"];
            $col++;
            $supplierdetails = $rowData[$col]; //$_POST["textDetails"];
            $col++;
            $category_id = ''; //implode(',', $_POST['category_id']);
            $col++;
            $typesupplier_id = ''; //implode(',', $_POST['typesupplier']);
            $supplierdate = $today;

            $checkSupplier = $supplierDAO->queryBySuppliername($suppliername);
            if (count($checkSupplier) == 0) {
                $supplier->suppliername = $suppliername;
                $supplier->supplieraddress = $supplieraddress;
                $supplier->supplierphone = $supplierphone;
                $supplier->supplierdetails = $supplierdetails;
                $supplier->suppliercurrentDebt = $suppliercurrentDebt;
                $supplier->userid = $_SESSION['userid'];
                $supplier->conditions = 0;
                $supplier->supplierdate = $supplierdate;
                $supplier->dailyentryid = 0;
                $supplier->category_id = $category_id;
                $supplier->typesupplier_id = $typesupplier_id;

                //Insert
                $supplierid = $supplierDAO->insert($supplier);





                if (!empty($supplierid)) {
                    $Supplierdebtchange->comment = "";
                    $Supplierdebtchange->processname = "إضافة مورد جديد";
                    $Supplierdebtchange->supplierdebtchangeafter = $suppliercurrentDebt;
                    $Supplierdebtchange->supplierdebtchangeamount = $suppliercurrentDebt;
                    $Supplierdebtchange->supplierdebtchangebefore = 0;
                    $Supplierdebtchange->supplierdebtchangedate = $supplierdate;
                    $Supplierdebtchange->supplierdebtchangemodelid = $supplierid;
                    $Supplierdebtchange->supplierid = $supplierid;
                    $Supplierdebtchange->supplierdebtchangetype = 0;
                    $Supplierdebtchange->tablename = "supplierController.php";
                    $Supplierdebtchange->userid = $_SESSION['userid'];
                    $Supplierdebtchange->dailyentryid = 0;

                    $SupplierdebtchangeDAO->insert($Supplierdebtchange);
                }



                $treeId = addTreeElement($suppliername, 81, 1, 0, 1, '', 0, 0);
                if ($noDailyEntry == 0) {

                    $dailyEntry->entryComment = 'إضافة مورد  ( ' . $suppliername . ' ) ';

                    // start Ras L Maaal
                    $dailyEntryDebtorArray = array();
                    $dailyEntryDebtor->value = $suppliercurrentDebt;
                    $dailyEntryDebtor->accountstreeid = 121;
                    /// end Ras L Maaal
                    //
                    /// start L 7sab L da2non
                    $dailyEntryCreditorArray = array();
                    $dailyEntryCreditor->value = $suppliercurrentDebt;


                    $dailyEntryCreditor->accountstreeid = $treeId;
                    /// end L 7sab L da2non

                    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
                    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

                    $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $supplierid, "supplierController.php?do=edit&id=$supplierid");
                    $did = $returnedData[1];
                }
                $supplier = $supplierDAO->load($supplierid);

                $supplier->treeId = (int) $treeId;
                $supplier->dailyentryid = (int) $did;

                $supplierDAO->update($supplier);
            }
        }


        unlink($inputFileName);
        $mytransactions->commit();
    } catch (Exception $e) {
        $mytransactions->rollback();
        //die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
    }
}

function showwithsearch($supplierid) {
    global $supplierDAO;
    global $supplierExt;
    global $today;
    global $smarty;

    $alldata = $supplierDAO->queryAll();
    $smarty->assign("alldata", $alldata);

    $shownData = $supplierExt->loadExt($supplierid);

    $sum;
    foreach ($shownData as $data) {
        if ($data->conditions == 0) {
            $sum += $data->suppliercurrentDebt;
        }
    }
    $smarty->assign('sum', $sum);

    $smarty->assign('shownData', $shownData);
}

//show
function show() {
    global $supplierDAO;
    global $supplierExt;
    global $today;
    global $smarty;

    if ($_REQUEST['showdelete'] == 1)
        $alldata = $supplierDAO->queryAll();
    else
        $alldata = $supplierDAO->queryByCondition(0); //queryAll();
    $smarty->assign("alldata", $alldata);

    if ($_REQUEST['showdelete'] == 1)
        $shownData = $supplierExt->queryAllForShow();
    else
        $shownData = $supplierExt->queryAllForShowWithCondition(); //queryAllForShow();

    $sum;
    foreach ($shownData as $data) {
        if ($data->conditions == 0) {
            $sum += $data->suppliercurrentDebt;
        }
    }
    $smarty->assign('sum', $sum);

    $smarty->assign('shownData', $shownData);
}

function executeOperation() {
    global $supplierDAO;
    global $supplierExt;
    global $smarty;
    global $outputString;

    $operationType = $_POST['operation'];

    $choosedItemArr = $_POST['choosedItem'];
    if (count($choosedItemArr) > 0) {
        $i = 1;
        foreach ($choosedItemArr as $supplierid) {
            if ($operationType == '1') { //tempdelete
                try {
                    $note = tempdelete($supplierid);
                    if ($note != "success") {
                        //get supplier name
                        $supplierData = $supplierDAO->load($supplierid);
                        if (count($supplierData) > 0) {
                            $suppliername = $supplierData->suppliername;
                            $outputString .= $suppliername . ": " . $note . "<br/>";
                        }
                    } else {
                        $outputString = "تمت العملية بنجاح";
                    }
                } catch (Exception $e) {

                }
            } elseif ($operationType == "2") { //returndelete
                try {
                    returndelete($supplierid);
                    $outputString = "تمت العملية بنجاح";
                } catch (Exception $e) {
                    $note = "حدث خطأ أثناء إتمام العملية";
                }
            }
            $i++;
        }
        $smarty->assign("outputString", $outputString);
    }
}

function tempdelete($supplierid) {
    global $supplierDAO;
    global $supplierExt;
    $note;
    if (empty($supplierid)) {
        $supplierid = $_GET['id'];
    }

    if (!empty($supplierid)) {
        try {
            $supplier = $supplierDAO->load($supplierid);
            $supplierExt->deletetempWithName($supplierid, $supplier->suppliername . '-del'); //deletetemp($supplierid);

            $note = "success";
        } catch (Exception $e) {
            $note = "حدث خطأ أثناء إتمام العملية";
        }
    } else {
        $note = "حدث خطأ أثناء إتمام العملية";
    }
    return $note;
}

function returndelete($supplierid) {
    global $supplierDAO;
    global $supplierExt;

    if (empty($supplierid)) {
        $supplierid = $_GET['id'];
    }

    if (!empty($supplierid)) {
        $supplier = $supplierDAO->load($supplierid);
        if (strpos($supplier->suppliername, "-del") !== false) {
            $name = str_replace("-del", "", $supplier->suppliername);
            $supplierExt->returndeleteWithName($supplierid, $name);
        } else
            $supplierExt->returndelete($supplierid);
    }
}

function edit() {
    global $supplierDAO;
    global $clientDAO;

    $id = $_GET["id"];
    $loadData = $supplierDAO->load($id);

    $loadData->category_id = explode(',', $loadData->category_id);
    $loadData->typesupplier_id = explode(',', $loadData->typesupplier_id);

    if ($loadData->linkedClientId > 0) {
        $clientData = $clientDAO->load($loadData->linkedClientId);
        $loadData->linkedClientName = $clientData->clientname;
    }
    return $loadData;
}

function deleteFinaly() {
    global $supplierDAO;
    global $SupplierdebtchangeEX;
    global $supplierExt;

    $id = (int) $_GET["id"];
    //$action = $_GET["action"];

    $rowDelData = $supplierDAO->load($id);
    $action = $rowDelData->dailyentryid;

    try {
        if (!empty($id) && $id > 1) { //dont delete supplierid =1
            $supplierData = $SupplierdebtchangeEX->queryBySupplierIdNotDeleted($id); //loadBySupplierId($id);// ' and (processname !="إضافة مورد جديد" and supplierdebtchangeamount=0)
            if (count($supplierData) <= 1) {
                $supplierdeleteValid = 0;
                // $supplierDAO->delete($id);
                $supplierExt->deleteFinallyWithName($id, $rowDelData->suppliername . '-del'); //deletetemp($supplierid);
                reverseEntryWithItsID($action);
                delTreeElementById($rowDelData->treeId);
                $note = "success";
            } else {
                $supplierdeleteValid = 1;
                $note = "لا يمكن حذف  هذا المورد";
            }
        } elseif ($id == 1) {
            $supplierdeleteValid = 1;
            $note = "لا يمكن حذف  هذا المورد";
        } else {

            $supplierdeleteValid = 2;
            $note = "حدث خطأ أثناء حذف المورد";
        }
    } catch (Exception $e) {
        $note = "حدث خطأ أثناء حذف المورد";
    }


    return array($note, $supplierdeleteValid);
}

function update() {
    global $supplierDAO;
    global $supplier;
    global $today;
    global $accountsTree;
    global $accountsTreeDAO;
    global $clientExt;
    $id = $_POST["id"];

    $suppliername = $_POST["txtName"];
    $supplieraddress = $_POST["txtAddress"];
    $supplierphone = $_POST["txtPhone"];
    $supplierdetails = $_POST["textDetails"];
    $suppliercurrentDebt = $_POST['debt'];
    $supplierdate = $today;
    $conditions = $_POST['conditions'];
    $dailyentryid = $_POST['dailyentryid'];
    $category_id = implode(',', $_POST['category_id']);
    $typesupplier_id = implode(',', $_POST['typesupplier']);

    $suppIsClientToo = (int) $_POST["suppIsClientToo"];
    $client = (int) $_POST["client"];
    $oldClientId = (int) $_POST["oldClientId"];
    $suppliercode = $_POST["suppliercode"];
    $goverareaid = $_POST["goverareaid"];
    $namepayeecheck = $_POST["namepayeecheck"];
    $suppliermobile = $_POST["suppliermobile"];
    $warrantyOfficer = $_POST["warrantyOfficer"];
    $warrantymobile = $_POST["warrantymobile"];
    $sellername = $_POST["sellername"];
    $sellermobile = $_POST["sellermobile"];
    $taxnumber = $_POST["taxnumber"];
    $supplierTypeForTree = (int) $_POST["supplierTypeForTree"];

    //Adding object properties
    $supplier->supplierid = $id;
    $supplier->suppliername = $suppliername;
    $supplier->supplieraddress = $supplieraddress;
    $supplier->supplierphone = $supplierphone;
    $supplier->supplierdetails = $supplierdetails;
    $supplier->suppliercurrentDebt = $suppliercurrentDebt;
    $supplier->userid = $_SESSION['userid'];
    $supplier->conditions = $conditions;
    $supplier->supplierdate = $supplierdate;
    $supplier->dailyentryid = $dailyentryid;
    $supplier->category_id = $category_id;
    $supplier->typesupplier_id = $typesupplier_id;
    $supplier->suppliercode = $suppliercode;
    $supplier->goverareaid = $goverareaid;
    $supplier->namepayeecheck = $namepayeecheck;
    $supplier->suppliermobile = $suppliermobile;
    $supplier->warrantyOfficer = $warrantyOfficer;
    $supplier->warrantymobile = $warrantymobile;
    $supplier->sellername = $sellername;
    $supplier->sellermobile = $sellermobile;
    $supplier->taxnumber = $taxnumber;
    $supplier->supplierTypeForTree = $supplierTypeForTree;



    $oldSupplier = $supplierDAO->load($id);
    //print_r($id . 'aaaaaaaaaaaaaaaa');
    //    print_r('<pre>');
    //    print_r($oldSupplier);
    //
    //    print_r('</pre>');

    $treeId = $oldSupplier->treeId;
    //  print_r($treeId . 'aaaaaaaaaaaaaaaaaa');

    $getRow = $accountsTreeDAO->load($treeId);

    if ($supplierTypeForTree == 0)
        $parent = 81;
    elseif ($supplierTypeForTree == 1)
        $parent = 87;

    $accountsTree->name = $suppliername;
    $accountsTree->id = $treeId;
    $accountsTree->del = $getRow->del;
    $accountsTree->customName = $suppliername;

    $accountsTree->itemfrom = $getRow->itemfrom;
    $accountsTree->itemtype = $getRow->itemtype;
    $accountsTree->itemtype2 = $getRow->itemtype2;
    $accountsTree->layingOrder = $getRow->layingOrder;
    $accountsTree->sysdate = $getRow->sysdate;
    $accountsTree->notes = $getRow->notes;
    $accountsTree->parent = $parent;
    $accountsTree->theOrder = $getRow->theOrder;
    $accountsTree->theValue = $getRow->theValue;
    $accountsTree->userid = $getRow->userid;
    $accountsTree->accountNature = $getRow->accountNature;
    $accountsTree->listId = $getRow->listId;



    $x = editTreeElement($accountsTree);


    $linkedClientId = $client;
    if ($suppIsClientToo == 2) { //link to existing client
        if ($client != $oldClientId) {
            //remove any link to the suppplier with any client
            $clientExt->removeAnyClientLinkForASupplier($id);
            //now link to existing client
            CURL_IT2(array('clientid' => $client, 'supplierid' => $id), 'clientControllerAjax.php?do=linkToSupplier');
        }
    } elseif ($suppIsClientToo == 1) {
        $linkedClientId = (int) CURL_IT2(array('txtName' => $supplier->suppliername, 'linkedSupplierId' => $id, 'txtDebt' => 0, 'debtLimit' => 1000, 'store_all' => 1, 'clientareaid' => 0), 'clientController.php?do=addSimpleReturn');
        $linkedClientId = ($linkedClientId < 0) ? 0 : $linkedClientId;
    } else { //link it to no client
        //CURL_IT2(array('clientid' => 0, 'supplierid' => $id), 'clientControllerAjax.php?do=linkToSupplier');
        //remove any link to the suppplier with any client
        $clientExt->removeAnyClientLinkForASupplier($id);
        $linkedClientId = 0;
    }


    $supplier->linkedClientId = $linkedClientId;
    $supplier->sullpierCurrencyid = $oldSupplier->sullpierCurrencyid;
    $supplier->suppliercurrentDebtInCurrency = $oldSupplier->suppliercurrentDebtInCurrency;
    $supplier->treeId = $treeId;
    //update
    $supplierDAO->update($supplier);
}

function getProductCatParents() {
    global $productCatExt;

    $allParents = $productCatExt->getProductCatParents();
    return $allParents;
}

function getTypeSupplier() {
    global $TypeSupplierEX;

    $allParents = $TypeSupplierEX->queryAllsup();
    return $allParents;
}

function CURL_IT2($data_arr, $url) {
    ##preparing session data
    //$projectURL = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/';
    $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $url;

    ##appending necessary data
    $data_arr['curlpost'] = '1';
    $data_arr['sessionlist'] = json_encode($_SESSION);


    // set post fields
    //    $post = [
    //        'data_arr' => json_encode($data_arr), //encode it as it is array
    //    ];
    $post = $data_arr;
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        //echo 'Error : ' . curl_error($ch);
    }

    // close the connection, release resources used
    curl_close($ch);
    // do anything you want with your response
    //var_dump($response);
    //print_r($response);
    return $response;
}