<?php

session_start();
ob_start();
$do        = isset($_GET['do']) ? $_GET['do'] : "";
$ajaxDoArr = ["add2SimpleReturn","new"];
include "initiateStaticSessionCommingWithCurl.php";
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
    array_push($ajaxDoArr, $do);
}

if (! in_array($do, $ajaxDoArr)) {
    include "../public/impOpreation.php";
}

if($do == "new"){
    include "../public/impOpreation.php";
}

include_once "../public/config.php";
include "../library/newUplode/uploadfunctions.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";

if (! in_array($do, $ajaxDoArr)) {
    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

    } else {
        $smarty->display("header.html");
    }
}

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

$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);

$myStoreEx = new StoreMySqlExtDAO();

$today = date("Y-m-d");
//check and use the condition that suite this action
if (empty($do) || $do == "new") {
    //here the permission check
    $userData = R::getRow('SELECT * from user where userid = ' . $_SESSION['userid']);
    if ($userData['branchId'] == 0) {
        $allBranch = R::getAll('SELECT * from branch where branchId != 0');
        $smarty->assign('allBranch', $allBranch);
    } else {
        $branchData = R::getRow('SELECT * from branch where branchId = ' . $userData['branchId']);
        $smarty->assign('branchData', $branchData);
    }

    $smarty->assign("searchinonestore", $_SESSION['searchinonestore']);
    if ($_SESSION['searchinonestore'] == 0) {
        if ($_SESSION['storeids'] == 0) {
            $stores = $myStoreEx->queryByConditions();
        } else {
            $stores = $myStoreEx->queryByConditions(' and store.storeId in (' . $_SESSION['storeids'] . ')');
        }
        $smarty->assign("storeData", $stores);
        $storedef = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("storedef", $storedef);
        $smarty->assign("storeid", $_SESSION['storeid']);
    } else {
        $storedef = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("storedef", $storedef);
        $smarty->assign("storeid", $_SESSION['storeid']);
    }

    
    if($do == "new"){
        $smarty->assign("customBranchRequestNew", 1);
        $smarty->assign('billjs',0);
        $smarty->display("header-bill.html");
        $smarty->display("branchRequestView/addnew.html");
        $smarty->display("footer.html");
    }
    else{
        $smarty->display("branchRequestView/add.html");
        $smarty->assign("customBranchRequest", 1);
    }
} elseif ($do == "add") {
    try {
        add();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = ['status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success'];
            echo json_encode($data);
        } else {
            header("location:?do=success");
        }
    } catch (Exception $e) {
        //echo $e;
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = ['status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error'];
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "show") {
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $userstoreid = R::getCell('SELECT userstoreid from user where userId = ' . $_SESSION['userid']);
    $queryStore  = '';
    if ($userstoreid == 0) {
        if ($_SESSION['storeids'] != 0) {
            $queryStore = ' and storeid in (' . $_SESSION['storeids'] . ')';
        }
    } else {
        $queryStore = ' and storeid =' . $userstoreid;
    }

    $showData = R::getAll('SELECT branchrequest.*, branch.branchName, user.employeeName username
            from branchrequest
            LEFT join branch ON branch.branchId = branchrequest.branchid
            LEFT JOIN user ON user.userid = branchrequest.userid
            where isdel = 0 ' . $queryStore.' order by branchrequest.id desc');
    $smarty->assign('showData', $showData);


    $showTransferBtn = R::getCell('SELECT transferBranchRequestBtnShow from usergroup where usergroupid = ' . $_SESSION['usergroupid']);
    $smarty->assign('showTransferBtn', $showTransferBtn);

    $smarty->display("branchRequestView/show.html");
    $smarty->assign("customCheck", 1);
} elseif ($do == "deleteFinaly") {
    try {
        $id = (int) $_GET['id'];
        deleteFinaly($id);

        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = ['status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success'];
            echo json_encode($data);
        } else {
            header("location:?do=success");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = ['status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error'];
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "details") { //view details
    $id       = $_GET['id'];
    $showData = R::getRow('SELECT branchrequest.*, branch.branchName, store.storeName, user.employeeName from branchrequest
            LEFT join branch ON branch.branchId = branchrequest.branchid
            LEFT JOIN store ON store.storeId = branchrequest.storeid
            LEFT JOIN user ON user.userid = branchrequest.userid
            where branchrequest.id = ' . $id);
    $smarty->assign('showData', $showData);

    $requestProducts = R::getAll('SELECT branchrequestproduct.*, product.productName from branchrequestproduct
            JOIN product ON product.productId = branchrequestproduct.productid
            where branchrequestproduct.requestid = ' . $id);
    $smarty->assign('allPro', $requestProducts);

    $showTransferBtn = R::getCell('SELECT transferBranchRequestBtnShow from usergroup where usergroupid = ' . $_SESSION['usergroupid']);
    $smarty->assign('showTransferBtn', $showTransferBtn);

    $smarty->display("branchRequestView/details.html");
} elseif ($do == "edit") { //edit
    $id       = $_GET['id'];
    $showData = R::load('branchrequest', $id);
    $smarty->assign('showData', $showData);

    $requestProducts = R::getAll('SELECT branchrequestproduct.*, product.productName, productcat.productCatName,storedetail.productquantity from branchrequestproduct
            JOIN product ON product.productId = branchrequestproduct.productid
            join productcat on productcat.productCatId = product.productCatId
            left join storedetail on storedetail.productid = product.productId and storedetail.storeId = ' . $showData['storeid'] . '
            where branchrequestproduct.requestid = ' . $id);
    $smarty->assign('allPro', $requestProducts);

    $userData = R::getRow('SELECT * from user where userid = ' . $_SESSION['userid']);
    if ($userData['branchId'] == 0) {
        $allBranch = R::getAll('SELECT * from branch where branchId != 0');
        $smarty->assign('allBranch', $allBranch);
    } else {
        $branchData = R::getRow('SELECT * from branch where branchId = ' . $userData['branchId']);
        $smarty->assign('branchData', $branchData);
    }

    $smarty->assign("searchinonestore", $_SESSION['searchinonestore']);
    if ($_SESSION['searchinonestore'] == 0) {
        if ($_SESSION['storeids'] == 0) {
            $stores = $myStoreEx->queryByConditions();
        } else {
            $stores = $myStoreEx->queryByConditions(' and store.storeId in (' . $_SESSION['storeids'] . ')');
        }
        $smarty->assign("storeData", $stores);
        $storedef = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("storedef", $storedef);
        $smarty->assign("storeid", $_SESSION['storeid']);
    } else {
        $storedef = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid'] . ' ');
        $smarty->assign("storedef", $storedef);
        $smarty->assign("storeid", $_SESSION['storeid']);
    }

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

    $smarty->display("branchRequestView/edit.html");
} elseif ($do == "update") { //edit update
    try {
        update();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = ['status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success'];
            echo json_encode($data);
        } else {
            header("location:?do=success");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = ['status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error'];
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "report") {
    $allData = getBranchRequestReport();
    $smarty->assign('allData', $allData);

    $showBranch = $_REQUEST['showBranch'];
    $smarty->assign('showBranch', $showBranch);

    $userData = R::getRow('SELECT * from user where userid = ' . $_SESSION['userid']);
    if ($userData['branchId'] == 0) {
        $allBranch = R::getAll('SELECT * from branch where branchId != 0');
        $smarty->assign('allBranch', $allBranch);
    } else {
        $branchData = R::getRow('SELECT * from branch where branchId = ' . $userData['branchId']);
        $smarty->assign('branchData', $branchData);
    }

    $allCat = R::getAll('SELECT * from productcat where conditions = 0');
    $smarty->assign('allCat', $allCat);
    $smarty->display("branchRequestView/report.html");
} elseif ($do == "success") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}

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

//here the global templates
if (! in_array($do, $ajaxDoArr)) {
    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

    } else {
        $smarty->display("footer.html");
    }
}

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

// add in productCat tbl
function add()
{


    $branchid = $_POST['branchid'];
    $storeId  = $_POST['storeId'];

    $request = R::dispense('branchrequest');
    $request->branchid   = $branchid;
    $request->storeid    = $storeId;
    $request->sysdate    = date("Y-m-d H:i:s");
    $request->updateDate = date("Y-m-d H:i:s");
    $request->userid     = $_SESSION['userid'];
    $request->isdel      = 0;
    $request->istransfer = 0;
    $id = R::store($request);
    $productItr = $_POST['productItr'];
    for ($i = 1; $i <= $productItr; $i++) {
        $productId = $_POST['product' . $i];
        $quantity  = $_POST['number' . $i];
        $comment   = $_POST['comment' . $i];
        if ($productId > 0 && $quantity > 0) {
            $requestItem = R::dispense('branchrequestproduct');
            $requestItem->requestid = $id;
            $requestItem->productid = $productId;
            $requestItem->quantity  = $quantity;
            $requestItem->comment   = $comment;
            R::store($requestItem);
        }
    }
    return $id;
}

function update()
{

    $branchid = $_POST['branchid'];
    $storeId  = $_POST['storeId'];
    $id       = $_POST['id'];

    $request             = R::load('branchrequest', $id);
    $request->branchid   = $branchid;
    $request->storeid    = $storeId;
    $request->updateDate = date("Y-m-d H:i:s");
    $request->userid     = $_SESSION['userid'];
    $id                  = R::store($request);

    R::exec('DELETE FROM branchrequestproduct WHERE requestid = ' . $id);

    $productItr = $_POST['productItr'];
    for ($i = 1; $i <= $productItr; $i++) {
        $productId = $_POST['product' . $i];
        $quantity  = $_POST['number' . $i];
        $comment   = $_POST['comment' . $i];

        if ($productId > 0 && $quantity > 0) {
            $requestItem            = R::dispense('branchrequestproduct');
            $requestItem->requestid = $id;
            $requestItem->productid = $productId;
            $requestItem->quantity  = $quantity;
            $requestItem->comment   = $comment;
            R::store($requestItem);
        }
    }
    return $id;
}

function deleteFinaly($id)
{
    $request        = R::load('branchrequest', $id);
    $request->isdel = 1;
    R::store($request);
}

function getBranchRequestReport()
{
    global $smarty;

    $fromdate = $_REQUEST['fromdate'];
    $todate   = $_REQUEST['todate'];
    $catid    = $_REQUEST['catid'];
    $branchid = $_REQUEST['branchid'];

    $where   = ' where branchrequest.isdel = 0';
    $message = 'تقرير طلبات الفروع ';
    if (! $fromdate && ! $todate) {
        $fromdate = date("Y-m-d");
        $todate   = date("Y-m-d");
    }
    if ($fromdate) {
        $where   .= ' and branchrequest.sysdate >= "' . $fromdate . ' 00:00:00" ';
        $message .= ' من تاريخ ' . $fromdate;
    }
    if ($todate) {
        $where   .= ' and branchrequest.sysdate <= "' . $todate . ' 23:59:59" ';
        $message .= ' إلى تاريخ ' . $todate;
    }
    if ($catid > 0) {
        $where   .= ' and product.productCatId = ' . $catid . ' ';
        $catName  = R::getCell('SELECT productCatName from productcat where productCatId = ' . $catid);
        $message .= '   التصنيف ' . $catName;
    }
    if ($branchid > 0) {
        $where      .= ' and branchrequest.branchid = ' . $branchid . ' ';
        $branchName  = R::getCell('SELECT branchName from branch where branchId = ' . $branchid);
        $message    .= '   الفرع ' . $branchName;
    }
    $smarty->assign('message', $message);
    $showBranch = $_REQUEST['showBranch'];

    if ($showBranch == 1) {
        $allData = R::getAll('SELECT  branchrequestproduct.comment, branchrequestproduct.productid, branch.branchId, branch.branchName, product.productName, sum(branchrequestproduct.quantity) proQuantity from branchrequest
                JOIN branchrequestproduct on branchrequestproduct.requestid = branchrequest.id
                left join branch ON branch.branchId = branchrequest.branchid
                left JOIN product on product.productId = branchrequestproduct.productid
                left JOIN productcat on productcat.productCatId = product.productCatId
                ' . $where . ' group by branch.branchId, product.productId order by product.productName ASC');
        $branchNames = [];
        $dataArr     = [];
        foreach ($allData as $data) {
            if (array_key_exists($data['productid'], $dataArr)) {
                $dataArr[$data['productid']]['proQuantity'] = $dataArr[$data['productid']]['proQuantity'] + $data['proQuantity'];
                $dataArr[$data['productid']]['comment'] = $dataArr[$data['productid']]['comment'].' - '. $data['comment'];
            } else {
                $dataArr[$data['productid']] = [
                    'proQuantity' => $data['proQuantity'],
                    'productName' => $data['productName'],
                    'comment' => $data['comment'],
                ];
            }
            if (array_key_exists($data['branchId'], $branchNames)) {
                if (array_key_exists($data['productid'], $branchNames[$data['branchId']])) {
                    $branchNames[$data['branchId']][$data['productid']] = $branchNames[$data['branchId']][$data['productid']] + $data['proQuantity'];
                } else {
                    $branchNames[$data['branchId']][$data['productid']] = $data['proQuantity'];
                }
                $branchNames[$data['branchId']]['branchTotalQuantity'] = $branchNames[$data['branchId']]['branchTotalQuantity'] + $data['proQuantity'];

            } else {
                $branchNames[$data['branchId']] = ['branchName' => $data['branchName'],
                    'branchTotalQuantity'                           => $data['proQuantity'],
                    $data['productid']                              => $data['proQuantity'],
                ];
            }

            $smarty->assign('branchData', $branchNames);
            $smarty->assign('dataArr', $dataArr);
        }
    } else {
        $allData = R::getAll('SELECT branchrequestproduct.comment, branch.branchId, branch.branchName, product.productName, sum(branchrequestproduct.quantity) proQuantity
                from branchrequest
                JOIN branchrequestproduct on branchrequestproduct.requestid = branchrequest.id
                left join branch ON branch.branchId = branchrequest.branchid
                left JOIN product on product.productId = branchrequestproduct.productid
                left JOIN productcat on productcat.productCatId = product.productCatId
                ' . $where . ' group by product.productId order by product.productName ASC');
    }
    return $allData;
}
