<?php
include("../public/impOpreation.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');

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


$do = $_GET['do'];
$today = date("Y-m-d H:i:s");
$date = date("Y-m-d");

if (empty($do)) {  
    $smarty->display("header.html");
    $smarty->display("maintenanceproductview/add.html");
    $smarty->assign("maintenance", 1);
    $smarty->display("footer.html");
} elseif ($do == "show") {
    include_once("../public/authentication.php");
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->display("header.html");
    $smarty->display("maintenanceproductview/show.html");
    $smarty->assign("maintenance", 1);
    $smarty->display("footer.html");
} elseif ($do == "edit") {
    include_once("../public/authentication.php");
    $id = filter_input(INPUT_GET, 'id');
    $del = filter_input(INPUT_GET, 'del');
    $productdata = R::getRow('SELECT product.* FROM `product` WHERE productId = ?',[$id]);
    $smarty->assign('productdata', $productdata);
    $smarty->assign('del', $del);
    $smarty->display("header.html");
    $smarty->display("maintenanceproductview/edit.html");
    $smarty->assign("maintenance", 1);
    $smarty->display("footer.html");
}else if ($do == 'savedata') {
  savedata();
}else if ($do == 'showajax') {
  showajax();
}else if ($do == 'saveproductcat') {
  saveproductcat();
}




function saveproductcat() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $productCatId = filter_input(INPUT_POST, 'productCatId');
    $productCatName = filter_input(INPUT_POST, 'productCatName');
    $productCatParent = filter_input(INPUT_POST, 'productCatParent');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    try {
        if (!$productCatParent) {$productCatParent = 0;}
        if (!$productCatId) {

            R::exec("INSERT INTO `productcat`(`productCatName`, `productCatDate`, `productCatParent`, `userId`, `conditions`) VALUES ('$productCatName','$date', $productCatParent, $userid, 0 )");
          $productcatlast =R::getROW("SELECT * FROM `productcat` order by productCatId desc");         
          $productCatId = $productcatlast['productCatId'];
          $text = $productcatlast['productCatName'];
        }else{
   
            R::exec("UPDATE `productcat` SET  `productCatName`='$productCatName', `productCatParent`= $productCatParent WHERE productCatId = $productCatId");
            $text = $productCatName;
        }
        $selectiditr = 'productCatId'.$selectitr;
        echo json_encode(array('id' => $productCatId,'selectname' => 'productCatId','selectid' => $selectiditr,'text' => $text
            ,'selectid' => $selectiditr,'selectitr' => $selectitr));
    } catch (Exception $e) {
        echo 0 ;
    }
}


function savedata() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $productName = filter_input(INPUT_POST, 'productName');
    $productDescription = filter_input(INPUT_POST, 'productDescription');
    $productCatId = filter_input(INPUT_POST, 'productcat');
    $productDate = filter_input(INPUT_POST, 'productDate');
    $runquery = filter_input(INPUT_POST, 'runquery');
    $productId = filter_input(INPUT_POST, 'productId');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    try {
        if (!$productId) {
             R::exec("INSERT INTO `product`(`productName`, `productDescription`, `productCatId`, `productDate`, `conditions`, `userId`,`runquery`) VALUES ('$productName','$productDescription','$productCatId','$date'
                , 0 ,'$userid','$runquery')");
            $last =R::getROW("SELECT productId, productName FROM `product` order by productId desc");
            $productId = $last['productId'];
            $text = $last['productName'];
        }else{
           R::exec("UPDATE `product` SET `productName`='$productName',`productDescription`='$productDescription',`productCatId`='$productCatId',`runquery`= '$runquery' WHERE productId = $productId");
            $text = $productName;
        }
        $selectiditr = 'productId'.$selectitr;
        echo json_encode(array('id' => $productId,'selectname' => 'productId','selectid' => $selectiditr,'text' => $text
            ,'selectid' => $selectiditr,'selectitr' => $selectitr));
    } catch (Exception $e) {
        echo 0 ;
    }
}


function showajax() {
    $columns = array('productId', 'productName', 'productDate', 'productCatName', 'employeename', 'productId', 'productId');
    $start_date = $_POST['start_date'];
    $end_date   = $_POST['end_date'];
    $del        = $_POST['del'];
    $data1      = $_POST['data1'];
    $data2      = $_POST['data2'];
    $data3      = $_POST['data3'];

    $searchQuery = " ";
    if($data1 != ''){
      $searchQuery .=  " and product.productId = ".$data1. " ";
    }
    if($del == ''){
       $searchQuery .= " and product.conditions = 0 "; 
    }

    if($data3 != ''){
       $searchQuery .= " and product.productCatId = ".$data3. " ";
    }
    
    if($start_date != '' && $end_date != ''){
       $searchQuery .=' and  product.productDate  >= "' . $start_date . ' 00-00-00" and product.productDate <= "' . $end_date . ' 23-59-55" ';
    }

    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( product.productId LIKE "%'.$_POST["search"]["value"].'%" 
                    OR product.productName LIKE "%'.$_POST["search"]["value"].'%"
                    OR product.productDate LIKE "%'.$_POST["search"]["value"].'%"
                    OR productCatName LIKE "%'.$_POST["search"]["value"].'%"
                    OR employeename LIKE "%'.$_POST["search"]["value"].'%"
        )
     ";
    }


    if(isset($_POST["order"]))
    {
    $searchQuery .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'  ';
    }
    else
    {
     $searchQuery .= "ORDER BY  product.productId DESC ";
    }
    
     $totals = R::count('product','LEFT JOIN user ON product.userid = user.userid 
        LEFT JOIN productcat ON product.productCatId = productcat.productCatId  WHERE 1 '.$searchQuery.' ');
    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    $rResult = R::getAll('SELECT product.* ,employeename ,productCatName  FROM `product` 
        LEFT JOIN user ON product.userid = user.userid 
        LEFT JOIN productcat ON product.productCatId = productcat.productCatId  
        WHERE 1 '.$searchQuery.' ');   
    $apps = count($rResult);
    
    
     
    $output = array(  
        "draw" => intval($_POST["draw"]),
        "recordsTotal" => intval($apps),
        "recordsFiltered" => $totals,
        "data" => array()
    );
  
       foreach ($rResult as $row) {
        $sub_array = array();
        $sub_array[] = $row["productId"];
        $sub_array[] = $row["productName"];
        $sub_array[] = $row["productDate"];
        $sub_array[] = $row["productCatName"];
        $sub_array[] = $row['employeename'] ;  
        if($row["conditions"] == 0){  
        $sub_array[] = '<a href="maintenanceproducts.php?do=edit&id='. $row["productId"] .'&del=0" type="button" class="btn btn-default btn-lg editicon"></a>';
         $sub_array[] = '<a href="javascript:;" data-id="'. $row["productId"] .'" data-tableid="productId" data-table="product" type="button" class="btn btn-default btn-lg deleteicon removeteble"  ></a>';
        }else{
          $sub_array[] = '<a href="maintenanceproducts.php?do=edit&id='. $row["productId"] .'&del=1" type="button" class="btn btn-default btn-lm ">تفاصيل</a>';
          $sub_array[] = 'محذوف ';
        }
       
        $output['data'][] = $sub_array;
       }
    
       echo json_encode($output, JSON_UNESCAPED_SLASHES);

}





?>