<?php

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

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

//here the db files that include in the file
include("../public/include_dao.php");
if (!in_array($do, $ajaxDoArr)) {
//the global file operation
    include("../public/impOpreation.php");
}

//Clientproductreview
require_once('../models/dao/ClientproductreviewDAO.class.php');
require_once('../models/dto/Clientproductreview.class.php');
require_once('../models/mysql/ClientproductreviewMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientproductreviewMySqlExtDAO.class.php');

// get the config file
include_once("../public/config.php");
include("../library/uploadImages.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/productCat/productCat.php");
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");

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

  Controller Name :- productCatController

  OPERTATION in Controller

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

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

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

//here goes the instances and general variables
//Clientproductreview
$clientProductReview = new Clientproductreview();
$clientProductReviewDAO = new ClientproductreviewMySqlDAO();
$clientProductReviewEX = new ClientproductreviewMySqlExtDAO();

$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) || $do == "show") {
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    //$smarty->display("productreview/show.html");
    $smarty->assign("customCheck", 1);
} elseif ($do == "add") {
    try {
        $id = add();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 'success', 'status_code' => 200, 'message' => $httpStatusCodes[200], 'data' => ['id' => $id]);
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
//echo $e;
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$e->getTraceAsString()]);
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "showallajax") {
    //showAllAjax();
} 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);

//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() {
    global $clientProductReview;
    global $clientProductReviewDAO;

    $clientid = (int) $_POST['clientid'];
    $productid = (int) $_POST['productid'];
    $rating = (int) $_POST['rating'];
    $review = $_POST['review'];

    if ($clientid > 0 && $productid > 0) {
        $clientProductReview->clientid = $clientid;
        $clientProductReview->productid = $productid;
        $clientProductReview->rating = $rating;
        $clientProductReview->review = $review;
        $clientProductReview->sysDate = date("Y-m-d H:i:s");
        $id = $clientProductReviewDAO->insert($clientProductReview);
    }

    return $id;
}

function showAllAjax() {
    global $wishListExt;
    $sIndexColumn = "id";

    /* DB table to use */
    $sTable = "wishlist
               join client on wishlist.clientid = client.clientid
               join product on wishlist.productid = product.productId";
    $aColumns = array('client.clientid', 'clientname', 'product.productid', 'productName', 'wishlist.sysDate');
    $aColumnsWithoutAS = array('client.clientid', 'clientname', 'product.productid', 'productName', 'wishlist.sysDate');
    $aColumnsWithout_clientmobile_for_ordering = array('client.clientid', 'clientname', 'product.productid', 'productName', 'wishlist.sysDate');

    // Indexed column (used for fast and accurate table cardinality)

    /*
     * Paging
     */


    $sLimit = "";
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
        $sLimit = "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    /*
     * Ordering
     */
    $sOrder = "";

    if (isset($_POST['order'][0])) {
        $sOrder = "ORDER BY  ";
        for ($i = 0; $i < intval($_POST['columns']); $i++) {
            $orderByColumnIndex = $_POST['order'][0]['column'] - 1; //this - 1 is because first column is not counted as it is checkbox
            $sOrder .= $aColumnsWithout_clientmobile_for_ordering[intval($_POST['columns'][$orderByColumnIndex]['data'])] . "
              " . ($_POST['order'][$i]['dir'] === 'asc' ? 'asc' : 'desc') . ", ";
        }
        $sOrder = substr_replace($sOrder, "", -2);
        if ($sOrder == "ORDER BY ") {
            $sOrder = "";
        }
    }
    /*
     * Filtering
     * NOTE this does not match the built-in DataTables filtering which does it
     * word by word on any field. It's possible to do here, but concerned about efficiency
     * on very large tables, and MySQL's regex functionality is very limited
     */
    // where del =0 and aqarstatus =0 and updatestatus in(1,2,3,4) and complete=1
    $sWhere = '';
    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
        $sWhere = " where (";
        for ($i = 0; $i < count($aColumns); $i++) {
            //            if ($aColumns[$i] == "sellbilldate") {
            //                //to get numbers and english chars only
            //                ##only alpha numeric is allowed . space not allowed
            //                $search = preg_replace('/[^#A-Za-z0-9]/', '', $_POST['search']['value']); // Removes special chars.
            //                if (!empty($search)) {
            //                    $sWhere .= $aColumns[$i] . " LIKE '%" . $search . "%' OR ";
            //                }
            //            }
            $sWhere .= $aColumnsWithoutAS[$i] . " LIKE '%" . $_POST['search']['value'] . "%' OR ";
        }
        $sWhere = substr_replace($sWhere, "", -3);
        $sWhere .= ")";
    }
    //-- search ------------------------------------------------------------
    if ($sWhere == '') {
        $queryString = ' WHERE';
    } else {
        $queryString = ' AND';
    }


