<?php

$do = isset($_GET['do']) ? $_GET['do'] : "";
$ajaxDoArr = array("payfromcard");
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("../library/uploadImages.php");
include_once("dailyentryfun.php");

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

//
require_once('../models/dao/PlaystationcardDAO.class.php');
require_once('../models/dto/Playstationcard.class.php');
require_once('../models/mysql/PlaystationcardMySqlDAO.class.php');
require_once('../models/mysql/ext/PlaystationcardMySqlExtDAO.class.php');
//Playstationclientcard
require_once('../models/dao/PlaystationclientcardDAO.class.php');
require_once('../models/dto/Playstationclientcard.class.php');
require_once('../models/mysql/PlaystationclientcardMySqlDAO.class.php');
require_once('../models/mysql/ext/PlaystationclientcardMySqlExtDAO.class.php');
//Playstationclientcardpayhistory
require_once('../models/dao/PlaystationclientcardpayhistoryDAO.class.php');
require_once('../models/dto/Playstationclientcardpayhistory.class.php');
require_once('../models/mysql/PlaystationclientcardpayhistoryMySqlDAO.class.php');
require_once('../models/mysql/ext/PlaystationclientcardpayhistoryMySqlExtDAO.class.php');

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

//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/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 :- unitController

  OPERTATION in Controller

  1-display add form
  2- add in unit tble
  4-display sucess or error
  5-display show and delete
  6-delete from unit tbl
  7-display edit
  8- update unit tbl
  ======================== */

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

//here goes the instances and general variables
//
$playstationCard = new Playstationcard();
$playstationCardDAO = new PlaystationcardMySqlDAO();
$playstationCardEX = new PlaystationcardMySqlExtDAO();
//
$playstationClientCard = new Playstationclientcard();
$playstationClientCardDAO = new PlaystationclientcardMySqlDAO();
$playstationClientCardEX = new PlaystationclientcardMySqlExtDAO();
//
$playstationClientCardPayHistory = new Playstationclientcardpayhistory();
$playstationClientCardPayHistoryDAO = new PlaystationclientcardpayhistoryMySqlDAO();
$playstationClientCardPayHistoryEX = new PlaystationclientcardpayhistoryMySqlExtDAO();

