<?php
//the global file operation
include("../public/impOpreation.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');
//global varable
global $showoutside;

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();
include_once("../public/config.php");


//here the db files that include in the file
// GOES HERE ....................
include("../public/include_dao.php");
$do = $_GET['do'];

if (empty($do)) {

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

    $smarty->display("header.html");
    $smarty->display("stockReportsview/index.html");
    $smarty->display("footer.html");
} else if ($do == 'select2products') {
    select2products();
} else if ($do == 'select2categories') {
    select2categories();
} else if ($do == 'showajax') {
    showajax();
} else if ($do == 'deleteproductserial') {
    deleteproductserial();
}

function buildTree($parentId = 0) {
    global $allcutsup;
    $categories = R::getAll('select * from productcat where productCatParent = ?', [$parentId]);
    foreach ($categories as $category) {
        $allcutsup .= "," . $category['productCatId'];
        buildTree($category['productCatId']);
    }
}

function select2categories() {

    $row_array = array();
    $return_arr = array();
    $name = $_POST['searchTerm'];

    $productsData = R::getAll("SELECT productCatId, productCatName as name
    FROM  productcat
    WHERE productCatName LIKE '%" . $name . "%' limit 50");
    foreach ($productsData as $pro) {
        $row_array['id'] = $pro['productCatId'];
        $row_array['text'] = $pro['name'];
        array_push($return_arr, $row_array);
    }

    echo json_encode($return_arr);
}

function select2products() {
    global $allcutsup;
    $row_array = array();
    $return_arr = array();
    $name = $_POST['searchTerm'];
    $categoryid = $_POST['categoryid'];
    $query_search = "";
    if ($categoryid) {
        $allcutsup = '' . $categoryid;
        buildTree($categoryid);
        $query_search .= ' AND product.productCatId in (' . $allcutsup . ')';
    }

    $productsData = R::getAll("SELECT productId,CONCAT(productName,'/',productCatName) as name
    FROM product left join productcat on product.productCatId = productcat.productCatId
    WHERE CONCAT(productName,'/',productCatName) LIKE '%" . $name . "%' $query_search limit 50");
    foreach ($productsData as $pro) {
        $row_array['id'] = $pro['productId'];
        $row_array['text'] = $pro['name'];
        array_push($return_arr, $row_array);
    }

    echo json_encode($return_arr);
}

function showajax() {
    global $allcutsup;
    $columns = array('buybilldate','productName', 'serialnumber', 'don', 'chassisNo', 'motorNo', 'theColor', 'buybilldetailprice', 'buybilldetailprice', 'buybilldetailprice');

    $fromdate = $_POST['fromdate'];
    $todate = $_POST['todate'];
    $categoryid = $_POST['data1'];
    $productid = $_POST['data2'];



    $searchQuery = " ";
    if ($categoryid != '') {
        $allcutsup = '' . $categoryid;
        buildTree($categoryid);
        $searchQuery .= ' AND product.productCatId in (' . $allcutsup . ')';
    }
    if ($productid != '') {
        $searchQuery .= " and productserial.productid = " . $productid . " ";
    }

    if ($fromdate != '' && $todate != '') {
        $searchQuery .='and  buybilldate  >= "' . $fromdate . ' 00-00-00" and buybilldate <= "' . $todate . ' 23-59-55" ';
    }else if ($todate != '') {
        $searchQuery .=' and buybilldate <= "' . $todate . ' 23-59-55" ';
    }
    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
        $searchQuery .= "and ( productName LIKE " % '.$_POST["search"]["value"].' % "
                    OR serialnumber LIKE " % '.$_POST["search"]["value"].' % "
                    OR don LIKE " % '.$_POST["search"]["value"].' % "
                    OR chassisNo LIKE " % '.$_POST["search"]["value"].' % "
                    OR motorNo LIKE " % '.$_POST["search"]["value"].' % "
                    OR theColor LIKE " % '.$_POST["search"]["value"].' % "
                    OR buybilldetailprice LIKE " % '.$_POST["search"]["value"].' % "
        )
     ";
    }


    if (isset($_POST["order"])) {
        $searchQuery .= 'ORDER BY ' . $columns[$_POST['order']['0']['column']] . ' ' . $_POST['order']['0']['dir'] . '  ';
    }
    // else
    // {
    //  $searchQuery .= "ORDER BY  $controllName.id DESC ";
    // }


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

    $rResult = R::getAll("SELECT productserial.productserailid,productName,productCatName,serialnumber,don,chassisNo,motorNo,theColor,
    buybilldetailprice,buybilldetailquantity,payedtax,buybilldate FROM productserial left join product on product.productid = productserial.productid
    left join productcat on product.productCatId = productcat.productCatId
    left join buybilldetail on buybilldetail.buybilldetailid = productserial.buybilldetailid
    left join buybill on buybilldetail.buybillid = buybill.buybillid
    WHERE productserial.don > 0 and productserial.del = 0  $searchQuery ");

    $apps = count($rResult);

    $output = array(
        "recordsTotal" => intval($apps),
        "recordsFiltered" => intval($apps),
        "data" => array()
    );
    $buybilldetailquantity = 0;
    $buybilldetailprice = 0;
    $payedtax = 0;
    $total = 0;
    foreach ($rResult as $row) {
        // $buybilldetailquantity += $row["buybilldetailquantity"];
//        $buybilldetailquantity += 1;
        $buybilldetailquantity += $row["don"];
        $buybilldetailprice += $row["buybilldetailprice"] * $row["don"];
        //$payedtax += ($row["buybilldetailprice"] * $row["payedtax"]) / 100;
        $payedtax += ($row["buybilldetailprice"] * $row["don"] * $row["payedtax"]) / 100;
        $total += round((($row["buybilldetailprice"] * $row["don"]) + (($row["buybilldetailprice"] * $row["don"] * $row["payedtax"]) / 100)), 2);
         $sa = round((($row["buybilldetailprice"] * $row["don"]) + (($row["buybilldetailprice"] * $row["don"] * $row["payedtax"]) / 100)), 2);

        $sub_array = array();
		 $sub_array[] = date('Y-m-d', strtotime($row["buybilldate"]));
        $sub_array[] = $row["productName"] . ' / ' . $row["productCatName"];
        $sub_array[] = $row["serialnumber"];
        $sub_array[] = $row["don"];
        $sub_array[] = $row["chassisNo"];
        $sub_array[] = $row["motorNo"];
        $sub_array[] = $row["theColor"];
        $sub_array[] = $row["buybilldetailprice"] * $row["don"];

        $sub_array[] = ($row["buybilldetailprice"] * $row["don"] * $row["payedtax"]) / 100;
                            $sub_array[] =ceil($sa);

        $sub_array[] = "<a class='btn grey-cascade btn-xs productserailid' data-id='" . $row["productserailid"] . "'>حذف</a>";
        $output['data'][] = $sub_array;
    }
    $sub_array2 = array();
    $sub_array2[] = "";
	 $sub_array2[] = "";
    $sub_array2[] = "الكميه";
    $sub_array2[] = $buybilldetailquantity;
    $sub_array2[] = "";
    $sub_array2[] = "";
    $sub_array2[] = "الاجمالى";
    $sub_array2[] = $buybilldetailprice;
    $sub_array2[] = $payedtax;
    $sub_array2[] = ceil($total);
    $sub_array2[] = "";
    $output['data'][] = $sub_array2;

    echo json_encode($output, JSON_UNESCAPED_SLASHES);
}

function deleteproductserial() {
    $productserailid = $_POST['productserailid'];
    try {
        R::exec("UPDATE `productserial` SET `del`= 1  WHERE productserailid = '" . $productserailid . "' ");
        echo 1;
    } catch (Exception $e) {
        echo 0;
    }
}
?>