<?php

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

// get the config file
include_once("../public/config.php");

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

//here the global templates
$smarty->display("header.html");
//$smarty->display("maintennanceHeader.html");
//here goes the instances and general variables
//Restauranttable
require_once('../models/dao/RestauranttableDAO.class.php');
require_once('../models/dto/Restauranttable.class.php');
require_once('../models/mysql/RestauranttableMySqlDAO.class.php');
require_once('../models/mysql/ext/RestauranttableMySqlExtDAO.class.php');
//Restauranthall
require_once('../models/dao/RestauranthallDAO.class.php');
require_once('../models/dto/Restauranthall.class.php');
require_once('../models/mysql/RestauranthallMySqlDAO.class.php');
require_once('../models/mysql/ext/RestauranthallMySqlExtDAO.class.php');
//Restaurantplaystation
require_once('../models/dao/RestaurantplaystationDAO.class.php');
require_once('../models/dto/Restaurantplaystation.class.php');
require_once('../models/mysql/RestaurantplaystationMySqlDAO.class.php');
require_once('../models/mysql/ext/RestaurantplaystationMySqlExtDAO.class.php');
//Restaurantplaystationplay
require_once('../models/dao/RestaurantplaystationplayDAO.class.php');
require_once('../models/dto/Restaurantplaystationplay.class.php');
require_once('../models/mysql/RestaurantplaystationplayMySqlDAO.class.php');
require_once('../models/mysql/ext/RestaurantplaystationplayMySqlExtDAO.class.php');
//Productcat
require_once('../models/dao/ProductcatDAO.class.php');
require_once('../models/dto/Productcat.class.php');
require_once('../models/mysql/ProductcatMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatMySqlExtDAO.class.php');
//Productunit
require_once('../models/dao/ProductunitDAO.class.php');
require_once('../models/dto/Productunit.class.php');
require_once('../models/mysql/ProductunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductunitMySqlExtDAO.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');
//check and use the condetion that suite this action
//Restauranttable
$restaurantTable = new Restauranttable();
$restaurantTableDAO = new RestauranttableMySqlDAO();
$restaurantTableEX = new RestauranttableMySqlExtDAO();
//Restauranthall
$restaurantHall = new Restauranthall();
$restaurantHallDAO = new RestauranthallMySqlDAO();
$restaurantHallEX = new RestauranthallMySqlExtDAO();
//Restaurantplaystation
$restaurantPlaystation = new Restaurantplaystation();
$restaurantPlaystationDAO = new RestaurantplaystationMySqlDAO();
$restaurantPlaystationEX = new RestaurantplaystationMySqlExtDAO();
//Restaurantplaystationplay
$restaurantPlaystationPlay = new Restaurantplaystationplay();
$restaurantPlaystationPlayDAO = new RestaurantplaystationplayMySqlDAO();
$restaurantPlaystationPlayEX = new RestaurantplaystationplayMySqlExtDAO();
//Productcat
$productCat = new Productcat();
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();
//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();

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

if (empty($do)) {
    include_once("../public/authentication.php");

    $restaurantHalls = $restaurantHallDAO->queryAll();
    $smarty->assign("restaurantHalls", $restaurantHalls);

    $smarty->display("restaurantplaystationview/add.html");
    //date
} elseif ($do == "add") {
    // include_once("../public/authentication.php");
    include_once("../public/authentication.php");
    try {
        // here the function that do the action
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //print_r($e);
        header("location:?do=error");
    }
} elseif ($do == "show") {
    include_once("../public/authentication.php");
    $allPlaystations = $restaurantPlaystationDAO->queryAll();
    $smarty->assign("allPlaystations", $allPlaystations);

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

    $smarty->display("restaurantplaystationview/show.html");
}

