<?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");
$smarty->assign('username', $_SESSION['username']);
if (empty($do)) {    
    $smarty->display("header.html");
    $smarty->display("maintenancereceiptview/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("maintenancereceiptview/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');
    $maintenancepolicydata = R::load('maintenancepolicys',$id);
    $smarty->assign('maintenancepolicydata', $maintenancepolicydata);
   $maintenances = R::getAll('SELECT maintenances.* ,suppliername FROM `maintenances` 
        LEFT JOIN supplier ON maintenances.supplierid = supplier.supplierid 
        WHERE maintenances.maintenancecaseid > 2 and maintenances.conditions = 0 and maintenances.maintenancepolicyid =  '.$id.' ');
    $maintenances = json_decode(json_encode($maintenances), FALSE);
    foreach($maintenances as $maintenance){
        $products = R::getAll("SELECT productName FROM product  WHERE productId in (".$maintenance->productid.")");
            $productName = '';
            foreach($products as $product){
                  $productName .= $product['productName']. ' / ';
            }
            $maintenance->productName = $productName;
    }   
    $smarty->assign('maintenances', $maintenances);
    $smarty->assign('del', $del);
    $smarty->display("header.html");
    $smarty->display("maintenancereceiptview/edit.html");
    $smarty->assign("maintenance", 1);
    $smarty->display("footer.html");
}else if ($do == 'savedata') {
  savedata();
}else if ($do == 'showajax') {
  showajax();
}else if($do == 'savecompany') {
  savecompany();
}else if($do == 'changecondition') {
  changecondition();
}else if($do == 'maintenancepolicyget') {
$maintenancepolicyid = filter_input(INPUT_POST, 'maintenancepolicyid');
 $maintenances = R::getAll('SELECT maintenances.* ,suppliername FROM `maintenances` 
        LEFT JOIN supplier ON maintenances.supplierid = supplier.supplierid 
        WHERE maintenances.maintenancecaseid = 2 and maintenances.conditions = 0 and maintenances.maintenancepolicyid =  '.$maintenancepolicyid.' '); 
    $maintenances = json_decode(json_encode($maintenances), FALSE);
    foreach($maintenances as $maintenance){
        $products = R::getAll("SELECT productName FROM product  WHERE productId in (".$maintenance->productid.")");
            $productName = '';
            foreach($products as $product){
                  $productName .= $product['productName']. ' / ';
            }
            $maintenance->productName = $productName;
    }  
    $smarty->assign('maintenances', $maintenances);
$smarty->display("maintenancereceiptview/get.html");  
}else if($do == 'saveprocedure') {
  saveprocedure(); 
}




function saveprocedure() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $procedurename = filter_input(INPUT_POST, 'procedurename');
    $maintenanceprocedureid = filter_input(INPUT_POST, 'maintenanceprocedureid');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    try {
        if (!$maintenanceprocedureid) {
            $maintenanceprocedures = R::dispense('maintenanceprocedures');
            $maintenanceprocedures->maintenanceproceduredate = $today;  
            $maintenanceprocedures->conditions = 0;
            $maintenanceprocedures->userid = $userid;
        }else{
            $maintenanceprocedures = R::load('maintenanceprocedures',$maintenanceprocedureid);
            $maintenanceprocedures->euserid = $userid;
        }
            $maintenanceprocedures->procedurename = $procedurename;          
            $maintenanceprocedureid = R::store($maintenanceprocedures);
        $selectiditr = 'maintenanceprocedureid'.$selectitr;
        echo json_encode(array('id' => $maintenanceprocedureid,'selectname' => 'maintenanceprocedureid','selectid' => $selectiditr,'text' => $procedurename ,'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'];
    $policydate = filter_input(INPUT_POST, 'policydate');
    $policynumber = filter_input(INPUT_POST, 'policynumber');
    $policystatement = filter_input(INPUT_POST, 'policystatement');
    $shippingvalue = filter_input(INPUT_POST, 'shippingvalue');
    $maintenancepolicyid = filter_input(INPUT_POST, 'maintenancepolicys');
    $bmaintenancecompanieid = filter_input(INPUT_POST, 'maintenancecompanies');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    $maintenanceitr  = filter_input(INPUT_POST, 'maintenanceitr');
    try {
            $maintenancepolicys = R::load('maintenancepolicys',$maintenancepolicyid);
            $maintenancepolicys->sendorreceipt = 2;
            $maintenancepolicys->bmaintenancepolicydate = $today;  
            $maintenancepolicys->buserid = $userid;
            $maintenancepolicys->bpolicydate = $policydate;          
            $maintenancepolicys->bpolicynumber = $policynumber;
            $maintenancepolicys->bpolicystatement = $policystatement;   
            $maintenancepolicys->bmaintenancecompanieid = $bmaintenancecompanieid;       
            $maintenancepolicys->bshippingvalue = $shippingvalue;
            $maintenancepolicyid = R::store($maintenancepolicys);

            R::exec("UPDATE `maintenances` SET `bshipprice`= ' ', `bshipcharge`= ' ' ,  `sendorreceipt`= 1, maintenancecaseid = 2, maintenancepolicyid = 0 WHERE conditions = 0 and maintenancepolicyid = $maintenancepolicyid");
             for ($i = 1; $i <= $maintenanceitr; $i++) {
                $maintenanceid = filter_input(INPUT_POST, 'maintenanceid_' . $i);
                $bshipprice = filter_input(INPUT_POST, 'bshipprice_' . $i);
                $bshipcharge = filter_input(INPUT_POST, 'bshipcharge_' . $i);
                $factoringnumber = filter_input(INPUT_POST, 'factoringnumber_' . $i);
                $maintenanceprice = filter_input(INPUT_POST, 'maintenanceprice_' . $i);
                $maintenancecost = filter_input(INPUT_POST, 'maintenancecost_' . $i);
                $statementprocedure = filter_input(INPUT_POST, 'statementprocedure_' . $i);
                $maintenanceprocedureid = filter_input(INPUT_POST, 'maintenanceprocedures_' . $i);
                if (!$maintenanceid) {
                    continue;
                }
                $maintenances = R::load('maintenances',$maintenanceid);
                $maintenances->bshipprice =  $bshipprice;  
                $maintenances->bshipcharge = $bshipcharge;  
                $maintenances->factoringnumber = $factoringnumber;  
                $maintenances->maintenanceprice = $maintenanceprice;  
                $maintenances->maintenancecost = $maintenancecost;  
                $maintenances->statementprocedure = $statementprocedure;  
                $maintenances->maintenanceprocedureid = $maintenanceprocedureid; 
                $maintenances->totalcost = $maintenances->bshipcharge + $maintenances->shipcharge + $maintenances->maintenancecost;
                $maintenances->requiredcustomer =  $maintenances->totalcost - $maintenances->prepaid;         
                $maintenances->paidlater =  0;      
                $maintenances->paidall =  $maintenances->paidlater + $maintenances->prepaid;      
                $maintenances->residual = $maintenances->totalcost - $maintenances->prepaid;         
                $maintenances->maintenancecaseid = 3;
                $maintenances->maintenancepolicyid = $maintenancepolicyid;  
                R::store($maintenances);

            }

           
        

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


function showajax() {
    $columns = array('maintenancepolicys.id', 'bpolicydate', 'bpolicynumber', 'suppliername', 'companyname', 'bshippingvalue', 'bmaintenancepolicydate', '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 maintenancepolicys.supplierid = ".$data1. " ";
    }

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

    if($data3 != ''){
       $searchQuery .= " and maintenancepolicys.id = ".$data3. " ";
    }

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


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( maintenancepolicys.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR bpolicydate LIKE "%'.$_POST["search"]["value"].'%"
                    OR bpolicynumber LIKE "%'.$_POST["search"]["value"].'%"
                    OR suppliername LIKE "%'.$_POST["search"]["value"].'%"
                    OR companyname LIKE "%'.$_POST["search"]["value"].'%"
                    OR bshippingvalue 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  maintenancepolicys.id DESC ";
    }
    
     $totals = R::count('maintenancepolicys','LEFT JOIN user ON maintenancepolicys.userid = user.userid 
        LEFT JOIN supplier ON maintenancepolicys.supplierid = supplier.supplierid
        LEFT JOIN maintenancecompanies ON maintenancepolicys.maintenancecompanieid = maintenancecompanies.id  
          WHERE 1 '.$searchQuery.' ');
    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    $rResult = R::getAll('SELECT maintenancepolicys.* ,employeename ,suppliername , companyname FROM `maintenancepolicys` 
        LEFT JOIN user ON maintenancepolicys.buserid = user.userid 
        LEFT JOIN supplier ON maintenancepolicys.supplierid = supplier.supplierid
        LEFT JOIN maintenancecompanies ON maintenancepolicys.maintenancecompanieid = maintenancecompanies.id  
          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[] = '<label class="mt-checkbox mt-checkbox-single mt-checkbox-outline">
                            <input type="checkbox" class="checkboxes" value="' . $row["id"] . '" />
                            <span></span>
                        </label>';
        $sub_array[] = $row["bpolicydate"];
        $sub_array[] = $row["bpolicynumber"];
        $sub_array[] = $row["suppliername"];
        $sub_array[] = $row["companyname"];
        $sub_array[] = $row["bshippingvalue"];
        $sub_array[] = $row["bmaintenancepolicydate"];
        $sub_array[] = $row['employeename']; 
        if($row["conditions"] == 0  && $row["sendorreceipt"] == 2){  
        $sub_array[] = '<a href="maintenancereceipts.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="maintenancepolicys" type="button" class="btn btn-default btn-lg deleteicon removeteble"  ></a>';
        }else{
          $sub_array[] = '<a href="maintenancereceipts.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 changecondition() {
    $id = filter_input(INPUT_POST, 'myid');
    $maintenanceid = filter_input(INPUT_POST, 'maintenanceid');
    $conditions = filter_input(INPUT_POST, 'conditions');
    $maintenanceconects = R::load('maintenanceconects',$id);
    $maintenanceconects->conditions = $conditions;
    try {
        R::store($maintenanceconects);
        if ($conditions == 1) {
            $maintenanceconects->maintenancepolicyid = 0;
            $id = 0;
        }
        $maintenances = R::load('maintenances',$maintenanceid);
        $maintenances->maintenancepolicyid = $maintenanceconects->maintenancepolicyid;  
        $maintenances->maintenanceconectid = $id;  
        R::store($maintenances);
        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
}

?>