//save
$mySave = new Save();
$mySaveRecord = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();
//savedaily
$mySavedaily = new Savedaily();
$mySavedailyRecord = new SavedailyMySqlDAO();
$mySavedailyEx = new SavedailyMySqlExtDAO();
//Client
$myClientRecord = $clientDAO = new ClientMySqlDAO();
$myClient = $client = new Client();
$myClientEx = $clientEX = new ClientMySqlExtDAO();
//Clientdebtchange
$myClientdebtchange = new Clientdebtchange();
$myClientdebtchangeRecord = $clientDeptChangeDAO = new ClientdebtchangeMySqlDAO();

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

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

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

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

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

    $allPlaystationCards = $playstationCardDAO->queryByDel(0);
    $smarty->assign('allPlaystationCards', $allPlaystationCards);

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

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

    $id = (int) filter_input(INPUT_GET, 'id');

    $playstationCard = $playstationCardDAO->load($id);
    $smarty->assign('playstationCard', $playstationCard);

    //here the smarty templates
    $smarty->display("playStationCardView/edit.html");
} elseif ($do == "update") {
    include_once("../public/authentication.php");

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

    try {
        delete();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //print_r($e);
        header("location:?do=error");
    }
}
##choose , add , show , del pack
elseif ($do == "choosePack") {
    //here the permission check
    include_once("../public/authentication.php");

    $allPlaystationCards = $playstationCardDAO->queryByDel(0);
    $smarty->assign('allPlaystationCards', $allPlaystationCards);

    //here the smarty templates
    $smarty->display("playStationCardView/cards.html");
} elseif ($do == "chargeCard") {
    include_once("../public/authentication.php");

    $cardid = (int) filter_input(INPUT_GET, 'card');
    $smarty->assign('cardid', $cardid);

    $playstationCard = $playstationCardDAO->load($cardid);
    $smarty->assign('playstationCard', $playstationCard);

    //
    $smarty->assign('customplaystationcard', 1);
    $smarty->display("playStationCardView/chargeCard.html");
} elseif ($do == "dochargeCard") {
    include_once("../public/authentication.php");

    try {
        chargeCard();

        $url = 'playStationCardController.php?do=showClientsCards';
        $smarty->assign('urldirect', $url);
        $note = "تمت العملية بنجاح";
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
        //header("location:?do=sucess");
    } catch (Exception $e) {
        //print_r($e);
        header("location:?do=error");
    }
} elseif ($do == "showClientsCards") {

    ##query
    $cardid = (int) filter_input(INPUT_POST, 'PSCardNoClient');
    $client = (int) filter_input(INPUT_POST, 'client');
    $cardStatus = (int) filter_input(INPUT_POST, 'cardStatus');
    $buyfrom = filter_input(INPUT_POST, 'buyfrom');
    $buyto = filter_input(INPUT_POST, 'buyto');
    $endfrom = filter_input(INPUT_POST, 'endfrom');
    $endto = filter_input(INPUT_POST, 'endto');


    $queryString = ' and playstationclientcard.del=0 ';
    if ($cardid > 0) {
        $queryString .= " and playstationclientcard.cardid  = $cardid ";
    }
    if ($client > 0) {
        $queryString .= " and playstationclientcard.clientid  = $client ";
    }
    if ($cardStatus > -1) {
        $queryString .= " and playstationclientcard.cardStatus  = $cardStatus ";
    }
    if (!empty($buyfrom)) {
        $queryString .= ' and date(buyDate) >= "' . $buyfrom . '"  ';
    }
    if (!empty($buyto)) {
        $queryString .= ' and date(buyDate) <= "' . $buyto . '"  ';
    }
    if (!empty($endfrom)) {
        $queryString .= ' and date(cardEndDate) >= "' . $endfrom . '"  ';
    }
    if (!empty($endto)) {
        $queryString .= ' and date(cardEndDate) <= "' . $endto . '"  ';
    }

    if ($queryString == ' and playstationclientcard.del=0 ') {
        $from = date('Y-m-d') . " 00:00:00";
        $to = date('Y-m-d') . " 23:59:59";
        $queryString .= ' and buyDate >= "' . $from . '" and buyDate <= "' . $to . '" ';
    }

    $allPlaystationClientCard = $playstationClientCardEX->queryAllByQueryString($queryString);
    $smarty->assign('allPlaystationClientCard', $allPlaystationClientCard);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    //
    $smarty->assign('customplaystationcard', 1);
    $smarty->display("playStationCardView/showClientsCards.html");
} elseif ($do == "deleteClientCard") {
    include_once("../public/authentication.php");

    try {
        deleteClientCard();

        $url = 'playStationCardController.php?do=showClientsCards';
        $smarty->assign('urldirect', $url);
        $note = "تمت العملية بنجاح";
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } catch (Exception $e) {
        //print_r($e);
        header("location:?do=error");
    }
} elseif ($do == "handleExpiredCards") {
    include_once("../public/authentication.php");

    try {
        $clientId = (int) filter_input(INPUT_POST, 'clientId');
        handleExpiredCards($clientId);
        echo 1;
    } catch (Exception $e) {
        //print_r($e);
        echo -1;
    }
}
##
elseif ($do == "payCard") {
    //include_once("../public/authentication.php");

    $id = (int) filter_input(INPUT_GET, 'id');
    //get $restaurantPlaystationPlay data with id
    $closeData = CURL_IT2(array('id' => $id, 'json_ret' => 1), 'restaurantplaystationpalyajax.php?do=getCloseData');
    $closeData = json_decode($closeData);
    $smarty->assign("closeData", $closeData);

    $smarty->assign("customplaystationcard", 1);
    $smarty->display("playStationCardView/payCard.html");
} elseif ($do == "payfromcard") {//ajax
    payfromcard();
} elseif ($do == "chargeCard2") {
    //include_once("../public/authentication.php");

    $smarty->display("playStationCardView/chargeCard2.html");
}
##
elseif ($do == "sucess") {
//here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
//here the smarty templates
    $smarty->display("error.html");
}

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

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

