<?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");
$time = date("H:i:s");
$smarty->assign('date', $date);
$smarty->assign('time', $time);
$smarty->assign('username', $_SESSION['username']);
if (empty($do)) {  
    $smarty->display("header.html");
    $smarty->display("maintenanceview/add.html");
    $smarty->assign("maintenance", 1);
    $smarty->display("footer.html");
} elseif ($do == "show") {
    include_once("../public/authentication.php");
    $maintenancecases = R::findAll('maintenancecases','conditions = 0');
    $smarty->assign('maintenancecases', $maintenancecases);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->display("header.html");
    $smarty->display("maintenanceview/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');
    $maintenancedata = R::load('maintenances',$id);
    $users =R::getCell("SELECT employeename FROM `user` WHERE userid = ? ",[$maintenancedata->userid]);
    $maintenancedata->employeename =  $users;
    $new_time = explode(" ",$maintenancedata['dateatime']);
    $smarty->assign('get_date', $new_time[0]);
    $smarty->assign('get_time', $new_time[1]);
    $smarty->assign('maintenancedata', $maintenancedata);
    $maintenancecomments = R::findAll('maintenancecomments','maintenanceid = ? and conditions = 0 order by id desc',[$id]);
    foreach($maintenancecomments  as $comments){
        $last =R::getCell("SELECT employeename FROM `user` WHERE userid = ? ",[$comments->userid]);
        $comments->employeename =  $last;
    }
    $smarty->assign('maintenancecomments', $maintenancecomments);
    $smarty->assign('del', $del);
    $smarty->display("header.html");
    $smarty->display("maintenanceview/edit.html");
    $smarty->assign("maintenance", 1);
    $smarty->display("footer.html");
}else if ($do == 'savedata') {
  savedata();
}else if ($do == 'showajax') {
  showajax();
}else if ($do == 'savebranch') {
  savebranch();
}else if ($do == 'savecenter') {
  savecenter();
}else if ($do == 'savecase') {
  savecase();
}else if($do == 'savecomment') {
  savecomment();
}else if ($do == 'changecase') {
  changecase();
}else if ($do == 'changecenter') {
  changecenter();
}else if ($do == 'appentcomment') {  
$itr = filter_input(INPUT_POST, 'itr');
$appendname = filter_input(INPUT_POST, 'appendname');
$smarty->assign('itr', $itr);
$smarty->display("maintenanceview/".$appendname.".html");  
}else if ($do == 'updatecomment') {
  updatecomment();
}



function savecomment() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $comments = filter_input(INPUT_POST, 'comments');
    $maintenancecommentid = filter_input(INPUT_POST, 'maintenancecommentid');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    try {
        if (!$maintenancecommentid) {
            $maintenancecomments = R::dispense('maintenancecomments');
            $maintenancecomments->maintenancecommentdate = $today;  
            $maintenancecomments->conditions = 0;
            $maintenancecomments->userid = $userid;
        }else{
            $maintenancecomments = R::load('maintenancecomments', $maintenancecommentid);
            $maintenancecomments->euserid = $userid;
        }
        $maintenancecomments->comments =  $comments;  
        $maintenancecomments->maintenanceid =  $selectitr;  
        $maintenancecommentid = R::store($maintenancecomments);
           
        $selectiditr = 'maintenancecommentid'.$selectitr;
        echo json_encode(array('id' => $maintenancecommentid,'selectname' => 'maintenancecommentid','selectid' => $selectiditr,'text' => $comments,'selectid' => $selectiditr,'selectitr' => $selectitr));
    } catch (Exception $e) {
        echo 0 ;
    }
}

