<?php

session_start();
ob_start();
//the global file operation
$do = isset($_GET['do']) ? $_GET['do'] : "";
$ajaxDoArr = array("getallonlinecats","getallonlineSubCats");

include("initiateStaticSessionCommingWithCurl.php");
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
    array_push($ajaxDoArr, $do);
}


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

include("reportfunctions.php");

//global varable
global $showoutside;

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

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

//OnlineCat

//Programsetting
require_once('../models/dao/ProgramsettingsDAO.class.php');
require_once('../models/dto/Programsetting.class.php');
require_once('../models/mysql/ProgramsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProgramsettingsMySqlExtDAO.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/onlinecat/onlinecat.php");
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");

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

  Controller Name :- onlineCatController

  OPERTATION in Controller

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

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

//here goes the instances and general variables
$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();

//Programsetting
$Programsetting = new Programsetting();
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingEX = new ProgramsettingsMySqlExtDAO();

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

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

//check and use the condition that suite this action
if (empty($do)) {
    //here the permission check
    $allParents = getOnlineCatParents();
    $smarty->assign("categories", $allParents);
    $smarty->display("onlineCatview/add.html");
} elseif ($do == "add") {
    $flag = $_GET['flag'];
    try {
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
} elseif ($do == "show") {
    $allData = R::getAll('SELECT * FROM onlinecat WHERE conditions = 0');
    $smarty->assign("allData", $allData);
    $catId = $_REQUEST['catId'];
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    if (isset($catId) && !empty($catId) && $catId != '-1') {
        showByCatId($catId);
    } else {
        show();
    }
    $smarty->display("onlineCatview/show.html");
    $smarty->assign('customUsergroup', 1);

    $smarty->assign("customCheck", 1);
} elseif ($do == "executeOperation") {
    try {
        executeOperation();
        show();
        $smarty->display("onlineCatview/show.html");

        $smarty->assign("customCheck", 1);
    } catch (Exception $e) {
        $smarty->display("error.html");
    }
} elseif ($do == "returndelete") { //returndelete
    try {
        returndelete();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "tempdelete") { //tempdelete
    try {
        $note = tempdelete();
        if ($note != "success") {
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
                echo 1;
            } else {
                header("location:?do=sucess");
            }
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "deleteFinaly") { //tempdelete
    try {
        $id = $_GET['id'];
        deleteFinaly($id);

        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "edit") { //edit  onlineCat
    $id = $_GET['id'];
    $allParents = getOnlineCatParents($id);
    $smarty->assign("allParents", $allParents);
    $parentid = $_GET['parentid'];
    if ($parentid) {
        $onlineCatparent = R::load('onlinecat', $parentid);
        $smarty->assign("onlineCatparent", $onlineCatparent);
    }
    $smarty->assign("parentid", $parentid);
    $smarty->assign("categories", $allParents);

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

    $smarty->display("onlineCatview/edit.html");
} elseif ($do == "update") { //edit update
    try {
        update();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            echo 1;
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
} elseif ($do == "getallonlinecats") {
    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);
    $withoutId = $_GET['withoutId'];

    $row_array = array();
    $return_arr = array();
    $resultData = R::getAll('SELECT * FROM onlinecat where conditions = 0 and name LIKE "%' . $name . '%" limit ' . $limit);
    foreach ($resultData as $value) {
        if ($withoutId && $withoutId == $value['id'])
            continue;
        $parentId = $value['id'];
        $pathArr = fetch_recursive($parentId, $categories);
        $row_array['id'] = $parentId;
        $row_array['text'] = $pathArr;
        array_push($return_arr, $row_array);
    }

    //echo $return_arr;
    echo json_encode($return_arr);
} elseif ($do == "getallonlineSubCats") {
    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);
    $withoutId = $_GET['withoutId'];

    $row_array = array();
    $return_arr = array();
    $resultData = R::getAll('SELECT child.*, parent.name as parentName
                FROM onlinecat child
                left join onlinecat parent on child.`parentid` = parent.id 
                WHERE child.conditions = 0 and child.parentid != 0 and child.name LIKE "%' . $name . '%" limit ' . $limit);
    foreach ($resultData as $value) {
        if ($withoutId && $withoutId == $value['id'])
            continue;
        $parentId = $value['id'];
        $pathArr = fetch_recursive($parentId, $categories);
        $row_array['id'] = $parentId;
        $row_array['text'] = $pathArr;
        array_push($return_arr, $row_array);
    }

    //echo $return_arr;
    echo json_encode($return_arr);
}
$smarty->assign("customValidation", 1);

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

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

function getOnlineCatParents($id = 0)
{
    $allParents = R::getAll('SELECT onlinecat.*
                    FROM onlinecat
                    WHERE id NOT IN (SELECT id FROM  product where conditions=0)
                    AND onlinecat.conditions = 0 and onlinecatid !=' . $id . '');
    return $allParents;
}

// add in onlineCat tbl
function add()
{
    global $today;

    $name = $_POST['name'];
    $name_en = $_POST['name_en'];
    $parent = (int) $_POST['parent'];
    #################################
    if (empty($parent) || $parent == -1) {
        $parent = 0;
    }

    $onlineCat = R::dispense('onlinecat');
    $onlineCat->conditions = 0;
    $onlineCat->sysdate = $today;
    $onlineCat->name = $name;
    $onlineCat->name_en = $name_en;
    $onlineCat->parentid = $parent;
    $onlineCat->user_id = $_SESSION['userid'];
    //     var_dump($onlineCat);
    // die();
    $id = R::store($onlineCat);

    return $id;
}

//show
function show()
{
    global $smarty;

    $onlineCatData = R::getAll('SELECT child.*, parent.name as parentName
                FROM onlinecat child
                left join onlinecat parent on child.`parentid` = parent.id
                ORDER BY child.id DESC');
    $smarty->assign('onlineCatData', $onlineCatData);
}

function showByCatId($catId)
{
    global $smarty;

    $onlineCatData = R::getAll('SELECT child.*, parent.name as parentName
                FROM onlinecat child
                left join onlinecat parent on child.`parentid` = parent.id
                WHERE child.id = ' . $catId);
    $smarty->assign('onlineCatData', $onlineCatData);
}

function executeOperation()
{
    global $smarty;
    global $outputString;

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

    $choosedItemArr = $_POST['choosedItem'];
    //print_r($choosedItemArr);
    if (count($choosedItemArr) > 0) {
        $i = 1;
        foreach ($choosedItemArr as $id) {
            //get product category name
            $onlineCatData = R::load('onlinecat', $id);

            $onlineCatName = $onlineCatData->name;

            if ($operationType == '1') { //tempdelete
                try {
                    $note = tempdelete($id);
                    if ($note != "success") {
                        $outputString .= $onlineCatName . ": " . $note . "<br/>";
                    } else {
                        $outputString .= $onlineCatName . ": تمت العملية بنجاح<br/>";
                    }
                } catch (Exception $e) {
                }
            } elseif ($operationType == "2") {
                try {
                    returndelete($id);

                    $outputString = " تمت العملية بنجاح";
                } catch (Exception $e) {
                    $note = "حدث خطأ أثناء إتمام العملية";
                }
            }
            $i++;
        }
        $smarty->assign("outputString", $outputString);
    }
}

function tempdelete($id)
{
    global $ProductEX;
    if (empty($id)) {
        $id = $_GET['id'];
    }

    if (!empty($id)) {

        //1- check if there are any products associated with this category
        $productsData = $ProductEX->queryByOnlineCatIdExt($id);
        //2- check if there are any child category for this parent category
        $childCategories = R::getAll('SELECT * FROM onlinecat WHERE parentid = ' . $id);
        if (count($productsData) > 0 || count($childCategories) > 0) {
            $note = "لا يمكن حذف هذا التصنيف لارتباطه ببيانات أخرى";
        } else {
            try {
                R::exec('UPDATE onlinecat SET sysdate = "' . date("Y-m-d") . '" , user_id = ' . $_SESSION['userid'] . ', conditions = 1 where id = ' . $id);
                $note = "success";
            } catch (Exception $e) {
                $note = "حدثت مشكلة أثناء إجراء العملية ... يرجى المحاولة مرة أخرى";
            }
        }
    }
    return $note;
}

function returndelete($id)
{
    if ($id == "") {
        $id = $_GET['id'];
    }

    //return delete from onlineCat tbl
    R::exec('UPDATE onlinecat SET conditions = 0 WHERE id = ' . $id);
}

function edit()
{
    $id = $_GET['id'];
    $onlineCatData = R::load('onlinecat', $id);
    return $onlineCatData;
}

function update()
{
    global $today;

    $id = $_POST['id'];
    $conditions = $_POST['conditions'];
    $name = $_POST['name'];
    $name_en = $_POST['name_en'];
    $parent = $_POST['parent'];
    #################################


    if (empty($parent) || $parent == -1) {
        $parent = 0;
    }
    $onlineCat = R::load('onlinecat', $id);
    $onlineCat->sysdate = $today;
    $onlineCat->name = $name;
    $onlineCat->name_en = $name_en;
    $onlineCat->parentid = $parent;
    $onlineCat->user_id = $_SESSION['userid'];
    $onlineCat->id = $id;
    $onlineCat->conditions = $conditions;

    R::store($onlineCat);
}

function deleteFinaly($id)
{
    global $productDAO;

    $prodactcatdata = R::getAll('SELECT * FROM onlinecat WHERE parentid = ' . $id . ' AND conditions = 0 ');
    if (count($prodactcatdata) > 0) {
        foreach ($prodactcatdata as $myprodactcatdata) {
            deleteFinaly($myprodactcatdata['id']);
        }

        R::exec('DELETE FROM product WHERE onlinecatid = ' . $id);
        R::trash('onlinecat', $id);
    } else {
        R::exec('DELETE FROM product WHERE onlinecatid = ' . $id);
        R::trash('onlinecat', $id);
    }
}

function fetch_recursive($parentid, $categories)
{
    if ($parentid) {
        $catData = R::getRow('SELECT child.*, parent.name as parentName
                    FROM onlinecat  as child
                    left join onlinecat  as parent on child.`parentid` = parent.id
                    WHERE child.id = ' . $parentid);
        if (count($catData) > 0) {
            $categories .= $catData['name'] . '/';
            $newParentId = $catData['parentid'];
            return fetch_recursive($newParentId, $categories);
        }
    }
    $categories = substr($categories, 0, strlen($categories) - 1);
    return $categories;
}
