<?php

ob_start();
$do = isset($_GET['do']) ? $_GET['do'] : "";
$ajaxDoArr = array("addSimpleReturn");

if (!in_array($do, $ajaxDoArr)) {
    //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';
//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');
//Clientdebtchange
require_once('../models/dao/ClientdebtchangeDAO.class.php');
require_once('../models/dto/Clientdebtchange.class.php');
require_once('../models/mysql/ClientdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientdebtchangeMySqlExtDAO.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');


//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');

//Government
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');


//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');

//Store
require_once('../models/dao/StoreDAO.class.php');
require_once('../models/dto/Store.class.php');
require_once('../models/mysql/StoreMySqlDAO.class.php');
require_once('../models/mysql/ext/StoreMySqlExtDAO.class.php');

//typeClient
require_once('../models/dao/TypeClientDAO.class.php');
require_once('../models/dto/TypeClient.class.php');
require_once('../models/mysql/TypeClientMySqlDAO.class.php');
require_once('../models/mysql/ext/TypeClientMySqlExtDAO.class.php');
//
require_once('../models/dao/TamweenclientdetailDAO.class.php');
require_once('../models/dto/Tamweenclientdetail.class.php');
require_once('../models/mysql/TamweenclientdetailMySqlDAO.class.php');
require_once('../models/mysql/ext/TamweenclientdetailMySqlExtDAO.class.php');
//Usergroup
require_once('../models/dao/UsergroupDAO.class.php');
require_once('../models/dto/Usergroup.class.php');
require_once('../models/mysql/UsergroupMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupMySqlExtDAO.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 :- clientController

  OPERTATION in Controller

  1- display add form
  2- add in client tbl
  3- display show and tempdelete
  4- edit client
  5- update client
  5.1- update client tbl with clientid

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

//here the global templates
if (!in_array($do, $ajaxDoArr)) {
    $smarty->display("header.html");
}

//here goes the instances and general variables
//Clientarea
$Clientarea = new Clientarea();
$ClientareaDAO = new ClientareaMySqlDAO();
$ClientareaEX = new ClientareaMySqlExtDAO();
//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();
//Clientdebtchange
$clientDeptChange = new Clientdebtchange();
$clientDeptChangeDAO = new ClientdebtchangeMySqlDAO();
$clientDeptChangeExt = new ClientdebtchangeMySqlExtDAO();

//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();

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

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();

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


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

//Store
$store = new Store();
$storeDAO = new StoreMySqlDAO();
$storeEX = new StoreMySqlExtDAO();

//typeClient
$type = new TypeClient();
$TypeClientDAO = new TypeClientMySqlDAO();
$TypeClientEX = new TypeClientMySqlExtDAO();
//Tamweenclientdetail
$tamweenClientDetail = new Tamweenclientdetail();
$tamweenClientDetailDAO = new TamweenclientdetailMySqlDAO();
$tamweenClientDetailEX = new TamweenclientdetailMySqlExtDAO();
//
$userGroup = new Usergroup();
$userGroupDAO = new UsergroupMySqlDAO();
$userGroupEX = new UsergroupMySqlExtDAO();

$today = date("Y-m-d H:i:s"); //i mean it to be date time for client debt change ,and it will not give error in client table

$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");
    $smarty->assign("today_date", date('Y-m-d'));

    // Load All Government
    $allGovernment = $governmentDAO->queryAll();
    $smarty->assign("allGovernment", $allGovernment);

    // Load All stores
    $stores = $storeDAO->queryAll();
    $smarty->assign("stores", $stores);

    $typeClient = $TypeClientDAO->queryAll();
    $smarty->assign("typeClient", $typeClient);


    $allDelegate = R::getAll('SELECT user.* FROM `user`
         WHERE usergroupid = 2');
    $smarty->assign("allDelegate", $allDelegate);
    $allclientarea = $ClientareaDAO->queryAll();
    $smarty->assign("allclientarea", $allclientarea);

    ##get client serial
    $DBName = ConnectionProperty::getDatabase();
    if ($_SESSION['dbname'] != "" && isset($_SESSION['dbname'])) {
        $DBName = $_SESSION['dbname'];
    }


    $clientsData = $clientDAO->queryAll();
    $clientsData = end($clientsData);

    //$nextId = $clientExt->getAutoIncrementValue($DBName);
    $nextId = (int) $clientsData->clientid + 1;
    $smarty->assign("nextId", $nextId);
    $smarty->assign("clientnegative", $_SESSION['clientnegative']);
    //here the smarty templates
    $smarty->display("clientview/add.html");
} elseif ($do == "add") {
    include_once("../public/authentication.php");

    try {
        $flag = add();
        if ($flag == -1) {
            $smarty->assign('msg', 'تم ادخال  اسم العميل  من قبل ');

            $allclientarea = $ClientareaDAO->queryAll();
            $smarty->assign("allclientarea", $allclientarea);
            $smarty->assign("clientnegative", $_SESSION['clientnegative']);
            $smarty->display("clientview/add.html");
        } elseif ($flag == -2) {
            $smarty->assign('checkNo', 'ادخل رقم');
            $allclientarea = $ClientareaDAO->queryAll();
            $smarty->assign("allclientarea", $allclientarea);
            $smarty->assign("clientnegative", $_SESSION['clientnegative']);
            $smarty->display("clientview/add.html");
        } else {
            //header("location:?do=sucess");
            #go to add again instead of show
            $smarty->assign('urldirect', 'clientController.php');
            $smarty->assign('msgnote', "تمت العملية بنجاح");
            $smarty->display("notes2.html");
            exit();
        }
    } catch (Exception $e) {
//print_r($e);
        header("location:?do=error");
    }
} elseif ($do == "addSimpleReturn") {//special for link with supplier
    try {
        $id = add();
        if ($id == -1) {
            //there is client with same name => get its id
            $checkName = $clientDAO->queryByClientname($_POST['txtName']);
            $id = $clientId = $checkName[0]->clientid;
            $supplierId = (int) $_POST["linkedSupplierId"];

            //link
            //remove any link to same suppplier
            $clientExt->removeAnyClientLinkForASupplier($supplierId);

            $checkName[0]->linkedSupplierId = $supplierId;
            $clientDAO->update($checkName[0]);
        }
        echo $id; //it is client id
    } catch (Exception $e) {
//print_r($e);
        header("location:?do=error");
    }
} elseif ($do == "addexcel") {
    //here the permssion check
    include_once("../public/authentication.php");

    //here the smarty templates
    $smarty->display("clientview/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 == "deleteFinaly") {
    include_once("../public/authentication.php");

    try {
        deleteFinaly();

        header("location:?do=show");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "show") {
    include_once("../public/authentication.php");

//    $clientId = $_POST['clientid'];
//    $allclientarea = $ClientareaDAO->queryAll();
//    $smarty->assign("allclientarea", $allclientarea);
//    /* if (isset($clientName) && $clientName != "") {
//      $message = "إسم العميل: " . $clientName;
//      $smarty->assign("message", $message);
//
//      search($clientName);
//      } */
//    if ($clientId == -1 || $clientId == -2) {
//        $clientId = 0;
//    }
//    if (isset($clientId) && !empty($clientId)) {
//        $alldata = $clientDAO->queryAll();
//        $smarty->assign("alldata", $alldata);
//        search($clientId);
//    } else {
//        show();
//    }

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

    $groupData = $userGroupDAO->load($_SESSION['usergroupid']);
    $smarty->assign('groupData', $groupData);

    $smarty->display("clientview/show.html");
    $smarty->assign('customUsergroup', 1);

    $smarty->assign("customCheck", 1);
} elseif ($do == "showByType") {
    include_once("../public/authentication.php");

//    $clientId = $_POST['clientid'];
    $allclientarea = $ClientareaDAO->queryAll();
    $smarty->assign("allclientarea", $allclientarea);
    /* if (isset($clientName) && $clientName != "") {
      $message = "إسم العميل: " . $clientName;
      $smarty->assign("message", $message);

      search($clientName);
      } */
//    if ($clientId == -1 || $clientId == -2) {
//        $clientId = 0;
//    }
//    if (isset($clientId) && !empty($clientId)) {
//        $alldata = $clientDAO->queryAll();
//        $smarty->assign("alldata", $alldata);
//        search($clientId);
//    } else {
//        show();
//    }
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    showByType();
    $smarty->display("clientview/showByType.html");
    $smarty->assign('customUsergroup', 1);

    $smarty->assign("customCheck", 1);
} elseif ($do == "executeOperation") {
    try {
        executeOperation();
        show();
        $smarty->display("clientview/show.html");
    } catch (Exception $e) {
        $smarty->display("error.html");
    }

    $smarty->assign("customCheck", 1);
} elseif ($do == "returndelete") {//returndelete
    include_once("../public/authentication.php");
    try {
        $note = returndelete();
        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 == "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  client
    include_once("../public/authentication.php");
    $loadData = edit();
    $smarty->assign("loadData", $loadData[0]);
    $smarty->assign("tamweenClientDetail", $loadData[1]);

    $smarty->display("clientview/editprint.html");

    $smarty->assign("customPrint", 1);
} elseif ($do == "printdatail") {//edit  client
    include_once("../public/authentication.php");
    $clientid = $_GET["id"];
    $client = R::getRow('SELECT * FROM `client` where clientid = ?', [$clientid]);
    $smarty->assign("client", $client);
    $clientdetails = R::findOne('clientdetails', 'clientid = ?', [$clientid]);
    $smarty->assign("clientdetails", $clientdetails);
    $smarty->display("clientview/printdetail.html");
    $smarty->assign("customPrint", 1);
} elseif ($do == "edit") {//edit  client
    include_once("../public/authentication.php");
    $loadData = edit();
    $smarty->assign("loadData", $loadData[0]);
    $smarty->assign("tamweenClientDetail", $loadData[1]);

    $clientareaData = $ClientareaDAO->load($loadData[0]->clientareaid);
    $goverData = $governAreaDAO->queryByClientareaid($loadData[0]->clientareaid);


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

    $governmentData = $governmentDAO->load($goverData[0]->governmentid);
    $smarty->assign("governmentData", $governmentData);


    $allDelegate = R::getAll('SELECT user.* FROM `user`
         WHERE usergroupid = 2');
    $smarty->assign("allDelegate", $allDelegate);



    // Load All stores
    $stores = $storeDAO->queryAll();
    $smarty->assign("stores", $stores);

    // Load All types client
    $types = $TypeClientDAO->queryAll();
    $smarty->assign("types", $types);

    if ($Programsettingdata->clientdetail == 0) {
        $clientid = $_GET["id"];
        $clientdetails = R::findOne('clientdetails', 'clientid = ?', [$clientid]);
        $smarty->assign("clientdetails", $clientdetails);
    }

    if ($Programsettingdata->ebill == 1) {
        $clientid = $_GET["id"];
        $eclientsetting = R::findOne('eclientsetting', 'clientid = ?', [$clientid]);
        $smarty->assign("eclientsetting", $eclientsetting);
    }


    $smarty->display("clientview/edit.html");
} elseif ($do == "update") { //edit update
    include_once("../public/authentication.php");
    try {
        update();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "downloadphone") {
    $groupData = $userGroupDAO->load($_SESSION['usergroupid']);
    if ($groupData->downloadClientPhones != 1) {
        header("location:login.php?do=en");
        exit();
    }

    $clientData = $clientDAO->queryAll();

    $handle = fopen('../upload/phone.txt', 'w+');
    foreach ($clientData as $data) {
        if ($data->clientmobile)
            fwrite($handle, $data->clientmobile . ',');
        if ($data->clientphone)
            fwrite($handle, $data->clientphone . ',');
    }
    $stat = fstat($handle);
    ftruncate($handle, $stat['size'] - 1);
    fclose($handle);

    $mobFile = fopen('../upload/mobile.txt', 'w+');
    foreach ($clientData as $data) {
        if (strpos($data->clientmobile, '01') === 0)
            fwrite($mobFile, $data->clientmobile . ',');
        if (strpos($data->clientphone, '01') === 0)
            fwrite($mobFile, $data->clientphone . ',');
    }
    $stat = fstat($mobFile);
    ftruncate($mobFile, $stat['size'] - 1);
    fclose($mobFile);
    $smarty->display('clientview/download.html');
} 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("customClient", 1);

//here the global templates
if (!in_array($do, $ajaxDoArr)) {
    $smarty->display("footer.html");
}

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

// add in client tbl
function add() {
    global $clientExt;
    global $clientDAO;
    global $client;
    global $clientDeptChange;
    global $clientDeptChangeDAO;
    global $today;
    global $storeDAO;
    global $TypeClientDAO;
    global $tamweenClientDetailDAO;

//Dailyentry
    global $dailyEntry;

//Dailyentrycreditor دائن
    global $dailyEntryCreditor;

//Dailyentrydebtor مدين
    global $dailyEntryDebtor;

    $clientname = $_POST["txtName"];
    $clientaddress = $_POST["txtAddress"];
    $clientaddress2 = $_POST["txtAddress2"];
    $country = $_POST["country"];
    $clientphone = $_POST["txtPhone"];
    $clientmobile = $_POST["txtMobile"];
    $clientdebt = (float) $_POST["txtDebt"];
    $clientdebt = round($clientdebt, 2);
    $clientdetails = $_POST["textDetails"];
    $clientareaid = (int) $_POST["clientareaid"];
    $clientcode = $_POST["clientcode"];
    $store_all = $_POST["store_all"];
    $debtLimit = $_POST["debtLimit"];
    $postponeDays = (int) $_POST["postponeDays"];
    $typeClient_all = $_POST["typeClient_all"];
    $priceTypeId = $_POST["priceTypeId"];
    $mandobCollectRatio = (float) $_POST["mandobCollectRatio"];

    $noOfPersonsTamween = (int) $_POST["noOfPersonsTamween"];
    $noOfPersonsDa3m = (int) $_POST["noOfPersonsDa3m"];
    $cardNum = $_POST["cardNum"];
    $cardPassword = $_POST["cardPassword"];
    $specialDiscount = (int) $_POST["specialDiscount"];
    $specialDiscountVal = (float) $_POST["specialDiscountVal"];
    $clientRFID = $_POST["clientRFID"];
    $linkedSupplierId = (int) $_POST["linkedSupplierId"];
    $taxnumber = $_POST["taxnumber"];
    $password = $_POST["password"];
    $booking_date = $_POST["booking_date"];
    $rehearsal_date = $_POST["rehearsal_date"];
    $shoulder = $_POST["shoulder"];
    $how_much = $_POST["how_much"];
    $jacket_length = $_POST["jacket_length"];
    $jacket_expand = $_POST["jacket_expand"];
    $sleeve_head = $_POST["sleeve_head"];
    $pants_beam = $_POST["pants_beam"];
    $pants_stone = $_POST["pants_stone"];
    $pants_hash = $_POST["pants_hash"];
    $pants_knee = $_POST["pants_knee"];
    $pants_thigh = $_POST["pants_thigh"];
    $pants_man = $_POST["pants_man"];
    $samanah = $_POST["samanah"];
    $pants_length = $_POST["pants_length"];
    $sudairi_belly = $_POST["sudairi_belly"];
    $sudairi_chest = $_POST["sudairi_chest"];
    $sudairi_length = $_POST["sudairi_length"];
    $size_jackt = $_POST["size_jackt"];
    $clientdetail = $_POST["clientdetail"];

    $egovernorate = $_POST["egovernorate"];
    $ecity = $_POST["ecity"];
    $estreet = $_POST["estreet"];
    $ebuildingNum = $_POST["ebuildingNum"];
    $etaxType = $_POST["etaxType"];
    $etaxNum = $_POST["taxnumber"];
    $ebill = $_POST["ebill"];
    $clientTypeForTree = (int) $_POST["clientTypeForTree"];
    $txtNameE = $_POST["txtNameE"];
    $facility = $_POST["facility"];
    $delegate = $_POST["delegate"];
    $txtemail = $_POST["txtemail"];
    $commercial = $_POST["commercial"];
    $valtaxnumber = $_POST["valtaxnumber"];

    $delegateid = $_POST["delegateid"];


    $checkName = $clientDAO->queryByClientname($clientname);

    if (!empty($checkName)) {
        return -1;
    } else {

        $handle = new upload($_FILES['file']);
        $file = uploadImageswhioutresize($handle, '../upload/clientFile');


        //remove any link to same suppplier // no need as it is new supplier not linked to any client
        //$clientExt->removeAnyClientLinkForASupplier($supplierId);

        $checknumber = filter_var($clientdebt, FILTER_VALIDATE_INT);
        /* if (!$checknumber) {

          return -2;
          } else { */
//insert into client
        $client->clientcode = $clientcode;
        $client->clientaddress = $clientaddress;
        $client->clientaddress2 = $clientaddress2;
        $client->country = $country;
        $client->clientdate = $today;
        $client->clientdebt = $clientdebt;
        $client->clientdetails = $clientdetails;
        $client->clientmobile = $clientmobile;
        $client->clientname = $clientname;
        $client->delegateid = $delegateid;
        $client->clientphone = $clientphone;
        $client->debtLimit = $debtLimit;
        $client->postponeDays = $postponeDays;
        $client->conditions = 0;
        $client->userid = $_SESSION['userid'];
        $client->clientareaid = $clientareaid;
        $client->dailyentryid = 0;
        $client->priceTypeId = $priceTypeId;
        $client->mandobCollectRatio = $mandobCollectRatio;
        $client->specialDiscount = $specialDiscount;
        $client->specialDiscountVal = $specialDiscountVal;
        $client->file = $file;
        $client->addDate = date('Y-m-d');
        $client->webApiId = (int) $_POST['webApiId'];
        $client->clientRFID = $clientRFID;
        $client->linkedSupplierId = $linkedSupplierId;
        $client->taxnumber = $taxnumber;
        $client->password = $password;
        $client->clientTypeForTree = $clientTypeForTree;
        $client->txtNameE = $txtNameE;
        $client->facility = $facility;
        $client->delegate = $delegate;
        $client->txtemail = $txtemail;
        $client->commercial = $commercial;
        $client->valtaxnumber = $valtaxnumber;
        $client->obygyPatientId = $clientcode;


        if (isset($store_all) && $store_all == 1) {
            $client->clientStoreIds = '-10'; //all stores
        } else {
            $client->clientStoreIds = '';
            $stores = $storeDAO->queryAll();
            foreach ($stores as $data) {
                $selectStore = $_POST["store" . $data->storeId];
                if (isset($selectStore) && $selectStore == 1) {
                    $client->clientStoreIds .= $data->storeId . ',';
                }
            }
            $client->clientStoreIds = rtrim($client->clientStoreIds, ",");
        }


        if (isset($typeClient_all) && $typeClient_all == 1) {
            $client->typeclientid = ',-20,'; //all types
        } else {
            $client->typeclientid = ',';
            $types = $TypeClientDAO->queryAll();
            foreach ($types as $data) {
                $selectType = $_POST["type" . $data->typeId];
                if (isset($selectType) && $selectType == 1) {
                    $client->typeclientid .= $data->typeId . ',';
                }
            }
            //$client->typeclientid = rtrim($client->typeclientid, ",");
        }

        $clientid = $clientDAO->insert($client);
        $tamweenClientDetail->clientid = $clientid;
        $tamweenClientDetail->noOfPersonsTamween = $noOfPersonsTamween;
        $tamweenClientDetail->noOfPersonsDa3m = $noOfPersonsDa3m;
        $tamweenClientDetail->cardNum = $cardNum;
        $tamweenClientDetail->cardPassword = $cardPassword;
        $tamweenClientDetailDAO->insert($tamweenClientDetail);
//}
    }

    if (!empty($clientid)) {
//insert into clientdeptchange
        $clientDeptChange->clientdebtchangeafter = $clientdebt;
        $clientDeptChange->clientdebtchangeamount = $clientdebt;
        $clientDeptChange->totalOperationCost = $clientdebt;
        $clientDeptChange->clientdebtchangebefore = 0;
        $clientDeptChange->clientdebtchangedate = $today;
        $clientDeptChange->clientdebtchangemodelid = $clientid;
        $clientDeptChange->clientdebtchangetype = 0;
        $clientDeptChange->clientid = $clientid;
        $clientDeptChange->comment = "";
        $clientDeptChange->processname = "إضافة عميل جديد";
        $clientDeptChange->tablename = "clientController.php";
        $clientDeptChange->userid = $_SESSION['userid'];
        $clientDeptChange->clientareaid = $clientareaid;
        $clientDeptChange->dailyentryid = 0;
        $clientDeptChangeDAO->insert($clientDeptChange);
    }
    if ($clientTypeForTree == 0)
        $parent = 58;
    elseif ($clientTypeForTree == 1)
        $parent = 60;
    $treeId = addTreeElement($clientname, $parent, 3, 0, 1, '', 0, 0);


    $dailyEntry->dDateTime = date('Y-m-d H:i:s');
    $dailyEntry->entryComment = 'تم اضافة عميل ' . $clientname;

    $dailyEntryDebtor->value = $clientdebt;
    $dailyEntryDebtor->accountstreeid = $treeId;

    $dailyEntryCreditor->value = $clientdebt;
    $dailyEntryCreditor->accountstreeid = 121;

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

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

    $rowData = $clientDAO->load($clientid);
    $rowData->dailyentryid = $did;
    $rowData->treeId = $treeId;

    $clientDAO->update($rowData);

    if (!empty($clientid) && $clientdetail == 0) {
        $clientdetails = R::dispense('clientdetails');
        $clientdetails->clientid = $clientid;
        $clientdetails->booking_date = $booking_date;
        $clientdetails->rehearsal_date = $rehearsal_date;
        $clientdetails->shoulder = $shoulder;
        $clientdetails->how_much = $how_much;
        $clientdetails->jacket_length = $jacket_length;
        $clientdetails->jacket_expand = $jacket_expand;
        $clientdetails->sleeve_head = $sleeve_head;
        $clientdetails->pants_beam = $pants_beam;
        $clientdetails->pants_stone = $pants_stone;
        $clientdetails->pants_hash = $pants_hash;
        $clientdetails->pants_knee = $pants_knee;
        $clientdetails->pants_thigh = $pants_thigh;
        $clientdetails->pants_man = $pants_man;
        $clientdetails->samanah = $samanah;
        $clientdetails->pants_length = $pants_length;
        $clientdetails->sudairi_belly = $sudairi_belly;
        $clientdetails->sudairi_chest = $sudairi_chest;
        $clientdetails->sudairi_length = $sudairi_length;
        $clientdetails->size_jackt = $size_jackt;
        R::store($clientdetails);
    }


    if (!empty($clientid) && $ebill == 1) {
        $eclientsetting = R::dispense('eclientsetting');
        $eclientsetting->clientid = $clientid;
        $eclientsetting->egovernorate = $egovernorate;
        $eclientsetting->ecity = $ecity;
        $eclientsetting->estreet = $estreet;
        $eclientsetting->ebuildingNum = $ebuildingNum;
        $eclientsetting->etaxType = $etaxType;
        $eclientsetting->etaxNum = $etaxNum;
        $eclientsetting->clientname = $clientname;
        R::store($eclientsetting);
    }
    return $clientid;
}

function addFromExcel() {
    global $clientExt;
    global $clientDAO;
    global $client;
    global $clientDeptChange;
    global $clientDeptChangeDAO;
    global $today;
    global $storeDAO;
    global $TypeClientDAO;
    global $tamweenClientDetailDAO;

//Dailyentry
    global $dailyEntry;

//Dailyentrycreditor دائن
    global $dailyEntryCreditor;

//Dailyentrydebtor مدين
    global $dailyEntryDebtor;


    ## upload file temporarely
    $handle = new upload($_FILES['clientssheet']);
    $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];

            ##getdata
            $col = 0;
            $clientname = $rowData[$col]; //$_POST["txtName"];
            $col++;
            $clientcode = $rowData[$col]; //$_POST["clientcode"];
            $col++;
            $clientaddress = $rowData[$col]; //$_POST["txtAddress"];
            $col++;
            $clientphone = $rowData[$col]; //$_POST["txtPhone"];
            $col++;
            $clientmobile = $rowData[$col]; //$_POST["txtMobile"];
            $col++;
            $clientdebt = (float) $rowData[$col]; //$_POST["txtDebt"];
            $clientdebt = round($clientdebt, 2);
            $col++;
            $debtLimit = $rowData[$col]; //$_POST["debtLimit"];
            $col++;
            $clientdetails = $rowData[$col]; //$_POST["textDetails"];
            $col++;
            $noOfPersonsDa3m = (int) $rowData[$col];
            $col++;
            $noOfPersonsTamween = (int) $rowData[$col];
            $col++;
            $cardNum = $rowData[$col];
            $col++;
            $cardPassword = $rowData[$col];

            $clientareaid = 0; //$_POST["clientareaid"];
            $store_all = 1; //$_POST["store_all"];
            $typeClient_all = ','; //$_POST["typeClient_all"];
            $priceTypeId = -1; //$_POST["priceTypeId"];


            $checkName = $clientDAO->queryByClientname($clientname);
//            $occurance = $clientExt->countAddressOccurance($clientname);
//            if ($occurance > 0) {
//                $clientname .= "($occurance)";
//            }
            $clientcodeFlag = 1;
            if (!empty($clientcode)) {
                $codeData = $clientDAO->queryByClientcode($clientcode);
                if (count($codeData) > 0) {
                    $clientcodeFlag = 0;
                }
            }
            if (count($checkName) == 0 && $clientcodeFlag == 1) {
                //insert into client
                $client->clientcode = $clientcode;
                $client->clientaddress = $clientaddress;
                $client->clientdate = $today;
                $client->clientdebt = $clientdebt;
                $client->clientdetails = $clientdetails;
                $client->clientmobile = $clientmobile;
                $client->clientname = $clientname;
                $client->clientphone = $clientphone;
                $client->debtLimit = $debtLimit;
                $client->conditions = 0;
                $client->userid = $_SESSION['userid'];
                $client->clientareaid = $clientareaid;
                $client->dailyentryid = 0;
                $client->priceTypeId = $priceTypeId;

                if (isset($store_all) && $store_all == 1) {
                    $client->clientStoreIds = '-10'; //all stores
                } else {
                    $client->clientStoreIds = '';
                    $stores = $storeDAO->queryAll();
                    foreach ($stores as $data) {
                        $selectStore = $_POST["store" . $data->storeId];
                        if (isset($selectStore) && $selectStore == 1) {
                            $client->clientStoreIds .= $data->storeId . ',';
                        }
                    }
                    $client->clientStoreIds = rtrim($client->clientStoreIds, ",");
                }


                if (isset($typeClient_all) && $typeClient_all == 1) {
                    $client->typeclientid = ',-20,'; //all types
                } else {
                    $client->typeclientid = ',';
                    $types = $TypeClientDAO->queryAll();
                    foreach ($types as $data) {
                        $selectType = $_POST["type" . $data->typeId];
                        if (isset($selectType) && $selectType == 1) {
                            $client->typeclientid .= $data->typeId . ',';
                        }
                    }
                    //$client->typeclientid = rtrim($client->typeclientid, ",");
                }

                $client->addDate = date('Y-m-d');
                $clientid = $clientDAO->insert($client);
                $tamweenClientDetail->clientid = $clientid;
                $tamweenClientDetail->noOfPersonsTamween = $noOfPersonsTamween;
                $tamweenClientDetail->noOfPersonsDa3m = $noOfPersonsDa3m;
                $tamweenClientDetail->cardNum = $cardNum;
                $tamweenClientDetail->cardPassword = $cardPassword;
                $tamweenClientDetailDAO->insert($tamweenClientDetail);





                if (!empty($clientid)) {
//insert into clientdeptchange
                    $clientDeptChange->clientdebtchangeafter = $clientdebt;
                    $clientDeptChange->clientdebtchangeamount = $clientdebt;
                    $clientDeptChange->totalOperationCost = $clientdebt;
                    $clientDeptChange->clientdebtchangebefore = 0;
                    $clientDeptChange->clientdebtchangedate = $today;
                    $clientDeptChange->clientdebtchangemodelid = $clientid;
                    $clientDeptChange->clientdebtchangetype = 0;
                    $clientDeptChange->clientid = $clientid;
                    $clientDeptChange->comment = "";
                    $clientDeptChange->processname = "إضافة عميل جديد";
                    $clientDeptChange->tablename = "clientController.php";
                    $clientDeptChange->userid = $clientareaid;
                    $clientDeptChange->clientareaid = $_SESSION['userid'];
                    $clientDeptChange->dailyentryid = 0;
                    $clientDeptChangeDAO->insert($clientDeptChange);
                }


                $treeId = addTreeElement($clientname, 58, 3, 0, 1, '', 0, 0);
                if ($noDailyEntry == 0) {


                    $dailyEntry->dDateTime = date('Y-m-d H:i:s');
                    $dailyEntry->entryComment = 'تم اضافة عميل ' . $clientname;

                    $dailyEntryDebtor->value = $clientdebt;
                    $dailyEntryDebtor->accountstreeid = $treeId;

                    $dailyEntryCreditor->value = $clientdebt;
                    $dailyEntryCreditor->accountstreeid = 121;

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

                    $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $clientid, "clientController.php?do=edit&id=$clientid");
                    $did = $returnedData[1];
                }
                $rowData = $clientDAO->load($clientid);
                $rowData->treeId = (int) $treeId;
                $rowData->dailyentryid = (int) $did;
                $clientDAO->update($rowData);
            }
        }





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

//show
function show() {
    global $clientDAO;
    global $clientExt;
    global $today;
    global $smarty;
    global $TypeClientDAO;

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

//conditions  = 0;
    $shownData = $clientExt->queryAllForShow();

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

    foreach ($shownData as $data) {

        $data->typeclientid = explode(',', $data->typeclientid);
    }

    $typeClient = $TypeClientDAO->queryAll();
    $smarty->assign('types', $typeClient);
    $smarty->assign('shownData', $shownData);


//conditions  = 1;
    $shownDataaz = $clientExt->queryAllForShowaz();

    $sumaz;
    foreach ($shownDataaz as $data) {
        if ($data->conditions == 1) {
            $sumaz += $data->clientdebt;
        }
    }
    $smarty->assign('sumaz', $sumaz);

    foreach ($shownDataaz as $data) {

        $data->typeclientid = explode(',', $data->typeclientid);
    }

    $typeClient = $TypeClientDAO->queryAll();
    $smarty->assign('types', $typeClient);
    $smarty->assign('shownDataaz', $shownDataaz);
}

//show
function showByType() {
    global $clientDAO;
    global $clientExt;
    global $today;
    global $smarty;
    global $TypeClientDAO;


    $TypeClient = $TypeClientDAO->queryAll();
    $TypeClientAll = new stdClass();
    $TypeClientAll->typeId = -20;
    $TypeClientAll->typeName = "كل انواع العملاء";
    //
    $TypeClientNone = new stdClass();
    $TypeClientNone->typeId = ",";
    $TypeClientNone->typeName = "بلا نوع";

    $TypeClientstop = new stdClass();
    $TypeClientstop->typeId = '-000-';
    $TypeClientstop->typeName = "الموقوفين";

    //
    array_unshift($TypeClient, $TypeClientNone, $TypeClientAll, $TypeClientstop);
    foreach ($TypeClient as $value) {
        if ($value->typeId == ",") {//"بلا نوع"
            $value->clients = $clientExt->queryByTypeclientidEqual($value->typeId);
        } else if ($value->typeId == '-000-') {
            $value->clients = $clientExt->queryByTypeclientconditions();
        } else {
            $value->clients = $clientExt->queryByTypeclientid($value->typeId);
        }
    }
    $smarty->assign('types', $TypeClient);
//
//    $shownData = $clientExt->queryAllForShow();
//
//    $sum;
//    foreach ($shownData as $data) {
//        if ($data->conditions == 0) {
//            $sum += $data->clientdebt;
//        }
//    }
//    $smarty->assign('sum', $sum);
//    foreach ($shownData as $data) {
//
//        if ($data->typeclientid != "-20") {
//            $data->typeclientid = explode(',', $data->typeclientid);
//        }
//    }
}

function search($input) {
    global $clientExt;
    global $smarty;


//$clientData = $clientExt->queryByClientNameExt($input);

    $shownData = $clientExt->queryByClientNameExt($input);

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

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

function executeOperation() {
    global $clientDAO;
    global $clientExt;
    global $smarty;
    global $outputString;

    $operationType = $_POST['operation'];

    $choosedItemArr = $_POST['choosedItem'];
    if (count($choosedItemArr) > 0) {
        $i = 1;
        foreach ($choosedItemArr as $clientid) {
            if ($operationType == '1') {//tempdelete
                try {
                    $note = tempdelete($clientid);
                } catch (Exception $e) {

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

            if ($note != "success") {
//get client name
                $clientData = $clientDAO->load($clientid);
                if (count($clientData) > 0) {
                    $clientname = $clientData->clientname;
                    $outputString .= $clientname . ": " . $note . "<br/>";
                }
            } else {
                $outputString = "تمت العملية بنجاح";
            }


            $i++;
        }
        $smarty->assign("outputString", $outputString);
    }
}

function tempdelete($clientid) {
    global $clientDAO;
    global $clientExt;
    $note;
    if (empty($clientid)) {
        $clientid = $_GET['id'];
    }

    if (!empty($clientid)) {
        try {
            $clientExt->deletetemp($clientid);
            $note = "success";
        } catch (Exception $e) {
            $note = "حدث خطأ أثناء إتمام العملية";
        }
    } else {
        $note = "حدث خطأ أثناء إتمام العملية";
    }
    return $note;
}

function returndelete($clientid) {
    global $clientDAO;
    global $clientExt;
    $note;
    if (empty($clientid)) {
        $clientid = $_GET['id'];
    }

    if (!empty($clientid)) {
        try {
            $clientExt->returndelete($clientid);
            $note = "success";
        } catch (Exception $e) {
            $note = "حدث خطأ أثناء إلغاء حذف العميل";
        }
    } else {
        $note = "حدث خطأ أثناء إتمام العملية";
    }
    return $note;
}

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

    $id = $_GET["id"];
    $loadData = $clientDAO->load($id);
    if ($loadData->clientStoreIds != "-10") {
        $loadData->clientStoreIds = explode(',', $loadData->clientStoreIds);
    }

    if ($loadData->typeclientid != ",-20,") {
        $loadData->typeclientid = explode(',', $loadData->typeclientid);
    }

    $tamweenClientDetail = $tamweenClientDetailDAO->queryByClientid($id);
    return array($loadData, $tamweenClientDetail[0]);
}

function deleteFinaly() {
    global $clientDAO;
    global $tamweenClientDetailDAO;

    $id = (int) $_GET["id"];
    if ($id > 1) {//dont delete clent id=1
        $action = $_GET["action"];
        $rowData = $clientDAO->load($id);
        //reverseEntryWithItsID($action);
        reverseEntryWithItsID($rowData->dailyentryid);

        delTreeElementById($rowData->treeId);
        $tamweenClientDetailDAO->deleteByClientid($id);
        $loadData = $clientDAO->delete($id);
    }
}

function update() {
    global $clientExt;
    global $clientDAO;
    global $client;
    global $today;
    global $accountsTreeDAO;
    global $accountsTree;
    global $storeDAO;
    global $TypeClientDAO;
    global $tamweenClientDetailDAO;


    $id = $_POST["id"];

    $conditions = $_POST['conditions'];
    $clientname = $_POST["txtName"];
    $clientaddress = $_POST["txtAddress"];
    $clientaddress2 = $_POST["txtAddress2"];
    $country = $_POST["country"];
    $clientphone = $_POST["txtPhone"];
    $clientmobile = $_POST["txtMobile"];
    $clientdebt = (float) $_POST["txtDebt"];
    $clientdebt = round($clientdebt, 2);
    $clientdetails = $_POST["textDetails"];
    $clientareaid = (int) $_POST["clientareaid"];

    $clientcode = $_POST["clientcode"];
    $dailyentryid = $_POST["dailyentryid"];
    $store_all = $_POST["store_all"];
    $debtLimit = $_POST["debtLimit"];
    $postponeDays = (int) $_POST["postponeDays"];
    $typeClient_all = $_POST["typeClient_all"];
    $priceTypeId = $_POST["priceTypeId"];
    $mandobCollectRatio = (float) $_POST["mandobCollectRatio"];

    $noOfPersonsTamween = (int) $_POST["noOfPersonsTamween"];
    $noOfPersonsDa3m = (int) $_POST["noOfPersonsDa3m"];
    $cardNum = $_POST["cardNum"];
    $cardPassword = $_POST["cardPassword"];
    $specialDiscount = (int) $_POST["specialDiscount"];
    $specialDiscountVal = (float) $_POST["specialDiscountVal"];
    $clientRFID = $_POST["clientRFID"];
    $taxnumber = $_POST["taxnumber"];
    $password = $_POST["password"];

    $booking_date = $_POST["booking_date"];
    $rehearsal_date = $_POST["rehearsal_date"];
    $shoulder = $_POST["shoulder"];
    $how_much = $_POST["how_much"];
    $jacket_length = $_POST["jacket_length"];
    $jacket_expand = $_POST["jacket_expand"];
    $sleeve_head = $_POST["sleeve_head"];
    $pants_beam = $_POST["pants_beam"];
    $pants_stone = $_POST["pants_stone"];
    $pants_hash = $_POST["pants_hash"];
    $pants_knee = $_POST["pants_knee"];
    $pants_thigh = $_POST["pants_thigh"];
    $pants_man = $_POST["pants_man"];
    $samanah = $_POST["samanah"];
    $pants_length = $_POST["pants_length"];
    $sudairi_belly = $_POST["sudairi_belly"];
    $sudairi_chest = $_POST["sudairi_chest"];
    $sudairi_length = $_POST["sudairi_length"];
    $clientdetail = $_POST["clientdetail"];
    $size_jackt = $_POST["size_jackt"];
    $clientdetail_id = $_POST["clientdetail_id"];

    $egovernorate = $_POST["egovernorate"];
    $ecity = $_POST["ecity"];
    $estreet = $_POST["estreet"];
    $ebuildingNum = $_POST["ebuildingNum"];
    $etaxType = $_POST["etaxType"];
    $etaxNum = $_POST["taxnumber"];
    $ebill = $_POST["ebill"];
    $clientTypeForTree = (int) $_POST["clientTypeForTree"];
    $eclientsetting_id = $_POST["eclientsetting_id"];
    $txtNameE = $_POST["txtNameE"];
    $facility = $_POST["facility"];
    $delegate = $_POST["delegate"];
    $txtemail = $_POST["txtemail"];
    $commercial = $_POST["commercial"];
    $valtaxnumber = $_POST["valtaxnumber"];
    $delegateid = $_POST["delegateid"];


    $handle = new upload($_FILES['file']);
    $file = updateImagesWithoutresiz($handle, "oldfile", '../upload/clientFile');

    $clientData = $clientDAO->load($id);
    $oldfile = $clientData->file;
//update into client
    $client->clientcode = $clientcode;
    $client->delegateid = $delegateid;
    $client->clientid = $id;
    $client->clientaddress = $clientaddress;
    $client->clientaddress2 = $clientaddress2;
    $client->country = $country;
    $client->clientdate = $today;
    $client->clientdebt = $clientdebt;
    $client->clientdetails = $clientdetails;
    $client->clientmobile = $clientmobile;
    $client->clientname = $clientname;
    $client->clientphone = $clientphone;
    $client->conditions = $conditions;
    $client->debtLimit = $debtLimit;
    $client->postponeDays = $postponeDays;
    $client->userid = $clientData->userid;
    $client->lastEditUser = $_SESSION['userid'];
    $client->clientareaid = $clientareaid;
    $client->dailyentryid = $dailyentryid;
    $client->priceTypeId = $priceTypeId;
    $client->mandobCollectRatio = $mandobCollectRatio;
    $client->specialDiscount = $specialDiscount;
    $client->specialDiscountVal = $specialDiscountVal;
    $client->file = $file;
    $client->inUse = 0;
    $client->clientRFID = $clientRFID;
    $client->taxnumber = $taxnumber;
    $client->password = $password;
    $client->clientTypeForTree = $clientTypeForTree;
    $client->txtNameE = $txtNameE;
    $client->facility = $facility;
    $client->delegate = $delegate;
    $client->txtemail = $txtemail;
    $client->commercial = $commercial;
    $client->valtaxnumber = $valtaxnumber;


    if (isset($store_all) && $store_all == 1) {
        $client->clientStoreIds = '-10'; //all stores
    } else {
        $client->clientStoreIds = '';
        $stores = $storeDAO->queryAll();
        foreach ($stores as $data) {
            $selectStore = $_POST["store" . $data->storeId];
            if (isset($selectStore) && $selectStore == 1) {
                $client->clientStoreIds .= $data->storeId . ',';
            }
        }
        $client->clientStoreIds = rtrim($client->clientStoreIds, ",");
    }


    /////////////////////////////////////
    $tamweenClientDetail->clientid = $id;
    $tamweenClientDetail->noOfPersonsTamween = $noOfPersonsTamween;
    $tamweenClientDetail->noOfPersonsDa3m = $noOfPersonsDa3m;
    $tamweenClientDetail->cardNum = $cardNum;
    $tamweenClientDetail->cardPassword = $cardPassword;

    $oldTamweenClientDetail = $tamweenClientDetailDAO->queryByClientid($id);
    if (count($oldTamweenClientDetail) > 0) {
        $tamweenClientDetail->id = $oldTamweenClientDetail[0]->id;
        $tamweenClientDetailDAO->update($tamweenClientDetail);
    } else {
        $tamweenClientDetailDAO->insert($tamweenClientDetail);
    }
    /////////////////////////////////////

    if (isset($typeClient_all) && $typeClient_all == 1) {
        $client->typeclientid = ',-20,'; //all types
    } else {
        $client->typeclientid = ',';
        $types = $TypeClientDAO->queryAll();
        foreach ($types as $data) {
            $selectType = $_POST["type" . $data->typeId];
            if (isset($selectType) && $selectType == 1) {
                $client->typeclientid .= $data->typeId . ',';
            }
        }
        //$client->typeclientid = rtrim($client->typeclientid, ",");
    }

    $oldClient = $clientDAO->load($id);
    $treeClient = $accountsTreeDAO->load($oldClient->treeId);
    if ($clientTypeForTree == 0)
        $parent = 58;
    elseif ($clientTypeForTree == 1)
        $parent = 60;

    if (!isset($treeClient->id) || empty($treeClient->id)) {
        $treeId = addTreeElement($oldClient->clientname, $parent, 3, 0, 1, '', 0, $oldClient->clientdebt);
    } else {
        $treeId = $treeClient->id;
    }


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


    $oldTree->customName = $clientname;
    $oldTree->name = $clientname;
    $oldTree->parent = $parent;


    editTreeElement($oldTree);

    $client->treeId = $treeId;
    // $client->obygyPatientId = $oldClient->obygyPatientId;
    $client->obygyPatientId = $clientcode;

    //update
    $clientExt->updateButNotDept($client);
    if ($ebill == 1) {
        $eclientsetting = R::load('eclientsetting', $eclientsetting_id);
        $eclientsetting->clientid = $id;
        $eclientsetting->egovernorate = $egovernorate;
        $eclientsetting->ecity = $ecity;
        $eclientsetting->estreet = $estreet;
        $eclientsetting->ebuildingNum = $ebuildingNum;
        $eclientsetting->etaxType = $etaxType;
        $eclientsetting->etaxNum = $etaxNum;
        $eclientsetting->clientname = $clientname;
        R::store($eclientsetting);
    }
    if ($clientdetail == 0) {
        $clientdetails = R::load('clientdetails', $clientdetail_id);
        $clientdetails->clientid = $id;
        $clientdetails->booking_date = $booking_date;
        $clientdetails->rehearsal_date = $rehearsal_date;
        $clientdetails->shoulder = $shoulder;
        $clientdetails->how_much = $how_much;
        $clientdetails->jacket_length = $jacket_length;
        $clientdetails->jacket_expand = $jacket_expand;
        $clientdetails->sleeve_head = $sleeve_head;
        $clientdetails->pants_beam = $pants_beam;
        $clientdetails->pants_stone = $pants_stone;
        $clientdetails->pants_hash = $pants_hash;
        $clientdetails->pants_knee = $pants_knee;
        $clientdetails->pants_thigh = $pants_thigh;
        $clientdetails->pants_man = $pants_man;
        $clientdetails->samanah = $samanah;
        $clientdetails->pants_length = $pants_length;
        $clientdetails->sudairi_belly = $sudairi_belly;
        $clientdetails->sudairi_chest = $sudairi_chest;
        $clientdetails->sudairi_length = $sudairi_length;
        $clientdetails->size_jackt = $size_jackt;
        R::store($clientdetails);
    }
}

?>