function savecase() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $casename = filter_input(INPUT_POST, 'casename');
    $maintenancecaseid = filter_input(INPUT_POST, 'maintenancecaseid');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    try {
        if (!$maintenancecaseid) {
             $maintenancecases = R::dispense('maintenancecases');
        }else{
            $maintenancecases = R::load('maintenancecases', $maintenancecaseid);
        }
        $maintenancecases->casename =  $casename;  
        $maintenancecases->maintenancecasedate = $today;  
        $maintenancecases->conditions = 0;
        $maintenancecases->userid = $userid;
        $maintenancecaseid = R::store($maintenancecases);
        $selectiditr = 'maintenancecaseid'.$selectitr;
        echo json_encode(array('id' => $maintenancecaseid,'selectname' => 'maintenancecaseid','selectid' => $selectiditr,'text' => $casename,'selectid' => $selectiditr,'selectitr' => $selectitr));
    } catch (Exception $e) {
        echo 0 ;
    }
}


function savebranch() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $branchName = filter_input(INPUT_POST, 'branchName');
    $phone = filter_input(INPUT_POST, 'phone');
    $mobile = filter_input(INPUT_POST, 'mobile');
    $branchNo = filter_input(INPUT_POST, 'branchNo');
    $branchAddress = filter_input(INPUT_POST, 'branchAddress');
    $branchId = filter_input(INPUT_POST, 'branchId');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    try {
        if (!$branchId) {
          R::exec("INSERT INTO `branch`(`branchName`, `branchDate`, `phone`, `mobile`, `branchNo`, `branchAddress`) VALUES ('$branchName','$date','$phone','$mobile','$branchNo','$branchAddress')");
          $last =R::getROW("SELECT branchId, branchName FROM `branch` order by branchId desc");
          $branchId = $last['branchId'];
          $text = $last['branchName'];
        }else{
           R::exec("UPDATE `branch` SET `branchName`='$branchName',`phone`='$phone',`mobile`= '$mobile' ,`branchNo`= '$branchNo',`branchAddress`= '$branchAddress' WHERE branchId = $branchId");
           $text = $branchName;
        }

       $selectiditr = 'branchId'.$selectitr;
        echo json_encode(array('id' => $branchId,'selectname' => 'branchId','selectid' => $selectiditr,'text' => $text,'selectid' => $selectiditr,'selectitr' => $selectitr));
    } catch (Exception $e) {
        echo 0 ;
    }
}


