<?php
include("../public/impOpreation.php");
include("../library/uploadImages.php");

$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->assign('maintenances', $maintenances);
    $smarty->display("header.html");
    $smarty->display("maintenancesendview/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("maintenancesendview/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.maintorguar = 2 and maintenances.maintenancecaseid < 3 and maintenances.conditions = 0 and maintenances.supplierid =  '.$maintenancepolicydata->supplierid.' ');   
    $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("maintenancesendview/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 == 'getmaintenances') {
    $supplierid = filter_input(INPUT_POST, 'supplierid');
    $maintenances = R::getAll('SELECT maintenances.* ,suppliername FROM `maintenances`  LEFT JOIN supplier ON maintenances.supplierid = supplier.supplierid 
        WHERE maintenances.maintorguar = 2 and maintenances.maintenancecaseid = 1 and maintenances.conditions = 0 and maintenancepolicyid = 0 and maintenances.supplierid = '.$supplierid.' ');
    $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("maintenancesendview/get.html");   
}




function savecompany() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $companyname = filter_input(INPUT_POST, 'companyname');
    $companyphone = filter_input(INPUT_POST, 'companyphone');
    $companyaddress = filter_input(INPUT_POST, 'companyaddress');
    $maintenancecompanieid = filter_input(INPUT_POST, 'maintenancecompanieid');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    try {
        if (!$maintenancecompanieid) {
            $maintenancecompanies = R::dispense('maintenancecompanies');
            $maintenancecompanies->maintenancecompaniedate = $today;  
            $maintenancecompanies->conditions = 0;
            $maintenancecompanies->userid = $userid;
        }else{
            $maintenancecompanies = R::load('maintenancecompanies',$maintenancecompanieid);
            $maintenancecompanies->euserid = $userid;
        }
            $maintenancecompanies->companyname = $companyname;          
            $maintenancecompanies->companyphone = $companyphone;
            $maintenancecompanies->companyaddress = $companyaddress; 
            $maintenancecompanieid = R::store($maintenancecompanies);
        $selectiditr = 'maintenancecompanieid'.$selectitr;
        echo json_encode(array('id' => $maintenancecompanieid,'selectname' => 'maintenancecompanieid','selectid' => $selectiditr,'text' => $companyname.'/'.$companyphone ,'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');
    $supplierid = filter_input(INPUT_POST, 'supplier');
    $maintenancecompanieid = filter_input(INPUT_POST, 'maintenancecompanies');
    $policystatement = filter_input(INPUT_POST, 'policystatement');
    $shippingvalue = filter_input(INPUT_POST, 'shippingvalue');
    $maintenancepolicyid = filter_input(INPUT_POST, 'maintenancepolicyid');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    $maintenanceitr  = filter_input(INPUT_POST, 'maintenanceitr');
    try {
        if (!$maintenancepolicyid) {
            $maintenancepolicys = R::dispense('maintenancepolicys');
            $maintenancepolicys->maintenancepolicydate = $today;  
            $maintenancepolicys->conditions = 0;
            $maintenancepolicys->userid = $userid;
            $maintenancepolicys->sendorreceipt = 1;
        }else{
            $maintenancepolicys = R::load('maintenancepolicys',$maintenancepolicyid);
            $maintenancepolicys->euserid = $userid;
        }
            $maintenancepolicys->policydate = $policydate;          
            $maintenancepolicys->policynumber = $policynumber;
            $maintenancepolicys->supplierid = $supplierid;
            $maintenancepolicys->maintenancecompanieid = $maintenancecompanieid;
            $maintenancepolicys->policystatement = $policystatement;          
            $maintenancepolicys->shippingvalue = $shippingvalue;
            $maintenancepolicyid = R::store($maintenancepolicys);
            R::exec("UPDATE `maintenances` SET `shipprice`= ' ', `shipcharge`= ' ' ,  `shipnumber`= ' ', maintenancecaseid = 1, maintenancepolicyid = 0 WHERE conditions = 0 and maintenancepolicyid = $maintenancepolicyid");
             for ($i = 1; $i <= $maintenanceitr; $i++) {
                $maintenanceid = filter_input(INPUT_POST, 'maintenanceid_' . $i);
                $shipprice = filter_input(INPUT_POST, 'shipprice_' . $i);
                $shipcharge = filter_input(INPUT_POST, 'shipcharge_' . $i);
                $shipnumber = filter_input(INPUT_POST, 'shipnumber_' . $i);
                if (!$maintenanceid) {
                    continue;
                }
                $maintenances = R::load('maintenances',$maintenanceid);
                $maintenances->shipprice =  $shipprice;  
                $maintenances->shipcharge = $shipcharge;  
                $maintenances->shipnumber = $shipnumber;                  
                $maintenances->maintenancecaseid = 2;
                $maintenances->supplierid = $supplierid;
                $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', 'policydate', 'policynumber', 'suppliername', 'companyname', 'shippingvalue', 'maintenancepolicydate', '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.maintenancepolicydate  >= "' . $start_date . ' 00-00-00" and maintenancepolicys.maintenancepolicydate <= "' . $end_date . ' 23-59-55" ';
    }


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( maintenancepolicys.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR policydate LIKE "%'.$_POST["search"]["value"].'%"
                    OR policynumber LIKE "%'.$_POST["search"]["value"].'%"
                    OR suppliername LIKE "%'.$_POST["search"]["value"].'%"
                    OR companyname LIKE "%'.$_POST["search"]["value"].'%"
                    OR shippingvalue 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.userid = 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["policydate"];
        $sub_array[] = $row["policynumber"];
        $sub_array[] = $row["suppliername"];
        $sub_array[] = $row["companyname"];
        $sub_array[] = $row["shippingvalue"];
        $sub_array[] = $row["maintenancepolicydate"];
        $sub_array[] = $row['employeename']; 
        if($row["conditions"] == 0 && $row["sendorreceipt"] == 1){  
        $sub_array[] = '<a href="maintenancesends.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="maintenancesends.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() {
//     $maintenanceid = filter_input(INPUT_POST, 'maintenanceid');
//     $maintenancecaseid = filter_input(INPUT_POST, 'maintenancecaseid');
//     $maintenancepolicyid = filter_input(INPUT_POST, 'maintenancepolicyid');
//     $maintenances = R::load('maintenances',$maintenanceid);
//     try {
//         $maintenances->maintenancepolicyid = $maintenancepolicyid;  
//         $maintenances->maintenancecaseid   = $maintenancecaseid;  
//         R::store($maintenances);
//         echo 1;
//     } catch (Exception $e) {
//         echo 0 ;
//     }
// }

?>