//    $datefrom = $_POST['datefrom'];
//    $dateto = $_POST['dateto'];
//    if ($datefrom)
//        $queryString .= ' client.addDate >= "' . $datefrom . '" AND';
//
//    if ($dateto)
//        $queryString .= ' client.addDate <= "' . $dateto . '" AND';


    $message = "";
    ##needed Data
    ##############
    $arr = explode(' ', $queryString);
    //print_r($arr);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') { //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }
        if ($lastWord == 'WHERE') { //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }
        //print("<br>queryString: ".$queryString."<br>");
    }


    $sWhere .= $queryString;
    //----------------------------------------------------------------------
    $sQuery = "SELECT SQL_CALC_FOUND_ROWS distinct " . implode(",", $aColumns) . " FROM $sTable $sWhere $sOrder $sLimit ";
    //echo $sQuery;
    $rResult = $wishListExt->runSelectQuery($sQuery);

    /* Data set length after filtering */
    $sQuery = "SELECT COUNT( distinct " . $sIndexColumn . ") as id FROM $sTable $sWhere "; //$sOrder
    // echo $sQuery;
    $rResultFilterTotal = $wishListExt->runSelectQuery($sQuery);
    foreach ($rResultFilterTotal as $oneis) {
        $countis = $oneis->id;
    }
    $iFilteredTotal = $countis;
    /* Total data set length */
    $sQuery = "SELECT COUNT( distinct " . $sIndexColumn . ") as clientid FROM $sTable";
    $rResultTotal = $wishListExt->runSelectQuery($sQuery);

    foreach ($rResultTotal as $oneis) {
        $countit = $oneis->id;
    }
    //$aResultTotal = mysql_fetch_array($rResultTotal);
    $iTotal = $countit;

    $output = array(
        "draw" => intval(filter_input(INPUT_POST, 'sEcho')), //$_REQUEST['draw'], //intval(filter_input(INPUT_POST, 'sEcho')),
        "recordsTotal" => intval($iTotal),
        "recordsFiltered" => intval($iFilteredTotal),
        "totals" => array(),
        "data" => array()
    );
    $rowno = 1;
    $totalDebtShownNotDel = 0;
    $totalDebtShownDel = 0;
    foreach ($rResult as $aRow) {
        $row = array();
        for ($i = 0; $i < count($aColumns); $i++) {

            switch ($aColumns[$i]) {
                case "client.clientid":
                    //$row[] = $aRow->$aColumns[0];
                    $row[] = $rowno;
                    $aRow->clientname = mb_convert_encoding($aRow->clientname, 'UTF-8', 'UTF-8');
                    $row[] = $aRow->clientname;
                    break;
                case "product.productid":
                    $row[] = $aRow->productName;
                    break;
                case "wishlist.sysDate":
                    $row[] = $aRow->sysDate;
                    break;
                default:
                    break;
            }
        }
//        if ($Programsetting->clientdetail == 0) {
//            $row[] = '<a href="clientController.php?do = printdatail&id = ' . $aRow->clientid . '" type="button" class="btn btn-default btn-lg editicon" target="_blank"></a>';
//        }
        $output['data'][] = $row;
        $rowno++;
    }
    //print_r($output);

    echo json_encode($output, JSON_UNESCAPED_SLASHES); //note we use mb_convert_encoding($aRow->$aColumns[$i], 'UTF-8', 'UTF-8'); to correct encoding of error that stop this function
    //var_dump(json_last_error_msg());//Returns the error string of the last json_encode() or json_decode() call
}