function add() {
    global $playstationCard;
    global $playstationCardDAO;

    //
    $name = filter_input(INPUT_POST, 'name');
    $packageVal = (float) filter_input(INPUT_POST, 'packageVal');
    $packagePrice = (float) filter_input(INPUT_POST, 'packagePrice');
    $packageDays = (int) filter_input(INPUT_POST, 'packageDays');


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

    //
    $playstationCard->name = $name;
    $playstationCard->packageVal = $packageVal;
    $playstationCard->packagePrice = $packagePrice;
    $playstationCard->packageDays = $packageDays;
    $playstationCard->file = $file;
    $playstationCard->del = 0;
    $playstationCard->userid = $_SESSION['userid'];
    $playstationCard->sysdate = date('Y-m-d H:i:s');

    $playstationCardDAO->insert($playstationCard);
}

function update() {
    global $playstationCard;
    global $playstationCardDAO;

    //
    $id = (int) filter_input(INPUT_POST, 'id');
    $name = filter_input(INPUT_POST, 'name');
    $packageVal = (float) filter_input(INPUT_POST, 'packageVal');
    $packagePrice = (float) filter_input(INPUT_POST, 'packagePrice');
    $packageDays = (int) filter_input(INPUT_POST, 'packageDays');


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

    $playstationCard = $playstationCardDAO->load($id);
    //
    $playstationCard->name = $name;
    $playstationCard->packageVal = $packageVal;
    $playstationCard->packagePrice = $packagePrice;
    $playstationCard->packageDays = $packageDays;
    $playstationCard->file = $file;

    $playstationCardDAO->update($playstationCard);
}

function delete() {
    global $playstationCard;
    global $playstationCardDAO;

    //
    $id = (int) filter_input(INPUT_GET, 'id');
    $playstationCard = $playstationCardDAO->load($id);
    $playstationCard->del = 1;
    $playstationCardDAO->update($playstationCard);
}