function savecenter() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $centername = filter_input(INPUT_POST, 'centername');
    $centerphone = filter_input(INPUT_POST, 'centerphone');
    $centermobile = filter_input(INPUT_POST, 'centermobile');
    $centeraddress = filter_input(INPUT_POST, 'centeraddress');
    $administrator = filter_input(INPUT_POST, 'administrator');
    $administratorphone = filter_input(INPUT_POST, 'administratorphone');
    $administratordebt = filter_input(INPUT_POST, 'administratordebt');
    $maintenancecenterid = filter_input(INPUT_POST, 'maintenancecenterid');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    try {
        if (!$maintenancecenterid) {
            $maintenancecenters = R::dispense('maintenancecenters');
            $maintenancecenters->maintenancecenterdate = $today;  
            $maintenancecenters->conditions = 0;
            $maintenancecenters->userid = $userid;
        }else{
            $maintenancecenters = R::load('maintenancecenters',$maintenancecenterid);
            $maintenancecenters->euserid = $userid;
        }
            $maintenancecenters->centername =  $centername;  
            $maintenancecenters->centerphone =  $centerphone;  
            $maintenancecenters->centermobile =  $centermobile;  
            $maintenancecenters->centeraddress =  $centeraddress;  
            $maintenancecenters->administrator =  $administrator;  
            $maintenancecenters->administratorphone =  $administratorphone;  
            $maintenancecenters->administratordebt =  $administratordebt;  
            $maintenancecenterid = R::store($maintenancecenters);
            if ($selectitr) {
              R::exec("UPDATE `maintenances` SET `maintenancecenterid`= $maintenancecenterid WHERE id = $selectitr");
            }
           
        $selectiditr = 'maintenancecenterid'.$selectitr;
        echo json_encode(array('id' => $maintenancecenterid,'selectname' => 'maintenancecenterid','selectid' => $selectiditr,'text' => $centername,'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'];
    $productId = filter_input(INPUT_POST, 'product');
    $supplierid = filter_input(INPUT_POST, 'supplier');
    $branchId = filter_input(INPUT_POST, 'branch');
    $clientid = filter_input(INPUT_POST, 'client');
    $maintenancecenterid = filter_input(INPUT_POST, 'maintenancecenters');
    $maintenancecaseid = filter_input(INPUT_POST, 'maintenancecases');
    $receiptnumber = filter_input(INPUT_POST, 'receiptnumber');
    $dateatime = filter_input(INPUT_POST, 'dateatime');
    $dateatime2 = filter_input(INPUT_POST, 'dateatime2');
    $quantity = filter_input(INPUT_POST, 'quantity');
    $defect = filter_input(INPUT_POST, 'defect');
    $accessories = filter_input(INPUT_POST, 'accessories');
    $notes = filter_input(INPUT_POST, 'notes');
    $estimatedcost = filter_input(INPUT_POST, 'estimatedcost');
    $prepaid = filter_input(INPUT_POST, 'prepaid');
    $datepurchase = filter_input(INPUT_POST, 'datepurchase');
    $invoicenumber = filter_input(INPUT_POST, 'invoicenumber');
    $invoicedate = filter_input(INPUT_POST, 'invoicedate');
    $maintorguar = filter_input(INPUT_POST, 'maintorguar');
    $maintenanceid = filter_input(INPUT_POST, 'maintenanceid');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    $commentitr  = filter_input(INPUT_POST, 'commentitr');
    try {
        if (!$maintenanceid) {
            $maintenances = R::dispense('maintenances');
            $maintenances->maintenancedate = $today;  
            $maintenances->conditions = 0;
            $maintenances->userid = $userid;
            $maintenances->maintenancecaseid = 1;
            $maintenances->maintenancepolicyid = 0;  
        }else{
            $maintenances = R::load('maintenances',$maintenanceid);
            $maintenances->euserid = $userid;
            
        }
            $maintenances->maintenancecenterid = $maintenancecenterid;
            $maintenances->clientid = $clientid;          
            $maintenances->branchid = $branchId;
            $maintenances->supplierid = $supplierid;          
            $maintenances->productid = $productId;
            $maintenances->maintenancecaseid = $maintenancecaseid;
            $maintenances->receiptnumber = $receiptnumber;          
            $maintenances->dateatime = $dateatime.' '.$dateatime2;
            $maintenances->quantity = $quantity; 
            $maintenances->defect = $defect; 
            $maintenances->accessories = $accessories; 
            $maintenances->notes = $notes; 
            $maintenances->estimatedcost = $estimatedcost; 
            $maintenances->prepaid = $prepaid;          
            $maintenances->datepurchase = $datepurchase; 
            $maintenances->invoicenumber = $invoicenumber; 
            $maintenances->invoicedate = $invoicedate; 
            $maintenances->maintorguar = $maintorguar; 
            $maintenanceid = R::store($maintenances);

            for ($i = 1; $i <= $commentitr; $i++) {
                $maintenancecommentid = filter_input(INPUT_POST, 'maintenancecommentid_' . $i);
                $comments = filter_input(INPUT_POST, 'comments_' . $i);

                if (!$comments) {
                    continue;
                }
                if (!$maintenancecommentid) {
                    $maintenancecomments = R::dispense('maintenancecomments');
                    $maintenancecomments->maintenancecommentdate = $today;  
                    $maintenancecomments->conditions = 0;
                    $maintenancecomments->userid = $userid;
                }else{
                    $maintenancecomments = R::load('maintenancecomments', $maintenancecommentid);
                    $maintenancecomments->euserid = $userid;
                }
                $maintenancecomments->comments =  $comments;  
                $maintenancecomments->maintenanceid = $maintenanceid;  
                R::store($maintenancecomments);
            }

        $selectiditr = 'maintenanceid'.$selectitr;
        echo json_encode(array('id' => $maintenanceid,'selectname' => 'maintenanceid','selectid' => $selectiditr,'text' => $text,'selectid' => $selectiditr,'selectitr' => $selectitr));
    } catch (Exception $e) {
        echo 0 ;
    }
}


function showajax() {
    $columns = array('id', 'clientname', 'productid', 'suppliername', 'branchName', 'invoicedate', 'maintenancereceiptdata', 'employeename', 'id', 'id');
    $start_date = $_POST['start_date'];
    $end_date   = $_POST['end_date'];
    $del        = $_POST['del'];
    $data1      = $_POST['data1'];
    $data2      = $_POST['data2'];
    $data3      = $_POST['data3'];
    $data4      = $_POST['data4'];
    $data5      = $_POST['data5'];

    $searchQuery = " ";
    if($data1 != ''){
      $searchQuery .=  " and maintenances.supplierid = ".$data1. " ";
    }

    if($data2 != ''){
      $searchQuery .=  " and maintenances.clientid = ".$data2. " ";
    }
    if($del == ''){
       $searchQuery .= " and maintenances.conditions = 0 "; 
    }

    if($data3 != ''){
       $searchQuery .= " and maintenances.branchid = ".$data3. " ";
    }

    if($data4 != '' && $data4 > 0){
       $searchQuery .= " and maintenances.maintorguar = ".$data4. " ";
    }

    if($data5 != ''){
       $searchQuery .= " and maintenances.maintenancecaseid = ".$data5. " ";
    }
    
    if($start_date != '' && $end_date != ''){
       $searchQuery .=' and  maintenances.maintenancedate  >= "' . $start_date . ' 00-00-00" and maintenances.maintenancedate <= "' . $end_date . ' 23-59-55" ';
    }


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( maintenances.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR clientname LIKE "%'.$_POST["search"]["value"].'%"
                    OR productid LIKE "%'.$_POST["search"]["value"].'%"
                    OR suppliername LIKE "%'.$_POST["search"]["value"].'%"
                    OR maintenances.supplierdate LIKE "%'.$_POST["search"]["value"].'%"
                    OR branchName 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  maintenances.id DESC ";
    }
    
     $totals = R::count('maintenances','LEFT JOIN user ON maintenances.userid = user.userid 
        LEFT JOIN client ON maintenances.clientid = client.clientid
        LEFT JOIN supplier ON maintenances.supplierid = supplier.supplierid
        LEFT JOIN branch ON maintenances.branchid = branch.branchId  
          WHERE 1 '.$searchQuery.' ');
    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    $rResult = R::getAll('SELECT maintenances.* ,employeename ,clientname ,suppliername ,branchName, centername, maintenancecenterid FROM `maintenances` 
        LEFT JOIN user ON maintenances.userid = user.userid 
        LEFT JOIN client ON maintenances.clientid = client.clientid 
        LEFT JOIN supplier ON maintenances.supplierid = supplier.supplierid 
        LEFT JOIN branch ON maintenances.branchid = branch.branchId  
        LEFT JOIN maintenancecenters ON maintenances.maintenancecenterid = maintenancecenters.id  
        WHERE 1 '.$searchQuery.' ');   
    $apps = count($rResult);
    
    
     
    $output = array(  
        "draw" => intval($_POST["draw"]),
        "recordsTotal" => intval($apps),
        "recordsFiltered" => $totals,
        "data" => array()
    );
  
       foreach ($rResult as $row) {
        $comments = R::findOne('maintenancecomments','maintenanceid = ? order by id desc',[$row['id']]);
        $products = R::getAll("SELECT productName FROM product  WHERE productId in (".$row['productid'].")");
        $productName = '';
        foreach($products as $product){
              $productName .= $product['productName']. ' / ';
        }
          
        $sub_array = array();
          $sub_array[] = '<label class="mt-checkbox mt-checkbox-single mt-checkbox-outline">
                            <input type="checkbox" class="checkboxes" value="' . $row["id"] . '" />
                            <span></span>
                        </label>';
        $sub_array[] = $row["clientname"];
        $sub_array[] = $productName;
        $sub_array[] = $row["suppliername"];
        $sub_array[] = $row["branchName"];
        $sub_array[] = $row["invoicedate"];
        $sub_array[] = $row["maintenancedate"];
        $sub_array[] = $row['employeename']; 
        if($row["maintorguar"] == 1){  
        $sub_array[] = ' <input id="maintenancecenterid'.$row["id"].'" type="text" name="maintenancecenters"  class="getselectjoin2 maintenancecenterid'.$row["id"].'"  data-placeholder=" المراكز    "   data-table="maintenancecenters" data-tableid="id"  data-join=""   data-filter="" data-parent="" data-itr="'.$row["id"].'"  data-search="centername"/>
            <input  type="hidden" name="maintenancecenterid" class="selectedit2" data-itr="'.$row["id"].'" data-join="" data-table="maintenancecenters" data-tableid="id" data-tableidname="maintenancecenterid" data-search="centername" value="'.$row["maintenancecenterid"].'" /><br>
            <button type="button" class="btn btn-primary adddatamodal" data-table="maintenancecenters" data-tableid="maintenancecenterid" data-toggle="modal" data-target="#Modalmaintenancecenterid" data-whatever="@maintenancecenters" data-formt="formmaintenancecenters" data-selectitr="'.$row["id"].'"> A</button>
            <button type="button" class="btn btn-primary editdatamodal"  data-model="#Modalmaintenancecenterid" data-table="maintenancecenters" data-name="maintenancecenterid" data-tableid="id" data-join="" data-formt="formmaintenancecenters" data-selectitr="'.$row["id"].'">E</button>'; 
        }else{
             $sub_array[] = 'ضمان'; 
        }
        $sub_array[] = ' <input  id="maintenancecommentid'.$row["id"].'"   type="text" class="form-control maintenancecomments" value="'.$comments->comments.'" data-id="'.$comments->id.'" data-maintenanceid="'.$row["id"].'"  />
            <button type="button" class="btn btn-primary adddatamodal" data-table="maintenancecomments" data-tableid="maintenancecommentid" data-toggle="modal" data-target="#Modalmaintenancecommentid" data-whatever="@maintenancecomments" data-formt="formmaintenancecomments" data-selectitr="'.$row["id"].'"> A</button>
          
             ';  
        if($row["conditions"] == 0){  
        $sub_array[] = '<a href="maintenances.php?do=edit&id='. $row["id"] .'&del=0" type="button" class="btn btn-default btn-lg editicon"></a>';
         $sub_array[] = '<a href="javascript:;" data-id="'. $row["id"] .'" data-tableid="id" data-table="maintenances" type="button" class="btn btn-default btn-lg deleteicon removeteble"  ></a>';
        }else{
          $sub_array[] = '<a href="maintenances.php?do=edit&id='. $row["id"] .'&del=1" type="button" class="btn btn-default btn-lm ">تفاصيل</a>';
          $sub_array[] = 'محذوف ';
        }
       
        $output['data'][] = $sub_array;
       }
    
       echo json_encode($output, JSON_UNESCAPED_SLASHES);

}


function changecase() {
    $id = filter_input(INPUT_POST, 'myid');
    $maintenancecaseid = filter_input(INPUT_POST, 'maintenancecaseid');
    $tables = R::load('maintenances',$id);
    $tables->maintenancecaseid = $maintenancecaseid;
    try {
        R::store($tables);
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }
}


function changecenter() {
    $id = filter_input(INPUT_POST, 'id');
    $maintenancecenterid = filter_input(INPUT_POST, 'maintenancecenterid');
    $tables = R::load('maintenances',$id);
    $tables->maintenancecenterid = $maintenancecenterid;
    try {
        R::store($tables);
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }
}

function updatecomment() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $id = filter_input(INPUT_POST, 'myid');
    $values = filter_input(INPUT_POST, 'values');
    $maintenanceid = filter_input(INPUT_POST, 'maintenanceid');
    $tables = R::load('maintenancecomments',$id);
    $tables->comments = $values;
    $tables->conditions = 0;
    $tables->maintenanceid = $maintenanceid;
    $tables->maintenancecommentdate = $today;  
    $tables->userid = $userid;
    try {
        R::store($tables);
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }
}





?>