<?php

//the global file operation
include("../public/impOpreation.php");


//global varable
global $showoutside;

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



//here the db files that include in the file
// GOES HERE ....................
include("../public/include_dao.php");
include_once("dailyentryfun.php");

//Partner
require_once('../models/dao/PartnerDAO.class.php');
require_once('../models/dto/Partner.class.php');
require_once('../models/mysql/PartnerMySqlDAO.class.php');
require_once('../models/mysql/ext/PartnerMySqlExtDAO.class.php');

//Savedaily
require_once ('../models/dao/SavedailyDAO.class.php');
require_once ('../models/dto/Savedaily.class.php');
require_once ('../models/mysql/SavedailyMySqlDAO.class.php');
require_once ('../models/mysql/ext/SavedailyMySqlExtDAO.class.php');

//Partnerwithdrawal
require_once('../models/dao/PartnerwithdrawalDAO.class.php');
require_once('../models/dto/Partnerwithdrawal.class.php');
require_once('../models/mysql/PartnerwithdrawalMySqlDAO.class.php');
require_once('../models/mysql/ext/PartnerwithdrawalMySqlExtDAO.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');

//Breadcrumb
require_once("../library/breadcrumb.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 :- userCTRL

  OPERTATION in Controller

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

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


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



//here goes the instances and general variables
//Partner
$myPartner = new Partner();
$myPartnerRecord = new PartnerMySqlDAO();
$myPartnerEx = new PartnerMySqlExtDAO();

//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();
//mySave
$mySave = new Save();
$mySaveRecord = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();
//savedaily
$mySavedaily = new Savedaily();
$mySavedailyRecord = new SavedailyMySqlDAO();
$mySavedailyEx = new SavedailyMySqlExtDAO();
//Breadcrumb
$breadcrumbObject = new Breadcrumb();
//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();
//Partnerwithdrawal
$myPartnerwithdrawal = new Partnerwithdrawal();
$myPartnerwithdrawalRecord = new PartnerwithdrawalMySqlDAO();
$myPartnerwithdrawalEx = new PartnerwithdrawalMySqlExtDAO();

$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="partnerController.php?do=show"> الشركاء </a> > إضافة شريك ', 'partnerController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


    //here the smarty templates
    $smarty->display("partnerview/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 == "show") {



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

    // here the function that do the action
    $partnerData = show();
    $smarty->assign("partnerData", $partnerData);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    //breadcrumb
    $breadcrumbObject->add('الادارة><a href="partnerController.php?do=show">الشركاء</a> > عرض الشركاء', 'partnerController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);



    //here the smarty templates
    $smarty->display("partnerview/show.html");


    $smarty->assign("customCheck", 1);
} elseif ($do == "tempdelete") {
    //here the permssion check
    include_once("../public/authentication.php");

    $partnerId = $_GET['partnerid'];

    try {
        // here the function that do the action
        tempdelete($partnerId);
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "returndelete") {
    //here the permssion check
    include_once("../public/authentication.php");

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

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


    //breadcrumb
    $breadcrumbObject->add('الادارة><a href="partnerController.php?do=show">الشركاء</a> > تعديل شريك', 'partnerController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


    //here the smarty templates
    $smarty->display("partnerview/edit.html");
} 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 == "executeOperation") {
    //here the permssion check
    include_once("../public/authentication.php");

    // here the function that do the action
    executeOperation();

    $partnerData = show();
    $smarty->assign("partnerData", $partnerData);


    //breadcrumb
    $breadcrumbObject->add('المخازن><a href="storeController.php?do=show">المخازن</a> > عرض المخازن', 'storeController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


    //here the smarty templates
    $smarty->display("partnerview/show.html");

    $smarty->assign("customCheck", 1);
} 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("customPartner", 1);

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

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

// add in Partner tbl
function add() {
    //to use the variable out side the funcion
    global $myPartner;
    global $myPartnerRecord;
    global $accountsTreeDAO;
    global $accountsTree;

    global $myPartnerwithdrawal;
    global $myPartnerwithdrawalRecord;


    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

    //save
    global $mySave;
    global $mySaveRecord;

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

    //Transaction
    $mytransactions = new Transaction();

    $partnerName = $_POST['partnername'];
    $partnerMoney = $_POST['partnermoney'];
    $partnerPercentage = $_POST['partnerpercentage'];
    $comment = $_POST['comment'];

    //insert data in Partner tbl
    $myPartner->conditions = 0;
    $myPartner->partnerdate = date("Y-m-d");
    $myPartner->userid = $_SESSION['userid'];
    $myPartner->partnermoney = $partnerMoney;
    $myPartner->partnername = $partnerName;
    $myPartner->partnerpercentage = $partnerPercentage;
    $myPartner->dailyentryid = 0;



    try {
        $treeId = addTreeElement($partnerName, 128, 4, 0, 1, '', 0, 0);
        $myPartner->treeId = $treeId;

        $partnerId = $myPartnerRecord->insert($myPartner, $comment);



        //add in Partnerwithdrawal tbl
        $myPartnerwithdrawal->conditions = 0;
        $myPartnerwithdrawal->partnerid = $partnerId;
        $myPartnerwithdrawal->partnerwithdrawaldate = date("Y-m-d");
        $myPartnerwithdrawal->partenrwithdrawaltype = 0;
        $myPartnerwithdrawal->partnerwithdrawalvalue = $partnerMoney;
        $myPartnerwithdrawal->partnerafter = $partnerMoney;
        $myPartnerwithdrawal->userid = $_SESSION["userid"];
        $myPartnerwithdrawal->comment = $partnerMoney . "اضافة  شريك   يقيمة  ";
        $myPartnerwithdrawal->dailyentryid = 0;
        $myPartnerwithdrawal->saveid = $_SESSION['saveid'];
        $myPartnerwithdrawal->bankid = 0;
        $myPartnerwithdrawal->bankaccountid = 0;
        $myPartnerwithdrawal->checknum = '';
        $wId = $myPartnerwithdrawalRecord->insert($myPartnerwithdrawal);



        //save session
        $saveid = $_SESSION['saveid'];
        $dataSave = $mySaveRecord->load($saveid);
        $saveValuebefore = $dataSave->savecurrentvalue;
        $dataSave->savecurrentvalue += $partnerMoney;
        $mySaveRecord->update($dataSave);
        insertSavedailyupdate($saveValuebefore, $partnerMoney, 0, $saveid, "اضافة شريك", $partnerId, $dataSave->savecurrentvalue, "partnerController.php", date("Y-m-d H:i:s"));


        //do comit here as we need transction ended before using element of tree that is added in it
        $mytransactions->commit();

        $idTreeSave = $dataSave->treeId;
        $did = addPartnerDailyEntry($partnerName, $partnerMoney, $idTreeSave, $treeId);

        $myPartnerwithdrawal->dailyentryid = $did;
        $myPartnerwithdrawal->partnerwithdrawalid = $wId;
        $myPartnerwithdrawalRecord->update($myPartnerwithdrawal);




        //$mytransactions->commit();
        $message = 'تمت العملية بنجاح';
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $message = 'عفوا لقد حدث خطأ';
    }
}

// show the form
function show() {
    //to use the variable out side the funcion
    global $myPartnerRecord;
    global $myPartnerwithdrawalEx;

    $partnerData = $myPartnerRecord->queryAll();
    foreach ($partnerData as $partner) {
        $queryString = ' and partnerwithdrawal.partnerid =  ' . $partner->partnerid . '';
        $partnerwithdrawalData = $myPartnerwithdrawalEx->queryStringSearch2($queryString);
        $totalone = 0;
        $totaltwo = 0;
        foreach ($partnerwithdrawalData as $mypartnerwithdrawalData) {
            if ($mypartnerwithdrawalData->partenrwithdrawaltype == 0) {
                $totalone += $mypartnerwithdrawalData->partnerwithdrawalvalue;
            } else {
                $totaltwo += $mypartnerwithdrawalData->partnerwithdrawalvalue;
            }
        }
        $partner->totalone = $totalone;
        $partner->totaltwo = $totaltwo;
        $partner->totalall = $totalone - $totaltwo;
    }

    return $partnerData;
}

function tempdelete($partnerId) {
    //to use the variable out side the funcion
    global $myPartner;
    global $myPartnerEx;

    $dailyentryid = $_GET['action'];
    //print_r($dailyentryid . 'del');

    try {

        //update conditions in partner tbl
        $myPartner->partnerdate = date("Y-m-d");
        $myPartner->userid = $_SESSION['userid'];
        $myPartner->conditions = 1;
        $myPartner->partnerid = $partnerId;
        $myPartner->dailyentryid = $dailyentryid;

        if ($myPartnerEx->updateConditions($myPartner)) {

            // reverseEntryWithItsID($dailyentryid);
            $note = "success";
        } else {
            $note = "حدث خطأ";
        }
    } catch (Exception $e) {
        $note = "حدث خطأ ";
    }

    return $note;
}

function returndelete($partnerId) {
    //to use the variable out side the funcion
    global $myPartner;
    global $myPartnerEx;
    global $myPartnerRecord;
    global $dailyEntryDAO;

    global $accountsTreeDAO;
    global $accountsTree;


    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

    //save
    global $mySave;
    global $mySaveRecord;

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

    $dailyentryid = $_GET['action'];
    // print_r($dailyentryid . 'return');
    try {


        //update conditions in partner tbl
        $myPartner->partnerdate = date("Y-m-d");
        $myPartner->userid = $_SESSION['userid'];
        $myPartner->conditions = 0;
        $myPartner->partnerid = $partnerId;
        $myPartner->dailyentryid = $dailyentryid;

        if ($myPartnerEx->updateConditions($myPartner)) {
            //          $loadDailyEntry = $dailyEntryDAO->load($dailyentryid);
////// عمل قيد جديد
//
//            $dailyEntry->dComment = 'اسم الشريك' . $partnerName;
//            //الي حساب الخزينة
//
//            $dailyEntryDebtorArray = array();
//            $dailyEntryDebtor->value = $loadDailyEntry->totalcreditor;
//            //save session
//            $saveid = $_SESSION['saveid'];
//            $dataSave = $mySaveRecord->load($saveid);
//
//            $idTreeSave = $dataSave->treeId;
//            $dailyEntryDebtor->accountstreeid = $idTreeSave;
//
////end  save data
//            //من حساب جاري الشركاء (اسم الشريك)
//            $dailyEntryCreditorArray = array();
//            $dailyEntryCreditor->value = $loadDailyEntry->totalcreditor;
//            $partnerData = $myPartnerRecord->load($partnerId);
//            $partnerTreeId = $partnerData->treeId;
//            $dailyEntryCreditor->accountstreeid = $partnerTreeId;
//
//
//
//            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
//            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
//            insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
            $note = "success";
        } else {
            $note = "حدث خطأ ";
        }
    } catch (Exception $e) {
        $note = "حدث خطأ ";
    }

    return $note;
}

// edit in table
function edit() {
    //to use the variable out side the funcion
    global $myPartnerRecord;

    //get variable
    $partnerId = $_GET['partnerid'];

    //load data by partnerid
    $loadData = $myPartnerRecord->load($partnerId);

    return $loadData;
}

// update table
function update() {
    //to use the variable out side the funcion
    global $myPartner;
    global $myPartnerRecord;
    global $accountsTreeDAO;
    global $accountsTree;
    global $mySaveRecord;
    global $myPartnerwithdrawalRecord;
    global $myPartnerwithdrawalEx;

    //Transaction
    $utransactions = new Transaction();

    $partnerName = $_POST['partnername'];
    $partnerMoney = $_POST['partnermoney'];
    $partnerPercentage = $_POST['partnerpercentage'];
    $comment = $_POST['comment'];
    $condition = $_POST['conditions'];
    $partnerDate = $_POST['partnerdate'];
    $partnerId = $_POST['partnerid'];

    try {
        //update data in Partner tbl
        $myPartner = $myPartnerRecord->load($partnerId);

        ### remove all old money of partner
        //1-save session
        $saveid = $_SESSION['saveid'];
        $dataSave = $mySaveRecord->load($saveid);
        $saveValuebefore = $dataSave->savecurrentvalue;
        $dataSave->savecurrentvalue -= $myPartner->partnermoney;
        $mySaveRecord->update($dataSave);
        insertSavedailyupdate($saveValuebefore, $myPartner->partnermoney, 1, $saveid, "تعديل شريك", $partnerId, $dataSave->savecurrentvalue, "partnerController.php", date("Y-m-d H:i:s"));

        //2- daily entry
        $pWithdraws = $myPartnerwithdrawalEx->getAllpartnerWithdrawalsNotDel($partnerId);
        foreach ($pWithdraws as $value) {
            reverseEntryWithItsID($value->dailyentryid);
        }
        //3- withdrawls
        $myPartnerwithdrawalEx->updateConditionsOnlyByPartner(1, $partnerId);


        $utransactions->commit();

        $message = 'تمت العملية بنجاح';
    } catch (Exception $ex) {
        $utransactions->rollback();
        $message = 'عفوا لقد حدث خطأ';
    }


    $utransactions = new Transaction();
    try {

        ### add the new balance 0f partner
        //1-save session
        $saveid = $_SESSION['saveid'];
        $dataSave = $mySaveRecord->load($saveid);
        $saveValuebefore = $dataSave->savecurrentvalue;
        $dataSave->savecurrentvalue += $partnerMoney;
        $mySaveRecord->update($dataSave);
        insertSavedailyupdate($saveValuebefore, $partnerMoney, 0, $saveid, "اضافة شريك", $partnerId, $dataSave->savecurrentvalue, "partnerController.php", date("Y-m-d H:i:s"));


        //2- daily entry
        $idTreeSave = $dataSave->treeId;

        //3- withdrawls
        //add in Partnerwithdrawal tbl
        $myPartnerwithdrawal = new stdClass();
        $myPartnerwithdrawal->conditions = 0;
        $myPartnerwithdrawal->partnerid = $partnerId;
        $myPartnerwithdrawal->partnerwithdrawaldate = date("Y-m-d");
        $myPartnerwithdrawal->partenrwithdrawaltype = ($partnerMoney >= 0 ) ? 0 : 1;
        $myPartnerwithdrawal->partnerwithdrawalvalue = abs($partnerMoney);
        $myPartnerwithdrawal->partnerafter = abs($partnerMoney);
        $myPartnerwithdrawal->userid = $_SESSION["userid"];
        $myPartnerwithdrawal->comment = abs($partnerMoney) . "تعديل  شريك   يقيمة  ";
        $myPartnerwithdrawal->dailyentryid = 0;
        $myPartnerwithdrawal->saveid = $_SESSION['saveid'];
        $myPartnerwithdrawal->bankid = 0;
        $myPartnerwithdrawal->bankaccountid = 0;
        $myPartnerwithdrawal->checknum = '';
        $wId = $myPartnerwithdrawalRecord->insert($myPartnerwithdrawal);




        $myPartner->conditions = $condition;
        $myPartner->partnerdate = $partnerDate;
        $myPartner->userid = $_SESSION['userid'];
        $myPartner->partnermoney = $partnerMoney;
        $myPartner->partnername = $partnerName;
        $myPartner->partnerpercentage = $partnerPercentage;


        $myPartnerRecord->update($myPartner, $comment);
        $utransactions->commit();

        $did = addPartnerDailyEntry($myPartner->partnername, $partnerMoney, $idTreeSave, $myPartner->treeId);
        $myPartnerwithdrawal->partnerwithdrawalid = $wId;
        $myPartnerwithdrawal->dailyentryid = $did;
        $myPartnerwithdrawalRecord->update($myPartnerwithdrawal);



        $message = 'تمت العملية بنجاح';
    } catch (Exception $ex) {
        $utransactions->rollback();
        $message = 'عفوا لقد حدث خطأ';
    }
}

function executeOperation() {
    //to use the variable out side the funcion
    global $myPartnerRecord;
    global $smarty;

    $outputString;

    $operationType = $_POST['operation'];
    $smarty->assign("operationType", $operationType);

    $choosedItemArr = $_POST['choosedItem'];

    if (count($choosedItemArr) > 0) {
        foreach ($choosedItemArr as $partnerId) {

            //get partner name
            $partnerData = $myPartnerRecord->load($partnerId);
            $partnerName = $partnerData->partnername;

            if ($operationType == '1') {
                //tempdelete
                $note = tempdelete($partnerId);


                if ($note != "success") {
                    $outputString .= $partnerName . ": " . $note . "<br/>";
                } else {
                    $outputString = "تمت العملية بنجاح";
                }
            } elseif ($operationType == "2") {
                //returndelete
                $note = returndelete($partnerId);
                if ($note != "success") {
                    $outputString .= $partnerName . ": " . $note . "<br/>";
                } else {
                    $outputString = "تمت العملية بنجاح";
                }
            }
        }

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

function insertSavedailyupdate($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename, $mydate) {

    //to use the variable out side the funcion
    global $mySavedaily;
    global $mySavedailyRecord;

    //insert in Savedaily tbl
    $mySavedaily->savedailydate = $mydate; //date("Y-m-d");
    $mySavedaily->userid = $_SESSION['userid'];
    $mySavedaily->savedailysavebefore = $savedailysavebefore;
    $mySavedaily->savedailychangeamount = $savedailychangeamount;
    $mySavedaily->savedailychangetype = $savedailychangetype;
    $mySavedaily->saveid = $saveid;
    $mySavedaily->processname = $processname;
    $mySavedaily->savedailymodelid = $savedailymodelid;
    $mySavedaily->savedailysaveafter = $savedailysaveafter;
    $mySavedaily->tablename = $tablename;
    if (isset($_SESSION['client_id']) && !empty($_SESSION['client_id'])) {
        $mySavedaily->clientid = $_SESSION['client_id'];
    } else {
        $mySavedaily->clientid = 0;
    }

    $mySavedailyRecord->insert($mySavedaily);
}

function addPartnerDailyEntry($partnerName, $partnerMoney, $idTreeSave, $treeId) {
    $dailyEntry = new stdClass();
    $dailyEntryDebtor = new stdClass();
    $dailyEntryCreditor = new stdClass();


    $dailyEntry->entryComment = 'اسم الشريك' . $partnerName;

    //  //الي حساب الخزينة
    $dailyEntryDebtorArray = array();
    $dailyEntryDebtor->value = $partnerMoney;
    $dailyEntryDebtor->accountstreeid = $idTreeSave;


    //من حساب جاري الشركاء (اسم الشريك)
    $dailyEntryCreditorArray = array();
    $dailyEntryCreditor->value = $partnerMoney;
    $dailyEntryCreditor->accountstreeid = $treeId;
    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
    $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);

    $did = $returnedData[1];
    return $did;
}

?>