////////////////////////////////////////////////////////////////////////////////
function chargeCard() {
    global $playstationCard;
    global $playstationCardDAO;

    global $playstationClientCard;
    global $playstationClientCardDAO;


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


        $cardid = (int) filter_input(INPUT_POST, 'cardid');
        $client = (int) filter_input(INPUT_POST, 'client');

        $playstationCard = $playstationCardDAO->load($cardid);

        //save card data
        $playstationClientCard->cardid = $playstationCard->id;
        $playstationClientCard->clientid = $client;
        $playstationClientCard->buyDate = date('Y-m-d H:i:s');
        $playstationClientCard->packVal = $playstationCard->packageVal;
        $playstationClientCard->packPrice = $playstationCard->packagePrice;
        $playstationClientCard->packDays = $playstationCard->packageDays;
        $playstationClientCard->packValConsumed = 0;

        $startDate = strtotime($playstationClientCard->buyDate);
        $playstationClientCard->cardEndDate = date('Y-m-d H:i:s', strtotime('+' . $playstationClientCard->packDays . ' day', $startDate));

        $playstationClientCard->cardStatus = 0;
        $playstationClientCard->userid = $_SESSION['userid'];
        $playstationClientCard->del = 0;
        $playstationClientCard->sysDate = date('Y-m-d H:i:s');

        $id = $playstationClientCardDAO->insert($playstationClientCard);

        //
        addPlaystationClientCardPayHistory($playstationClientCard->clientid, $playstationClientCard->cardid, 0, $playstationCard->packageVal, 0, $playstationCard->packageVal, "شراء باقة بلاي ستيشن", $id, "playStationCardController.php?do=details&id=$playstationCard->id", "");


        //update client debt
        $clientdata = getClientDataFromClientInUseSP($client);
        $debtAfter = $clientdata->clientdebt - $playstationCard->packageVal;
        updateClientDebt($playstationClientCard->clientid, $debtAfter);
        insertClientdebtchange($playstationClientCard->clientid, $clientdata->clientdebt, $playstationCard->packageVal, 1, "شراء باقة بلاي ستيشن", $id, $debtAfter, "playStationCardController.php?do=details&id=$playstationCard->id", '', $playstationCard->packageVal);
        markClientAsNOTInUse($playstationClientCard->clientid);

        //update save
        //get saveValue before and saveValue after Plus lPayed
        $saveData = getSaveValueAndPlus($_SESSION['saveid'], $playstationCard->packagePrice);
        $saveId = $saveData[0];
        $saveValuebefore = $saveData[1];
        $saveValueafter = $saveData[2];

        //update save value after add sellbill
        updateSave($saveId, $saveValueafter);

        //insert into savedaily tbl from save
        $_SESSION['client_id'] = $client;
        insertSavedaily($saveValuebefore, $playstationCard->packagePrice, 0, $saveId, "شراء باقة بلاي ستيشن", $id, $saveValueafter, "playStationCardController.php?do=details&id=$playstationCard->id");
        unset($_SESSION['client_id']);


        $mytransactions->commit();
    } catch (Exception $e) {
        //echo $e;
        $mytransactions->rollback();
        $client = (int) filter_input(INPUT_POST, 'client');
        markClientAsNOTInUse($client);
    }
}

function deleteClientCard() {
    global $playstationClientCard;
    global $playstationClientCardDAO;

    $id = filter_input(INPUT_GET, 'id');
    $playstationClientCard = $playstationClientCardDAO->load($id);
    if ($playstationClientCard->del == 0 && $playstationClientCard->packValConsumed == 0) {

        //Transaction
        $mytransactions = new Transaction();
        try {
            //del card data
            $playstationClientCard->del = 1;
            $playstationClientCardDAO->update($playstationClientCard);

            //
            addPlaystationClientCardPayHistory($playstationClientCard->clientid, $playstationClientCard->cardid, $playstationClientCard->packVal, $playstationClientCard->packVal, 1, 0, "الغاء شراء باقة بلاي ستيشن", $playstationClientCard->id, "playStationCardController.php?do=details&id=$playstationClientCard->cardid", "");


            //update client debt
            $clientdata = getClientDataFromClientInUseSP($playstationClientCard->clientid);
            $debtAfter = $clientdata->clientdebt + $playstationClientCard->packVal;
            updateClientDebt($playstationClientCard->clientid, $debtAfter);
            insertClientdebtchange($playstationClientCard->clientid, $clientdata->clientdebt, $playstationClientCard->packVal, 0, "الغاء شراء باقة بلاي ستيشن", $playstationClientCard->id, $debtAfter, "playStationCardController.php?do=details&id=$playstationClientCard->cardid", '', $playstationClientCard->packVal);
            markClientAsNOTInUse($playstationClientCard->clientid);

            //update save
            //get saveValue before and saveValue after Plus lPayed
            $saveData = getSaveValueAndMins($_SESSION['saveid'], $playstationClientCard->packPrice);
            $saveId = $saveData[0];
            $saveValuebefore = $saveData[1];
            $saveValueafter = $saveData[2];

            //update save value after add sellbill
            updateSave($saveId, $saveValueafter);

            //insert into savedaily tbl from save
            $_SESSION['client_id'] = $client;
            insertSavedaily($saveValuebefore, $playstationClientCard->packPrice, 1, $saveId, "الغاء شراء باقة بلاي ستيشن", $playstationClientCard->id, $saveValueafter, "playStationCardController.php?do=details&id=$playstationClientCard->cardid");
            unset($_SESSION['client_id']);


            $mytransactions->commit();
        } catch (Exception $e) {
            //echo $e;
            $mytransactions->rollback();
            $client = (int) filter_input(INPUT_POST, 'client');
            markClientAsNOTInUse($client);
        }
    }
}