//edit
elseif ($do == "edit") {
    include_once("../public/authentication.php");
    $id = (int) $_GET['id'];

    $alldata = $restaurantPlaystationEX->loadEX($id);
    $smarty->assign("alldata", $alldata);

    $restaurantHalls = $restaurantHallDAO->queryAll();
    $smarty->assign("restaurantHalls", $restaurantHalls);

    //print_r($alldata);
    $smarty->display("restaurantplaystationview/edit.html");
} elseif ($do == "update") {
    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 == "delete") {


    include_once("../public/authentication.php");
    //add();
    try {
        // here the function that do the action
        delete();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
}
##
elseif ($do == "dayReport") {
    $restaurantPlaystation = $restaurantPlaystationEX->queryAllWithQueryString(" and del = 0 ");
    $smarty->assign("restaurantPlaystation", $restaurantPlaystation);

    $datefrom = filter_input(INPUT_POST, 'datefrom');
    $dateto = filter_input(INPUT_POST, 'dateto');
    $restaurantplaystationId = (int) filter_input(INPUT_POST, 'restaurantplaystationId');

    $queryString = "";
    ##date
    if (isset($restaurantplaystationId) && !empty($restaurantplaystationId)) {
        $queryString .= ' and  restaurantplaystationplay.playstationid  = ' . $restaurantplaystationId . ' ';
    }
    if (isset($datefrom) && !empty($datefrom)) {
        $queryString .= ' and  restaurantplaystationplay.startsysDate  >= "' . $datefrom . '" ';
    }
    if (isset($dateto) && !empty($dateto)) {
        $queryString .= ' and  restaurantplaystationplay.startsysDate  <= "' . $dateto . '" ';
    }
    if ($queryString == '') {
        $queryString .= ' and  restaurantplaystationplay.startsysDate  >= "' . date('Y-m-d') . ' 00:00:00" ';
        $queryString .= ' and  restaurantplaystationplay.startsysDate  <= "' . date('Y-m-d') . ' 23:59:59" ';
    }
    //and restaurantplaystationplay.finished=1
    $queryString .= ' and restaurantplaystationplay.allMovesUnitedSellBillId > 0 order by restaurantplaystationplay.allMovesUnitedSellBillId desc,restaurantplaystationplay.oldPsPlayid asc';
    $result = $restaurantPlaystationPlayEX->queryAllQueryString($queryString);
    foreach ($result as $sellbilldetail) {
        //getstart , end time in form H:i
        $sellbilldetail->startTime = date('H:i', strtotime($sellbilldetail->moveStartSysDate)); //date('H:i', strtotime($sellbilldetail->startsysDate));//
        $sellbilldetail->endTime = date('H:i', strtotime($sellbilldetail->endsysDate));

        //calc duration for all time
        $datetime1 = new DateTime($sellbilldetail->moveStartSysDate); //new DateTime($sellbilldetail->startsysDate);
        $datetime2 = new DateTime($sellbilldetail->endsysDate);
        $interval = $datetime1->diff($datetime2);
        $sellbilldetail->duration = $interval->format('%h') . ":" . $interval->format('%i'); //. ":" . $interval->format('%s');
    }

    $smarty->assign("playstationPlay", $result);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->display("restaurantplaystationview/dayReport.html");
}
##
elseif ($do == "sucess") {

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

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

////****************************  Functions  ********************///

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


function add() {
    global $restaurantTable;
    global $restaurantTableDAO;
    global $restaurantTableEX;
    //
    global $restaurantPlaystation;
    global $restaurantPlaystationDAO;
    global $restaurantPlaystationEX;


    $name = $_POST['name'];
    $hallid = (int) $_POST['hallid'];
    $hasTable = (int) $_POST['hasTable'];
    $hourPrice = (float) $_POST['hourPrice'];
    $hourPriceMulti = (float) $_POST['hourPriceMulti'];
    $deviceIdentification = $_POST['deviceIdentification'];
    $subDeviceIdentification = $_POST['subDeviceIdentification'];
    $useSubIdentification = (int) $_POST['useSubIdentification'];

    //add service
    $catId = addTheCategory();
    $serviceId = addService($catId, $name);
    //add table
    $tableId = 0;
    if ($hasTable == 1) {
        $check = $restaurantTableDAO->queryByName($name);
        $restaurantTable->name = (count($check) > 0) ? $name . "_ps" : $name;
        $restaurantTable->hallid = $hallid;
        $restaurantTable->beingUsed = 0;
        $restaurantTable->userId = $_SESSION['userid'];
        $restaurantTable->sysdate = date('Y-m-d');
        $restaurantTable->del = 0;
        $tableId = $restaurantTableDAO->insert($restaurantTable);
    }
    //add ps
    $restaurantPlaystation->name = $name;
    $restaurantPlaystation->hourPrice = $hourPrice;
    $restaurantPlaystation->hourPriceMulti = $hourPriceMulti;
    $restaurantPlaystation->beingUsed = 0;
    $restaurantPlaystation->tableId = $tableId;
    $restaurantPlaystation->serviceId = $serviceId;
    $restaurantPlaystation->userId = $_SESSION['userid'];
    $restaurantPlaystation->sysdate = date('Y-m-d H:i:s');
    $restaurantPlaystation->del = 0;
    $restaurantPlaystation->deviceIdentification = $deviceIdentification;
    $restaurantPlaystation->subDeviceIdentification = $subDeviceIdentification;
    $restaurantPlaystation->useSubIdentification = $useSubIdentification;
    $restaurantPlaystationDAO->insert($restaurantPlaystation);
}

function update() {
    global $restaurantTable;
    global $restaurantTableDAO;
    global $restaurantTableEX;
    //
    global $restaurantPlaystation;
    global $restaurantPlaystationDAO;
    global $restaurantPlaystationEX;

    $id = (int) $_POST['id'];
    $oldhallid = (int) $_POST['oldhallid'];
    $name = $_POST['name'];

    $hallid = (int) $_POST['hallid'];
    $hasTable = (int) $_POST['hasTable'];
    $hourPrice = (float) $_POST['hourPrice'];
    $hourPriceMulti = (float) $_POST['hourPriceMulti'];
    $deviceIdentification = $_POST['deviceIdentification'];
    $subDeviceIdentification = $_POST['subDeviceIdentification'];
    $useSubIdentification = (int) $_POST['useSubIdentification'];


    $oldPS = $restaurantPlaystationDAO->load($id);
    //add service
    $catId = addTheCategory(); //cat already exist it will only return its id
    updateService($catId, $name, $oldPS->serviceId);
    //update table (using the four posibilities of two variables "$hasTable , $oldPS->tableId")
    $tableId = 0;
    if ($hasTable == 1 && $oldPS->tableId == 0) {
        //there was no table , but in new update there is //so add table
        $check = $restaurantTableDAO->queryByName($name);
        $restaurantTable->name = (count($check) > 0) ? $name . "_ps" : $name;
        $restaurantTable->hallid = $hallid;
        $restaurantTable->beingUsed = 0;
        $restaurantTable->userId = $_SESSION['userid'];
        $restaurantTable->sysdate = date('Y-m-d');
        $restaurantTable->del = 0;
        $tableId = $restaurantTableDAO->insert($restaurantTable);
    } elseif ($hasTable == 1 && $oldPS->tableId > 0) {//there is table before and after update but we may need to update the hall
        if ($hallid == $oldhallid) {
            //donothing
        } else {
            //update hall
            //
            //there was no table , but in new update there is //so add table
            $check = $restaurantTableDAO->queryByName($name);


            $restaurantTable = $restaurantTableDAO->load($oldPS->tableId);
            $restaurantTable->name = (count($check) > 0) ? $name . "_ps" : $name;
            $restaurantTable->hallid = $hallid;
            $restaurantTableDAO->update($restaurantTable);
        }
        $tableId = $oldPS->tableId;
    } elseif ($hasTable == 0 && $oldPS->tableId == 0) {//no thing changed //there is no table before or after update
        $tableId = $oldPS->tableId;
    } elseif ($hasTable == 0 && $oldPS->tableId > 1) {//there is a table we want to delete
        $restaurantTable = $restaurantTableDAO->load($oldPS->tableId);
        $restaurantTable->del = 1;
        $restaurantTableDAO->update($restaurantTable);
        $tableId = 0;
    }

    if ($name != $oldPS->name && $tableId > 0) {
        $check = $restaurantTableDAO->queryByName($name);
        $restaurantTable = $restaurantTableDAO->load($tableId);
        $restaurantTable->name = (count($check) > 0) ? $name . "_ps" : $name;
        $restaurantTableDAO->update($restaurantTable);
    }

    //update ps
    $restaurantPlaystation->id = $id;
    $restaurantPlaystation->name = $name;
    $restaurantPlaystation->hourPrice = $hourPrice;
    $restaurantPlaystation->hourPriceMulti = $hourPriceMulti;
    $restaurantPlaystation->beingUsed = $oldPS->beingUsed;
    $restaurantPlaystation->tableId = $tableId;
    $restaurantPlaystation->serviceId = $oldPS->serviceId; //remains the same
    $restaurantPlaystation->userId = $_SESSION['userid'];
    $restaurantPlaystation->sysdate = $oldPS->sysdate;
    $restaurantPlaystation->del = $oldPS->del;
    $restaurantPlaystation->deviceIdentification = $deviceIdentification; //$oldPS->deviceIdentification;
    $restaurantPlaystation->subDeviceIdentification = $subDeviceIdentification; //$oldPS->subDeviceIdentification;
    $restaurantPlaystation->useSubIdentification = $useSubIdentification; //$oldPS->useSubIdentification;
    $restaurantPlaystationDAO->update($restaurantPlaystation);
}

function delete() {
    global $restaurantTable;
    global $restaurantTableDAO;
    global $restaurantTableEX;
    //
    global $restaurantPlaystation;
    global $restaurantPlaystationDAO;
    global $restaurantPlaystationEX;

    $id = (int) $_GET['id'];
    //
    $oldPS = $restaurantPlaystationDAO->load($id);
    $oldPS->del = 1;
    $restaurantPlaystationDAO->update($oldPS);
    //
    if ($oldPS->tableId > 0) {
        $oldTable = $restaurantTableDAO->load($oldPS->tableId);
        $oldTable->del = 1;
        $restaurantTableDAO->update($oldTable);
    }
    //dont del service//
}

function addTheCategory() {
    global $productCatDAO;

    $catName = 'بلاي ستيشن';
    $catid_program = 0;
    $check = $productCatDAO->queryByProductCatName($catName);
    if (count($check) > 0) {
        $catid_program = $check[0]->productCatId;
    } else {
        $catDataArr = array('parent' => '-1'
            , 'level' => 0
            , 'productCatName' => $catName
            , 'inMenu' => 0
            , 'discounttype' => -1
            , 'selldiscount' => '0'
            , 'buydiscount' => '0'
            , 'buypricereal' => '0'
            , 'buytotal' => '0'
            , 'buyhalf' => '0'
            , 'buypart' => '0'
            , 'stopNegativeSale' => '0'
            , 'productCatDescription' => ''
            , 'productcatunit1' => '-1'
            , 'cat_productnumber1' => ''
            , 'cat_unitsItr' => '1'
        );
        $catid_program = CURL_IT2($catDataArr, 'productCatController.php?do=add2SimpleReturn');
    }
    return $catid_program;
}

function addService($catId, $name) {
    //add new
    $productDataArr = array('productCatId' => $catId,
        'productItr' => '2',
        'productindextype' => '0',
        'unitsItr1' => '0',
        'hide_precentage' => '1',
        'hide_realprice' => '1',
        'hide_isCaf' => '',
        'hide_isRestaurent' => '0',
        'productName1' => $name,
        'productBuyPrice1' => 0,
        'productbuypricereal1' => 0,
        'buypricereal_precentage1' => '0',
        'productSellAllPrice1' => 0,
        'buytotal_precentage1' => 0,
        'productSellHalfPrice1' => 0,
        'buyhalf_precentage1' => 0,
        'productSellUnitPrice1' => 0,
        'buypart_precentage1' => 0,
        'productquantity1' => '0',
        'parcode1' => '',
        'expireDate1' => '0',
        'productDate1' => date('Y-m-d'),
        'limitamount1' => '0',
        'inMenu1' => '0',
        'type1' => '0',
        'isservice1' => '1',
        'productDescription1' => '',
        'hidden_unitItr1' => '0',
        'hasSizeAndColor1' => 0,
    );

    $productid_program = CURL_IT2($productDataArr, 'productController.php?do=addOneSimpleReturn');
    return $productid_program;
}

function updateService($catId, $name, $serviceId) {
    global $myProductunitEx;
    $myunitdata = $myProductunitEx->queryWithProductIdAndCondition($serviceId);
    $productDataArr = array('productId' => $serviceId,
        'productCatId' => $catId,
        'productItr' => '2',
        'productindextype' => '0',
        'unitsItr1' => '1',
        'productunit11' => $myunitdata[0]->unitid,
        'productnumber11' => $myunitdata[0]->productnumber,
        'productunitid1' => $myunitdata[0]->productunitid,
        'hide_precentage' => '1',
        'hide_realprice' => '1',
        'hide_isCaf' => '',
        'hide_isRestaurent' => '0',
        'productName1' => $name,
        'productBuyPrice1' => 0,
        'productbuypricereal1' => 0,
        'buypricereal_precentage1' => '0',
        'productSellAllPrice1' => 0,
        'buytotal_precentage1' => 0,
        'productSellHalfPrice1' => 0,
        'buyhalf_precentage1' => 0,
        'productSellUnitPrice1' => 0,
        'buypart_precentage1' => 0,
        'productquantity1' => '0',
        'parcode1' => '',
        'expireDate1' => '0',
        'productDate1' => date('Y-m-d'),
        'limitamount1' => '0',
        'inMenu1' => '0',
        'type1' => '0',
        'isservice1' => '1',
        'productDescription1' => '',
        'hidden_unitItr1' => '0',
        'hasSizeAndColor1' => 0,
    );

    $productid_program = CURL_IT2($productDataArr, 'productController.php?do=update');
    //it wont return id besides serviceid wont change
    //return $productid_program;
}

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

?>