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

//user
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("maintenancesupplierview/add.html");
    $smarty->assign("maintenance", 1);
    $smarty->display("footer.html");
} elseif ($do == "show")f{
    include_once("../public/authentication.php");
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->display("header.html");
    $smarty->display("maintenancesupplierview/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');
    $supplierdata = R::getRow('SELECT supplier.* FROM `supplier` WHERE supplierid = ?',[$id]);
    $smarty->assign('supplierdata', $supplierdata);
    $smarty->assign('del', $del);
    $smarty->display("header.html");
    $smarty->display("maintenancesupplierview/edit.html");
    $smarty->assign("maintenance", 1);
    $smarty->display("footer.html");
}else if ($do == 'savedata') {
  savedata();
}else if ($do == 'showajax') {
  showajax();
}else if ($do == 'savegoverarea') {
  savegoverarea();
}else if ($do == 'getgoverarea') {
    getgoverarea();
}


function getgoverarea() {
    $searchterm = $_POST['searchTerms']; 
    
    $allData = R::getAll("SELECT goverarea.goverareaid as id,CONCAT(government.governmentname, ' - ', clientarea.name) as name FROM goverarea 
    LEFT JOIN government ON goverarea.governmentid = government.governmetid
        LEFT JOIN clientarea ON goverarea.clientareaid = clientarea.id WHERE  
        CONCAT(government.governmentname, ' - ', clientarea.name) LIKE '%" . $searchterm . "%' $search limit 50");
    $return_arr = [];
    foreach ($allData as $data) {
        $row_array = [];
        $row_array['id'] = $data['id'];
        $row_array['text'] = $data['name'];
        array_push($return_arr, $row_array);
    }
    
    echo json_encode($return_arr);

}


function savedata() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $suppliername = filter_input(INPUT_POST, 'suppliername');
    $supplieraddress = filter_input(INPUT_POST, 'supplieraddress');
    $supplierphone = filter_input(INPUT_POST, 'supplierphone');
    $clientaddress = filter_input(INPUT_POST, 'clientaddress');
    $suppliercode = filter_input(INPUT_POST, 'suppliercode');
    $goverareaid = filter_input(INPUT_POST, 'goverarea');
    $namepayeecheck = filter_input(INPUT_POST, 'namepayeecheck');
    $suppliermobile = filter_input(INPUT_POST, 'suppliermobile');
    $warrantyOfficer = filter_input(INPUT_POST, 'warrantyOfficer');
    $warrantymobile = filter_input(INPUT_POST, 'warrantymobile');
    $sellername = filter_input(INPUT_POST, 'sellername');
    $sellermobile = filter_input(INPUT_POST, 'sellermobile');
    $supplierid = filter_input(INPUT_POST, 'supplierid');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    try {
        if (!$supplierid) {
             R::exec("INSERT INTO `supplier`(`suppliername`, `supplieraddress`, `supplierphone`, `conditions`, `userid`, `supplierdate`, `suppliercode`, `goverareaid`, `namepayeecheck`, `suppliermobile`, `warrantyOfficer`, `warrantymobile`, `sellername`, `sellermobile`) VALUES ('$suppliername','$supplieraddress','$supplierphone', 0 ,'$userid','$date','$suppliercode','$goverareaid','$namepayeecheck','$suppliermobile','$warrantyOfficer','$warrantymobile','$sellername','$sellermobile')");
            $last =R::getROW("SELECT supplierid, suppliername FROM `supplier` order by supplierid desc");
            $supplierid = $last['supplierid'];
            $text = $last['suppliername'];
        }else{
           R::exec("UPDATE `supplier` SET `suppliername`='$suppliername',`supplieraddress`='$supplieraddress',`supplierphone`='$supplierphone',`userid`= $userid ,`suppliercode`= '$suppliercode',`goverareaid`= '$goverareaid',`namepayeecheck`= '$namepayeecheck',`suppliermobile`= '$suppliermobile',`warrantyOfficer`= '$warrantyOfficer',`warrantymobile`= '$warrantymobile',`sellername`= '$sellername',`sellermobile`= '$sellermobile' WHERE supplierid = $supplierid");
            $text = $suppliername;
        }
        $selectiditr = 'supplierid'.$selectitr;
        echo json_encode(array('id' => $supplierid,'selectname' => 'supplierid','selectid' => $selectiditr,'text' => $text
            ,'selectid' => $selectiditr,'selectitr' => $selectitr));
    } catch (Exception $e) {
        echo 0 ;
    }
}


function savegoverarea() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $governmentid = filter_input(INPUT_POST, 'governmentid');
    $governmentname = filter_input(INPUT_POST, 'governmentname');
    $areaname = filter_input(INPUT_POST, 'name');
    $goverareaid = filter_input(INPUT_POST, 'goverareaid');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    try {
        if (!$goverareaid) {
            if($governmentid){
                $getgovernment = R::getRow('SELECT government.* FROM `government` WHERE governmetid = ? ', [$governmentid]);
                
            }else{
                 R::exec("INSERT INTO `government`(`governmentname`) VALUES ('$governmentname')");
                 $getgovernment =R::getROW("SELECT * FROM `government` order by governmetid desc");
            }
           $governmetid =  $getgovernment['governmetid'];
            R::exec("INSERT INTO `clientarea`(`name`) VALUES ('$areaname')");
            $clientarealast = R::getROW("SELECT * FROM `clientarea` order by id desc");
            $clientareaid = $clientarealast["id"];
            R::exec("INSERT INTO `goverarea`(`governmentid`, `clientareaid`) VALUES ($governmetid, $clientareaid)");
            $last = R::getROW("SELECT * FROM `goverarea` order by goverareaid desc");          
          $goverareaid = $last['goverareaid'];
          $text = $getgovernment['governmentname'].'/'.$clientarealast['name'];
        }else{
            $getgoverarea = R::getRow('SELECT * FROM `goverarea` WHERE goverareaid = ? ', [$goverareaid]);
            $governmetid = $getgoverarea['governmentid'];
            $clientareaid = $getgoverarea['clientareaid'];
            R::exec("UPDATE `government` SET  `governmentname`='$governmentname' WHERE governmetid = $governmetid");
            R::exec("UPDATE `clientarea` SET  `name`='$areaname' WHERE id = $clientareaid");
            $text = $governmentname.'/'.$areaname;

          
        }

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


function showajax() {
    $columns = array('supplierid', 'suppliername', 'supplierphone', 'suppliermobile', 'supplierdate', 'governmentarea', 'employeename', 'supplierid', 'supplierid');
    $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 supplier.supplierid = ".$data1. " ";
    }
    if($del == ''){
       $searchQuery .= " and supplier.conditions = 0 "; 
    }

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


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( supplier.supplierid LIKE "%'.$_POST["search"]["value"].'%" 
                    OR supplier.suppliername LIKE "%'.$_POST["search"]["value"].'%"
                    OR supplier.supplierphone LIKE "%'.$_POST["search"]["value"].'%"
                    OR supplier.suppliermobile LIKE "%'.$_POST["search"]["value"].'%"
                    OR supplier.supplierdate LIKE "%'.$_POST["search"]["value"].'%"
                    OR governmentarea 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  supplier.supplierid DESC ";
    }
    
     $totals = R::count('supplier','LEFT JOIN user ON supplier.userid = user.userid 
        LEFT JOIN goverarea ON supplier.goverareaid = goverarea.goverareaid 
        LEFT JOIN government ON goverarea.governmentid = government.governmetid
        LEFT JOIN clientarea ON goverarea.clientareaid = clientarea.id
        WHERE 1 '.$searchQuery.' ');
    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    $rResult = R::getAll("SELECT supplier.* ,employeename ,CONCAT(governmentname,'/',clientarea.name) as governmentarea  FROM `supplier` 
        LEFT JOIN user ON supplier.userid = user.userid 
        LEFT JOIN goverarea ON supplier.goverareaid = goverarea.goverareaid 
        LEFT JOIN government ON goverarea.governmentid = government.governmetid
        LEFT JOIN clientarea ON goverarea.clientareaid = clientarea.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[] = $row["supplierid"];
        $sub_array[] = $row["suppliername"];
        $sub_array[] = $row["supplierphone"];
        $sub_array[] = $row["suppliermobile"];
        $sub_array[] = $row["supplierdate"];
        $sub_array[] = $row["governmentarea"];
        $sub_array[] = $row['employeename'] ;  
        if($row["conditions"] == 0){  
        $sub_array[] = '<a href="maintenancesuppliers.php?do=edit&id='. $row["supplierid"] .'&del=0" type="button" class="btn btn-default btn-lg editicon"></a>';
         $sub_array[] = '<a href="javascript:;" data-id="'. $row["supplierid"] .'" data-table="supplier"  data-tableid="supplierid" type="button" class="btn btn-default btn-lg deleteicon removeteble"  ></a>';
        }else{
          $sub_array[] = '<a href="maintenancesuppliers.php?do=edit&id='. $row["supplierid"] .'&del=1" type="button" class="btn btn-default btn-lm ">تفاصيل</a>';
          $sub_array[] = 'محذوف ';
        }
       
        $output['data'][] = $sub_array;
       }
    
       echo json_encode($output, JSON_UNESCAPED_SLASHES);

}






?>