function handleExpiredCards($clientId = 0) {//0 means all clients ,> 0 means one client
    global $playstationClientCard;
    global $playstationClientCardDAO;
    global $playstationClientCardEX;


    $queryString = '';
    if ($clientId > 0) {
        $queryString = " and clientid = $clientId ";
    }
    $expiredPlaystationCards = $playstationClientCardEX->getExpiredPSCards($queryString);
    foreach ($expiredPlaystationCards as $playstationClientCard) {

        //Transaction
        $mytransactions = new Transaction();
        try {
            //del card data
            $playstationClientCard->cardStatus = 2;
            $playstationClientCardDAO->update($playstationClientCard);

            //
            $cardValBefore = $playstationClientCard->packVal - $playstationClientCard->packValConsumed;
            addPlaystationClientCardPayHistory($playstationClientCard->clientid, $playstationClientCard->cardid, $cardValBefore, $cardValBefore, 1, 0, "انتهاء صلاحية باقة بلاي ستيشن", $playstationClientCard->id, "playStationCardController.php?do=details&id=$playstationClientCard->cardid", "");


            //update client debt
            $clientdata = getClientDataFromClientInUseSP($playstationClientCard->clientid);
            $debtAfter = $clientdata->clientdebt + $cardValBefore;
            updateClientDebt($playstationClientCard->clientid, $debtAfter);
            insertClientdebtchange($playstationClientCard->clientid, $clientdata->clientdebt, $cardValBefore, 0, "انتهاء صلاحية باقة بلاي ستيشن", $playstationClientCard->id, $debtAfter, "playStationCardController.php?do=details&id=$playstationClientCard->cardid", '', $cardValBefore);
            markClientAsNOTInUse($playstationClientCard->clientid);

            $mytransactions->commit();
        } catch (Exception $e) {
            //echo $e;
            $mytransactions->rollback();
            markClientAsNOTInUse($playstationClientCard->clientid);
        }
    }
}

function addPlaystationClientCardPayHistory($clientid, $cardid, $cardValBefore, $payAmount, $changeType, $cardValAfter, $processname, $modelid, $tablename, $comment) {
    global $playstationClientCardPayHistory;
    global $playstationClientCardPayHistoryDAO;

    $playstationClientCardPayHistory->clientid = $clientid;
    $playstationClientCardPayHistory->cardid = $cardid;
    $playstationClientCardPayHistory->cardValBefore = $cardValBefore;
    $playstationClientCardPayHistory->payAmount = $payAmount;
    $playstationClientCardPayHistory->changeType = $changeType;
    $playstationClientCardPayHistory->cardValAfter = $cardValAfter;
    $playstationClientCardPayHistory->processname = $processname;
    $playstationClientCardPayHistory->modelid = $modelid;
    $playstationClientCardPayHistory->tablename = $tablename;
    $playstationClientCardPayHistory->comment = $comment;
    $playstationClientCardPayHistory->conditions = 0;
    $playstationClientCardPayHistory->userid = $_SESSION['userid'];
    $playstationClientCardPayHistory->sysDate = date('Y-m-d H:i:s');

    $playstationClientCardPayHistoryDAO->insert($playstationClientCardPayHistory);
}

