<?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");
include_once("dailyentryfun.php");


//here the db files that include in the file
// GOES HERE ....................
include("../public/include_dao.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');

//Kempiala
require_once('../models/dao/KempialaDAO.class.php');
require_once('../models/dto/Kempiala.class.php');
require_once('../models/mysql/KempialaMySqlDAO.class.php');
require_once('../models/mysql/ext/KempialaMySqlExtDAO.class.php');
//Supplier
require_once('../models/dao/SupplierDAO.class.php');
require_once('../models/dto/Supplier.class.php');
require_once('../models/mysql/SupplierMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierMySqlExtDAO.class.php');

//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');
//Breadcrumb
require_once("../library/breadcrumb.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 :- assetsCTRL

  OPERTATION in Controller

  1-display add form
  2- add in Assets tble
  3-display sucess or error
  4-display show form
  5-delete from Assets tbl
  6-edit in Assets data

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


//here the global templates
$smarty->display("header.html");



//here goes the instances and general variables
//Clientdebtchange
$Clientdebtchange = new Clientdebtchange();
$ClientdebtchangeDAO = new ClientdebtchangeMySqlDAO();
$ClientdebtchangeEX = new ClientdebtchangeMySqlExtDAO();

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

$Kempiala = new Kempiala();
$KempialaDAO = new KempialaMySqlDAO();
$KempialaEX = new KempialaMySqlExtDAO();

//Supplier
$Supplier = new Supplier();
$SupplierDAO = new SupplierMySqlDAO();
$SupplierEX = new SupplierMySqlExtDAO();

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

//Breadcrumb
$breadcrumbObject = new Breadcrumb();

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



//Dailyentry
$dailyEntry2 = new Dailyentry();
$dailyEntryDAO2 = new DailyentryMySqlDAO();
$dailyEntryEX2 = new DailyentryMySqlExtDAO();

//Dailyentrycreditor دائن
$dailyEntryCreditor2 = new Dailyentrycreditor();
$dailyEntryCreditorDAO2 = new DailyentrycreditorMySqlDAO();
$dailyEntryCreditorEX2 = new DailyentrycreditorMySqlExtDAO();

//Dailyentrydebtor مدين
$dailyEntryDebtor2 = new Dailyentrydebtor();
$dailyEntryDebtorDAO2 = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX2 = new DailyentrydebtorMySqlExtDAO();

//Accountstree
$accountsTree2 = new Accountstree();
$accountsTreeDAO2 = new AccountstreeMySqlDAO();
$accountsTreeEX2 = new AccountstreeMySqlExtDAO();

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();
//check and use the condetion that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");

    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="kempialaController.php?do=show">الكمبياله</a> > اضافة كمبياله', 'kempialaController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


    $allclientdata = getallclient();
    $smarty->assign("allclientdata", $allclientdata);

    $today = date("Y-m-d");
    $smarty->assign("today", $today);


    // add old asset
    $smarty->display("kempialaview/add.html");
} elseif ($do == "add") {

    //here the permssion check
    include_once("../public/authentication.php");

    try {
        //here the function that do the action
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "addsell") {

    //here the permssion check
    include_once("../public/authentication.php");

    try {
        //here the function that do the action
        addsell();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "show") {

    //here the permssion check
    include_once("../public/authentication.php");
    $clientId = $_POST['clientId'];

    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="kempialaController.php?do=show">الكمبياله</a> > عرض الكمبيالات', 'kempialaController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


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


    $allclientdata = getallclient();
    $smarty->assign("allclientdata", $allclientdata);

    $myClient = $ClientDAO->load($clientId);
    $smarty->assign("myClient", $myClient);

    // here the function that do the action
    $smarty->assign('type', "avelabel");
    show($clientId);

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

    //here the permssion check
    include_once("../public/authentication.php");


    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="kempialaController.php?do=show">الكمبياله</a> > عرض الكمبيالات', 'kempialaController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);





    $allclientdata = getallclient();
    $smarty->assign("allclientdata", $allclientdata);

    // here the function that do the action


    $message = "عرض الكمبيالات المنتهيه ";
    $smarty->assign('message', $message);
    showexit();

    //here the smarty templates
    $smarty->display("kempialaview/show.html");
} elseif ($do == "sell") {
    //here the permssion check
    include_once("../public/authentication.php");

    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="kempialaController.php?do=show">الكمبياله</a> > اضافة كمبياله', 'kempialaController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


    $allSupplierdata = getallSupplier();
    //print_r($allSupplierdata);
    $smarty->assign("allSupplierdata", $allSupplierdata);

    $today = date("Y-m-d");
    $smarty->assign("today", $today);


    $showData = edit();
    $smarty->assign("showData", $showData);



    // add old asset
    $smarty->display("kempialaview/sell.html");
} elseif ($do == "showsold") {

    //here the permssion check
    include_once("../public/authentication.php");


    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="kempialaController.php?do=show">الكمبياله</a> > عرض الكمبيالات', 'kempialaController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);





    $allclientdata = getallclient();
    $smarty->assign("allclientdata", $allclientdata);




    // here the function that do the action
    $message = "عرض الكمبيالات المباعه ";
    $smarty->assign('message', $message);
    showsold();
    $smarty->assign('type', "sold");
    //here the smarty templates
    $smarty->display("kempialaview/show.html");
} elseif ($do == "delete") {
    //here the permssion check
    include_once("../public/authentication.php");

    try {
        $id = $_REQUEST["id"];
        // here the function that do the action
        delete($id);
        header("location:?do=sucess");
    } catch (Exception $e) {
        // print_r($e);
        header("location:?do=error");
    }
} elseif ($do == "edit") {
    //here the permssion check
    include_once("../public/authentication.php");

    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="kempialaController.php?do=show">الكمبياله</a> > تعديل كمبياله', 'kempialaController.php', 0);
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);





    $showData = edit();
    $smarty->assign("showData", $showData);



    $allclientdata = getallclient();
    $smarty->assign("allclientdata", $allclientdata);




    $smarty->display("kempialaview/edit.html");
} elseif ($do == "editprint") {
    //here the permssion check
    include_once("../public/authentication.php");

    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="kempialaController.php?do=show">الكمبياله</a> > عرض كمبياله', 'kempialaController.php', 0);
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);





    $showData = edit();
    $smarty->assign("showData", $showData);



    $smarty->assign("customPrint", 1);
    $smarty->display("kempialaview/editprint.html");
} elseif ($do == "deletefinal") {
    //here the permssion check
    include_once("../public/authentication.php");

    try {
        // here the function that do the action
        deletefinal();

        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "update") {
    //here the permssion check
    include_once("../public/authentication.php");

    try {
        // here the function that do the action
        update();

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




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


//here the global templates
$smarty->assign("customValidation", 1);
$smarty->display("footer.html");

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

// load Assets data
//sellkemp
function addsell() {



    global $Supplierdebtchange;
    global $SupplierdebtchangeDAO;
    global $SupplierdebtchangeEX;


    global $SupplierDAO;
    global $Supplier;
    global $SupplierEX;

    global $Kempiala;
    global $KempialaDAO;
    global $KempialaEX;

    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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


    //Transaction
    $mytransactions = new Transaction();
    try {


        $supplierid = $_POST["supplierID"];
        $suppliercomment = $_POST["suppliercomment"];

        $value = $_POST['value'];
        $today = date("Y-m-d");

        $kempialaid = $_POST["id"];

        $kempialadata = $KempialaDAO->load($kempialaid);

        //print_r($kempialadata);
        $value = $kempialadata->value;

        $Kempiala->selling = 1;
        $Kempiala->sellingdate = $today;
        $Kempiala->supplierID = $supplierid;
        $Kempiala->id = $kempialaid;
        $KempialaEX->updatesell($Kempiala, $suppliercomment);

        if ($kempialaid) {
            //////////////////////////


            $supplierdata = $SupplierDAO->load($supplierid);
            $debtBefore = $supplierdata->suppliercurrentDebt;


            $Supplier->suppliercurrentDebt = ($debtBefore - $value);
            $Supplier->supplierid = $supplierid;
            $Supplier->userid = $_SESSION['userid'];
            $Supplier->supplierdate = date("Y-m-d");

            //$supplierExtDAO -> updateSupplierCurrentDebt();
            $SupplierEX->updatedept($Supplier);

            //---------------------------------------
            //Insert in supplier dept cahnge
            $Supplierdebtchange->supplierdebtchangebefore = $debtBefore;
            $Supplierdebtchange->supplierid = $supplierid;

            $Supplierdebtchange->supplierdebtchangeamount = $value;
            $Supplierdebtchange->supplierdebtchangetype = 1;
            $Supplierdebtchange->tablename = "kempialaController.php";
            $Supplierdebtchange->supplierdebtchangemodelid = $kempialaid;
            $Supplierdebtchange->supplierdebtchangeafter = $debtBefore - $value;
            $Supplierdebtchange->supplierdebtchangedate = date("Y-m-d");
            $Supplierdebtchange->userid = $_SESSION['userid'];
            $Supplierdebtchange->processname = "بيع كمبياله";
            $Supplierdebtchange->dailyentryid = 0;


            //print_r($Supplierdebtchange);
            //Insert
            $SupplierdebtchangeDAO->insert($Supplierdebtchange);
            ///////////////////////////
        }

        $supplierData = $SupplierDAO->load($supplierid);

        $dailyEntry->entryComment = 'تم بيع الكمبيالة للمورد ( ' . $supplierData->suppliername . ' ) ';


//// من حساب  الدائنون
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $value;
        $supplierTreeId = $supplierdata->treeId;
        $dailyEntryDebtor->accountstreeid = $supplierTreeId;

//// الي حساب أوراق الدفع (رقم الكمبيالات )
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $value;
        $dailyEntryCreditor->accountstreeid = 91;

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

        insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);


        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
}

// add in kemp tbl
function add() {



    global $Clientdebtchange;
    global $ClientdebtchangeDAO;
    global $ClientdebtchangeDAO;


    global $Client;
    global $ClientDAO;
    global $ClientEX;

    global $Kempiala;
    global $KempialaDAO;
    global $KempialaEX;


    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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


//Transaction
    $mytransactions = new Transaction();
    try {

        $clientID = $_POST["clientID"];
        $recievingdate = $_POST["recievingdate"];
        $expiredate = $_POST["expiredate"];
        $value = $_POST["value"];
        $clientcomment = $_POST["clientcomment"];


        $Kempiala->clientcomment = $clientcomment;
        $Kempiala->clientID = $clientID;
        $Kempiala->conditions = 0;
        $Kempiala->expiredate = $expiredate;
        $Kempiala->value = $value;
        $Kempiala->recievingdate = $recievingdate;
        $Kempiala->selling = 0;
        $Kempiala->suppliercomment = "";
        $Kempiala->supplierID = 0;
        $Kempiala->dailyentryid = 0;


        $kempialaid = $KempialaDAO->insert($Kempiala);



        if ($kempialaid) {
            //////////////////////////


            $clientdata = $ClientDAO->load($clientID);
            $debtBefore = $clientdata->clientdebt;

            //print("mmm".$debtBefore);
            /* if($clientdata->clientdebt <=0)
              {
              $Client->clientdebt =0;
              $KempialaDAO->delete($kempialaid);
              header("location:?do=error"); //cannot subtract debt from check amount
              }
              else */ {
                //print("else");
                //if($debtBefore >= $value)
                {
                    //print("debtBefore:".$debtBefore);
                    $Client->clientdebt = ($debtBefore - $value);
                }
                /* else
                  {
                  //print("else");
                  //  $CheckdepositDAO->delete($kempialaid);
                  header("location:?do=error");
                  exit;//can't subtract
                  } */
            }

            //print_r("debtBefore".$debtBefore."<br>");
            $Client->clientdate = $today;
            $Client->clientdebt = ($debtBefore - $value);
            $Client->clientid = $clientID;
            $Client->userid = $_SESSION['userid'];
            //$supplierExtDAO -> updateSupplierCurrentDebt();
            $ClientEX->updatedept($Client);

            //---------------------------------------
            //Insert in supplier dept cahnge
            $Clientdebtchange->clientdebtchangebefore = $debtBefore;

            $Clientdebtchange->clientdebtchangeamount = $value;
            $Clientdebtchange->clientdebtchangetype = 1;
            $Clientdebtchange->clientid = $clientID;
            $Clientdebtchange->tablename = "kempialaController.php";
            $Clientdebtchange->clientdebtchangemodelid = $kempialaid;
            $Clientdebtchange->clientdebtchangeafter = $debtBefore - $value;
            $Clientdebtchange->clientdebtchangedate = date("Y-m-d");
            $Clientdebtchange->userid = $_SESSION['userid'];
            $Clientdebtchange->processname = "شراء كمبياله";
            $Clientdebtchange->dailyentryid = 0;


            //print_r($Clientdebtchange);
            //Insert
            $ClientdebtchangeDAO->insert($Clientdebtchange);

            ///////////////////////////
        }
        $clientData = $ClientDAO->load($clientID);

        $dailyEntry->entryComment = 'تم اضافة كمبيالة للعميل ( ' . $clientData->clientname . ' ) ';


//// الكمبيالات
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $value;
        $dailyEntryDebtor->accountstreeid = 91;

//// الى حساب المدينون


        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $value;
        $clientTreeId = $clientdata->treeId;
        $dailyEntryCreditor->accountstreeid = $clientTreeId;

        array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
        $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
        $did = $returnedData[1];

        $rowData = $KempialaDAO->load($kempialaid);

        $Kempiala->clientcomment = $rowData->clientcomment;
        $Kempiala->clientID = $rowData->clientID;
        $Kempiala->conditions = $rowData->conditions;
        $Kempiala->expiredate = $rowData->expiredate;
        $Kempiala->value = $rowData->value;
        $Kempiala->recievingdate = $rowData->recievingdate;
        $Kempiala->selling = $rowData->selling;
        $Kempiala->suppliercomment = $rowData->suppliercomment;
        $Kempiala->supplierID = $rowData->supplierID;
        $Kempiala->dailyentryid = $did;

        $KempialaDAO->update($Kempiala);


        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
}

//show sold kemp
function showsold() {
    //to use the variable out side the funcion
    global $Kempiala;
    global $KempialaDAO;
    global $KempialaEX;
    global $Client;
    global $ClientDAO;
    global $ClientEX;


    global $smarty;



    //select all data from Assets tbl

    $clientid = $_REQUEST["clientid"];
    $from = $_REQUEST["from"];
    $to = $_REQUEST["to"];
    $today = date("Y-m-d");

    // required connect
    $paginate = new SmartyPaginate;
    $paginate->connect();
    // set items per page
    $paginate->setLimit(25);

    // get the all colums number
    $allColums = $KempialaEX->queryAllsold(0);
    $paginate->setTotal(count($allColums));

    if ($paginate->getCurrentIndex() != -1) {
        //get the selected data with limitation
        $shownData = $KempialaEX->queryAllsoldlimted($paginate->getCurrentIndex(), $paginate->getLimit(), 0);
    }
    if (empty($_GET['page'])) {
        //get the selected data with limitation
        $shownData = $KempialaEX->queryAllsoldlimted(0, $paginate->getLimit(), 0);
        $paginate->setCurrentItem($_SESSION['SmartyPaginate'][$page]['current_item']);
    }


    // assign your db results to the template
    $smarty->assign('shownData', $shownData);


    // assign {$paginate} var
    $paginate->assign($smarty);
    $paginate->setUrlVar("page");
    //text that show in navgation
    $paginate->setNextText('التالى');
    $paginate->setPrevText('السابق');
    //add any varaible in url
    $paginate->setUrl('kempialaController.php?do=showsold&');
}

//show expier
function showexit() {
    //to use the variable out side the funcion
    global $Kempiala;
    global $KempialaDAO;
    global $KempialaEX;


    global $smarty;



    //select all data from Assets tbl

    $clientid = $_REQUEST["clientid"];
    $from = $_REQUEST["from"];
    $to = $_REQUEST["to"];
    $today = date("Y-m-d");

    // required connect
    $paginate = new SmartyPaginate;
    $paginate->connect();
    // set items per page
    $paginate->setLimit(25);

    // get the all colums number
    $allColums = $KempialaEX->queryAllexpier(0, $today);
    $paginate->setTotal(count($allColums));

    if ($paginate->getCurrentIndex() != -1) {
        //get the selected data with limitation
        $shownData = $KempialaEX->queryAllexpierlimted($paginate->getCurrentIndex(), $paginate->getLimit(), 0, $today);
    }
    if (empty($_GET['page'])) {
        //get the selected data with limitation
        $shownData = $KempialaEX->queryAllexpierlimted(0, $paginate->getLimit(), 0, $today);
        $paginate->setCurrentItem($_SESSION['SmartyPaginate'][$page]['current_item']);
    }


    // assign your db results to the template
    $smarty->assign('shownData', $shownData);

    $smarty->assign('type', "ex");
    // assign {$paginate} var
    $paginate->assign($smarty);
    $paginate->setUrlVar("page");
    //text that show in navgation
    $paginate->setNextText('التالى');
    $paginate->setPrevText('السابق');
    //add any varaible in url
    $paginate->setUrl('kempialaController.php?do=showexit&');
}

// show the available kemp
function show($clientId) {
    global $Kempiala;
    global $KempialaDAO;
    global $KempialaEX;
    global $smarty;

    $today = date("Y-m-d");

    $clientid = $_REQUEST["clientid"];
    $from = $_REQUEST["from"];
    $to = $_REQUEST["to"];

    $message = "عرض الكمبيالات المتاحه ";
    $smarty->assign('message', $message);

    // required connect
    $paginate = new SmartyPaginate;
    $paginate->connect();
    // set items per page
    $paginate->setLimit(25);

    // get the all colums number
    $allColums = $KempialaEX->queryAllex(0, $today);
    $paginate->setTotal(count($allColums));
    if (isset($clientId) && $clientId != -1) {
        $shownData = $KempialaDAO->queryByClientID($clientId);
    } else {
        if ($paginate->getCurrentIndex() != -1) {
            $shownData = $KempialaEX->queryAlllimted($paginate->getCurrentIndex(), $paginate->getLimit(), 0, $today);
        }
        if (empty($_GET['page'])) {
            $shownData = $KempialaEX->queryAlllimted(0, $paginate->getLimit(), 0, $today);
            $paginate->setCurrentItem($_SESSION['SmartyPaginate'][$page]['current_item']);
        }
    }
    // assign your db results to the template
    $smarty->assign('shownData', $shownData);

    // assign {$paginate} var
    $paginate->assign($smarty);
    $paginate->setUrlVar("page");
    //text that show in navgation
    $paginate->setNextText('التالى');
    $paginate->setPrevText('السابق');
    //add any varaible in url
    $paginate->setUrl('kempialaController.php?do=show&');
}

//update tempdelete
function delete($id) {
    global $Clientdebtchange;
    global $ClientdebtchangeDAO;
    global $ClientdebtchangeDAO;

    global $Client;
    global $ClientDAO;
    global $ClientEX;

    global $Kempiala;
    global $KempialaDAO;
    global $KempialaEX;


    //Transaction
    $mytransactions = new Transaction();
    try {

        //$id=$_GET["id"];

        $Kempialadata = $KempialaDAO->load($id);


        $clientID = $Kempialadata->clientID;

        $kempialaid = $id;

        $value = $Kempialadata->value;

        $today = date("Y-m-d");


        $Kempiala->id = $id;
        $Kempiala->conditions = 1;
        $KempialaEX->updatedel($Kempiala);

        if ($kempialaid) {
            //////////////////////////



            $clientdata = $ClientDAO->load($clientID);
            $debtBefore = $clientdata->clientdebt;




            //print("debtBefore:".$debtBefore);
            $Client->clientdebt = ($debtBefore + $value);


            //print_r("debtBefore".$debtBefore."<br>");
            $Client->clientdate = $today;
            $Client->clientdebt = ($debtBefore + $value);
            $Client->clientid = $clientID;
            $Client->userid = $_SESSION['userid'];
            //$supplierExtDAO -> updateSupplierCurrentDebt();
            $ClientEX->updatedept($Client);

            //---------------------------------------
            //Insert in supplier dept cahnge
            $Clientdebtchange->clientdebtchangebefore = $debtBefore;
            $Clientdebtchange->clientid = $clientID;
            $Clientdebtchange->clientdebtchangeamount = $value;
            $Clientdebtchange->clientdebtchangetype = 0;
            $Clientdebtchange->tablename = "kempialaController.php";
            $Clientdebtchange->clientdebtchangemodelid = $kempialaid;
            $Clientdebtchange->clientdebtchangeafter = $debtBefore + $value;
            $Clientdebtchange->clientdebtchangedate = date("Y-m-d");
            $Clientdebtchange->userid = $_SESSION['userid'];
            $Clientdebtchange->processname = "الغاء كمبياله كمبياله";
            $Clientdebtchange->dailyentryid = 0;


            //print_r($Clientdebtchange);
            //Insert
            $ClientdebtchangeDAO->insert($Clientdebtchange);
        }
        reverseEntryWithItsID($Kempialadata->dailyentryid, 1);


        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
}

function deletefinal() {

    //to use the variable out side the funcion
    global $Clientdebtchange;
    global $ClientdebtchangeDAO;
    global $ClientdebtchangeDAO;

    global $Supplierdebtchange;
    global $SupplierdebtchangeDAO;
    global $SupplierdebtchangeEX;


    global $SupplierDAO;
    global $Supplier;
    global $SupplierEX;


    global $Client;
    global $ClientDAO;
    global $ClientEX;

    global $Kempiala;
    global $KempialaDAO;
    global $KempialaEX;


    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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



//Transaction
    $mytransactions = new Transaction();
    try {

        $id = $_GET["id"];

        $kempdata = $KempialaDAO->load($id);
        $selling = $kempdata->selling;
        $value = $kempdata->value;
        $supplierid = $kempdata->supplierID;
        $clientId = $kempdata->clientID;
        if ($selling == 1 && $supplierid > 0) {

            $today = date("Y-m-d");

            $kempialaid = $id;



            if ($kempialaid) {
                //////////////////////////


                $supplierdata = $SupplierDAO->load($supplierid);
                $debtBefore = $supplierdata->suppliercurrentDebt;


                $Supplier->suppliercurrentDebt = ($debtBefore + $value);
                $Supplier->supplierid = $supplierid;
                $Supplier->userid = $_SESSION['userid'];
                $Supplier->supplierdate = date("Y-m-d");


                //$supplierExtDAO -> updateSupplierCurrentDebt();
                $SupplierEX->updatedept($Supplier);

                //print_r($Supplier);
                //---------------------------------------
                //Insert in supplier dept cahnge
                $Supplierdebtchange->supplierdebtchangebefore = $debtBefore;
                $Supplierdebtchange->supplierid = $supplierid;

                $Supplierdebtchange->supplierdebtchangeamount = $value;
                $Supplierdebtchange->supplierdebtchangetype = 0;
                $Supplierdebtchange->tablename = "kempialaController.php";
                $Supplierdebtchange->supplierdebtchangemodelid = $kempialaid;
                $Supplierdebtchange->supplierdebtchangeafter = $debtBefore + $value;
                $Supplierdebtchange->supplierdebtchangedate = date("Y-m-d");
                $Supplierdebtchange->userid = $_SESSION['userid'];
                $Supplierdebtchange->processname = "الغاء كمبياله";
                $Supplierdebtchange->dailyentryid = 0;


                //print_r($Supplierdebtchange);
                //Insert
                $SupplierdebtchangeDAO->insert($Supplierdebtchange);
                ///////////////////////////
            }

            ##remove that it was sold so i can sell it again
            $kempdata->selling = 0;
            $kempdata->supplierID = 0;
            $kempdata->sellingdate = "0000-00-00 00:00:00";
            $KempialaDAO->update($kempdata);
        }

        ///// القيد الاول
        //// من حساب المدينون (اسم العميل )
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $value;
        $clientData = $ClientDAO->load($clientId);
        $clientTreeId = $clientData->treeId;
        $dailyEntryDebtor->accountstreeid = $clientTreeId;

//    //// الي حساب أوراق القبض (الكمبيالات)
//    $dailyEntryCreditorArray = array();
//    $dailyEntryCreditor->value = $value;
//    $dailyEntryCreditor->accountstreeid = 91;
//
//    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
//    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
//    print_r('<pre>aaaaaaaaaaaaaaa' . $value);
//    print_r($dailyEntryDebtorArray);
//    print_r('<pre>');
//    print_r('<pre>aaaaaaaaaaaaaaaaaa');
//    print_r($dailyEntryCreditorArray);
//    print_r('<pre>');
//    $a = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
//    print_r($a);
//
//    //// نهاية القيد الاول
/////// القيد الثانى
//    $dailyEntry->entryComment = 'تم الغاء الكمبيالة';
//
//
////// من حساب أوراق  الدفع (الكمبيالات)
//    $dailyEntryDebtorArray2 = array();
//    $dailyEntryDebtor->value = $value;
//    $dailyEntryDebtor->accountstreeid = 91;
//// الى حساب الدائنون (اسم المورد )
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $value;
        $supplierData = $SupplierDAO->load($supplierid);

        $supplierTreeId = $supplierData->treeId;
        $dailyEntryCreditor->accountstreeid = $supplierTreeId;

        $dailyEntry->entryComment = 'تم عكس القيد من العميل (  ' . $clientData->clientname . ' ) الى المورد (   ' . $supplierData->suppliername . ' ) ';



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

        $b = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
//// نهاية القيد الثانى
        //delete($id);

        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
}

// edit in table
function edit() {
    //to use the variable out side the funcion

    global $Kempiala;
    global $KempialaDAO;
    global $KempialaEX;



    $id = $_GET["id"];

    $showData = $KempialaEX->loadEX($id);
    /* print_r("<pre>");
      print_r($showData);

      print_r("<pre>"); */

    return $showData;
}

// update table
function update() {



    global $Kempiala;
    global $KempialaDAO;
    global $KempialaEX;





    $id = $_POST["id"];
    $expiredate = $_POST["expiredate"];
    $clientcomment = $_POST["clientcomment"];


    $Kempiala->id = $id;
    $Kempiala->expiredate = $expiredate;
    $KempialaEX->updatekemp($Kempiala, $clientcomment);
}

//show all asset cat
function showallcat() {
    global $AssetscatDAO;
    global $Assetscat;


    $alldata = $AssetscatDAO->queryByDel(0);
    return $alldata;
}

function getallSupplier() {

    global $SupplierDAO;
    global $Supplier;
    global $SupplierEX;


    $allSupplierdata = $SupplierDAO->queryAll();

    return $allSupplierdata;
}

function getallclient() {

    global $ClientDAO;
    global $Client;
    global $ClientEX;


    $allclientdata = $ClientDAO->queryAll();

    return $allclientdata;
}

?>