function payfromcard() {
    global $playstationCard;
    global $playstationCardDAO;

    global $playstationClientCard;
    global $playstationClientCardDAO;


    $client = 0;
    try {

        $cardPayed = filter_input(INPUT_POST, 'cardPayed');
//        $psClientCardId = filter_input(INPUT_POST, 'psClientCardId');
        $restaurantPlaystationPlayId = filter_input(INPUT_POST, 'restaurantPlaystationPlayId');
        $client = (int) filter_input(INPUT_POST, 'client');

        #reduce card val and increase consume
        /*        $playstationClientCard = $playstationClientCardDAO->load($psClientCardId);

          $client = $playstationClientCard->clientid;
          $cardValBefore = $playstationClientCard->packVal - $playstationClientCard->packValConsumed;
          $playstationClientCard->packValConsumed += $cardPayed;
          if ($playstationClientCard->packValConsumed >= $playstationClientCard->packVal) {
          $playstationClientCard->cardStatus = 1;
          }
          $playstationClientCardDAO->update($playstationClientCard);
          $cardValAfter = $playstationClientCard->packVal - $playstationClientCard->packValConsumed;
          #save in client card history
          addPlaystationClientCardPayHistory($playstationClientCard->clientid, $playstationClientCard->cardid, $cardValBefore, $cardPayed, 1, $cardValAfter, "دفع البلاى ستيشن بكارت", $restaurantPlaystationPlayId, "restaurantplaystationpaly.php", ""); */
        selectCardsAndPay($cardPayed, $client, $restaurantPlaystationPlayId);

        #update client debt, save in client debt change
        //update client debt
        $clientdata = getClientDataFromClientInUseSP($client);
        $debtAfter = $clientdata->clientdebt + $cardPayed;
        updateClientDebt($client, $debtAfter);
        insertClientdebtchange($client, $clientdata->clientdebt, $cardPayed, 0, "دفع البلاى ستيشن بكارت", $restaurantPlaystationPlayId, $debtAfter, "restaurantplaystationpaly.php", '', $cardPayed);
        markClientAsNOTInUse($client);



        echo 1;
    } catch (Exception $e) {
        markClientAsNOTInUse($client);
        echo $e;
        echo -1;
    }
}

function selectCardsAndPay($cardPayed, $client, $restaurantPlaystationPlayId) {
    global $playstationClientCardDAO;
    global $playstationClientCardEX;


    $allPlaystationClientCard = $playstationClientCardEX->getClientPSCards($client, " order by cardEndDate asc");
    $payedWtihinForeach = 0;
    foreach ($allPlaystationClientCard as $playstationClientCard) {
        if ($payedWtihinForeach == $cardPayed) {
            //do nothing
            break;
        } else {
            $cardValBefore = $playstationClientCard->packVal - $playstationClientCard->packValConsumed;
            $cardValRequired = $cardPayed - $payedWtihinForeach;

            $onePay = 0;
            if ($cardValRequired <= $cardValBefore) {
                $onePay = $cardValRequired;
            } else {
                $onePay = $cardValBefore;
            }
            $payedWtihinForeach += $onePay;

            $playstationClientCard->packValConsumed += $onePay;
            if ($playstationClientCard->packValConsumed >= $playstationClientCard->packVal) {
                $playstationClientCard->cardStatus = 1;
            }
            $playstationClientCardDAO->update($playstationClientCard);
            $cardValAfter = $playstationClientCard->packVal - $playstationClientCard->packValConsumed;
            #save in client card history
            addPlaystationClientCardPayHistory($client, $playstationClientCard->cardid, $cardValBefore, $onePay, 1, $cardValAfter, "دفع البلاى ستيشن بكارت", $restaurantPlaystationPlayId, "restaurantplaystationpaly.php", "");
        }
    }
}

###

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

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


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

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

////////////////////////////client///////////////////////////
// update in rawmaterialssuppliers tbl
function updateClientDebt($clientid, $clientdebtAfter) {

    //to use the variable out side the funcion
    global $myClient;
    global $myClientEx;

    //update clientdebt in client tbl
    $myClient->userid = $_SESSION['userid'];
    $myClient->clientdebt = $clientdebtAfter;
    $myClient->clientid = $clientid;

    $myClientEx->updateClientdebt($myClient);
}

// insert data into Clientdebtchange tbl
function insertClientdebtchange($clientid, $clientdebtchangebefore, $clientdebtchangeamount, $clientdebtchangetype, $processname, $clientdebtchangemodelid, $clientdebtchangeafter, $tablename, $comment, $totalOperationCost) {

    //to use the variable out side the funcion
    global $myClientdebtchange;
    global $myClientdebtchangeRecord;

    $myClientdebtchange->clientdebtchangeafter = $clientdebtchangeafter;
    $myClientdebtchange->clientdebtchangeamount = $clientdebtchangeamount;
    $myClientdebtchange->clientdebtchangebefore = $clientdebtchangebefore;
    $myClientdebtchange->clientdebtchangedate = date("Y-m-d H:i:s");
    $myClientdebtchange->clientdebtchangemodelid = $clientdebtchangemodelid;
    $myClientdebtchange->clientdebtchangetype = $clientdebtchangetype;
    $myClientdebtchange->clientid = $clientid;
    $myClientdebtchange->comment = $comment;
    $myClientdebtchange->processname = $processname;
    $myClientdebtchange->tablename = $tablename;
    $myClientdebtchange->userid = $_SESSION['userid'];
    $myClientdebtchange->totalOperationCost = abs($totalOperationCost);
    $myClientdebtchange->dailyentryid = 0;

    $myClientdebtchangeRecord->insert($myClientdebtchange);
}

function getClientDataFromClientInUseSP($clientid) {
    global $clientEX;
    global $myClientRecord;
    if ($clientid == 1) {
        $client_data = $myClientRecord->load($clientid);
    } elseif ($clientid > 1) {
        $noOfTries = 0;
        $client_data = $clientEX->callClientInUseSP($clientid);
        while ($client_data->clientdebt == 'in_use') {
            sleep(1);
            $noOfTries++;
            if ($noOfTries > 15) {// mean 15 sec as sleep is 1 sec her
                //markClientAsNOTInUse -- using redbeans to instantly execute in database as we are in transaction now "means affecting row is done @end of execution or comit"
                liveBackupComment("-- force free client=$clientid with redbean");
                R::exec('UPDATE client SET  inUse = 0 where clientid = ' . $clientid);
            }
            $client_data = $clientEX->callClientInUseSP($clientid);
        }
    }
    return $client_data;
}

function markClientAsNOTInUse($clientid) {//mark as not in use "free him to be able to change debt again"
    global $clientEX;
    if ($clientid == 1) {
        //do no thing. we didnot mark it as in use at begining
    } else {
        $clientEX->markClientAsNOTInUse($clientid);
    }
}

////////////////////////////save///////////////////////////
// get savecurrentvalue from save tbl
function getSaveValueBefore($saveid) {

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveRecord;

    $saveData = $mySaveRecord->load($saveid);
    $saveValuebefore = $saveData->savecurrentvalue;

    return $saveValuebefore;
}

// get initialvalue and plus from save tbl
function getSaveValueAndPlus($saveid, $savevaluechanged) {

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveEx;

    $saveData = $mySaveEx->loadForUpdateEx($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore + $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter);
}

// get initialvalue and mins from save tbl
function getSaveValueAndMins($saveid, $savevaluechanged) {

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveEx;

    $saveData = $mySaveEx->loadForUpdateEx($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore - $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter);
}

// update in Save tbl
function updateSave($saveid, $savevalueafter) {

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveEx;

    //update initialvalue in Save tbl
    $mySave->savecurrentvalue = $savevalueafter;
    $mySave->userid = $_SESSION['userid'];
    $mySave->saveid = $saveid;

    $mySaveEx->updateSaveValue($mySave);
}

// insert in Savedaily tbl
function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename) {

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

    //insert in Savedaily tbl
    $mySavedaily->savedailydate = date("Y-m-d H:i:s");
    $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);
}

?>