<?php
include("../public/impOpreation.php");
$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("realestateunitsview/add.html");
    $smarty->assign("realestateunits", 1);
    $smarty->display("footer.html");
} else if ($do == "addappend") { 
    $itr = filter_input(INPUT_POST, 'itr');  
    $dataitr = filter_input(INPUT_POST, 'dataitr'); 
    $container = filter_input(INPUT_POST, 'container');  
    $smarty->assign('itr', $itr);
    $smarty->assign('dataitr', $dataitr);
    $smarty->assign('realestateunits', 1);
    $smarty->display("realestateunitsview/".$container.".html");  
} elseif ($do == "show") {
    $smarty->display("header.html");
    $smarty->display("realestateunitsview/show.html");
    $smarty->assign("realestateunits", 1);
    $smarty->display("footer.html");
} elseif ($do == "edit") {
    $id = filter_input(INPUT_GET, 'id');
    $editdata = R::load('realestates', $id);
    $smarty->assign('editdata', $editdata);
    $realestatesunits = R::findAll('realestatesunits','realestateid = ? and del < 2',[$id]);
    $smarty->assign('realestatesunits', $realestatesunits);
    $smarty->display("header.html");
    $smarty->display("realestateunitsview/edit.html");
    $smarty->assign("realestateunits", 1);
    $smarty->display("footer.html");
}else if ($do == 'savedata') {
  savedata();
}else if ($do == 'showajax') {
  showajax();
}else if ($do == 'removecontroller') {
  removecontroller();
}else if ($do == 'select2client') {
  select2client();   
}else if ($do == 'select2supplier') {
  select2supplier();       
}else if ($do == 'select2realestates') {
  select2realestates();
}else if ($do == 'select2realestatesunits') {
  select2realestatesunits();
}else if ($do == 'getexpenstype') {
  getexpenstype();
}


function select2supplier() {
    $name = $_POST['searchTerm'];
    $productsData = R::getAll("SELECT supplierid, CONCAT(suppliername,'/',supplierphone) as texts
    FROM supplier WHERE conditions = 0 and CONCAT(suppliername,'/',supplierphone) LIKE '%" . $name . "%' limit 50");
    $return_arr = array();
    foreach ($productsData as $pro) {
        $row_array = array();
        $row_array['id'] = $pro['supplierid'];
        $row_array['text'] = $pro['texts'];
        array_push($return_arr, $row_array);
    }
    echo json_encode($return_arr);
}


function select2client() {
    $name = $_POST['searchTerm'];
    $productsData = R::getAll("SELECT clientid, CONCAT(clientname,'/',clientphone) as texts
    FROM client WHERE conditions = 0 and CONCAT(clientname,'/',clientphone) LIKE '%" . $name . "%' limit 50");
    $return_arr = array();
    foreach ($productsData as $pro) {
        $row_array = array();
        $row_array['id'] = $pro['clientid'];
        $row_array['text'] = $pro['texts'];
        array_push($return_arr, $row_array);
    }
    echo json_encode($return_arr);
}



function select2realestates() {   
    $name = $_POST['searchTerm'];
    $productsData = R::getAll("SELECT id, realestatename
    FROM realestates 
    WHERE del < 2 and realestatename LIKE '%" . $name . "%'  limit 50");
    $return_arr = array();
    foreach ($productsData as $pro) {
        $row_array = array();
        $row_array['id'] = $pro['id'];
        $row_array['text'] = $pro['realestatename'];
        array_push($return_arr, $row_array);
    }

    echo json_encode($return_arr);
}

function select2realestatesunits() {
    
    $name = $_POST['searchTerm'];
    $realestateid = $_POST['realestateid'];
    $productsData = R::getAll("SELECT id, CONCAT(unitname,'/',unitarea) as texts
    FROM realestatesunits 
    WHERE del < 2 and CONCAT(unitname,'/',unitarea) LIKE '%" . $name . "%' and  realestatesunits.realestateid = $realestateid limit 50");
    $return_arr = array();
    foreach ($productsData as $pro) {
        $row_array = array();
        $row_array['id'] = $pro['id'];
        $row_array['text'] = $pro['texts'];
        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'];
    $realestatename = filter_input(INPUT_POST, 'realestatename');
    $realestatesunitsitr = filter_input(INPUT_POST, 'realestatesunitsitr');
    $id = filter_input(INPUT_POST, 'id');


    if (!$id) {
        $realestates = R::dispense('realestates');
        $realestates->del = 0;
        $realestates->addtoday = $today;          
        $realestates->adduserid = $userid;
        $realestates->savaible = 0;
        $realestates->cavaible = 0;
        $realestates->incometypeid = 0;
        $realestates->expenstypeid = 0;
        $realestates->deltoday = '';      
        $realestates->deluserid = '';
    }else{
        $realestates = R::load('realestates',$id);
        $realestates->del = 1;
        $realestates->updatetoday = $today;          
        $realestates->updateuserid = $userid; 
        R::exec("UPDATE `incometype` SET `incomeTypeName`='$realestatename', `incomeTypeDetails`='$realestatename' WHERE incomeTypeId = $realestates->incometypeid");
        R::exec("UPDATE `expensestype` SET `expensestypename`='$realestatename', `expensestypedetails`='$realestatename' WHERE expensestypeid = $realestates->expenstypeid");
    }
    $realestates->realestatename  = $realestatename;
    try {
         $realestateid = R::store($realestates);
          for ($i = 1; $i <= $realestatesunitsitr; $i++) {
            $unitname = filter_input(INPUT_POST, 'unitname_' . $i);
            $unitarea = filter_input(INPUT_POST, 'unitarea_' . $i);
            $unitid = filter_input(INPUT_POST, 'unitid_' . $i);   
            if (!$unitname) {continue;}         
            if (!$unitid) {
                $realestatesunits = R::dispense('realestatesunits');
                $realestatesunits->del = 0;
                $realestatesunits->addtoday = $today;  
                $realestatesunits->adduserid = $userid;
                $realestatesunits->deltoday = '';  
                $realestatesunits->deluserid = '';

            }else{
                $realestatesunits = R::load('realestatesunits',$unitid); 
                $realestatesunits->del = 1;
                $realestatesunits->updatetoday = $today;          
                $realestatesunits->updateuserid = $userid;

            }
           
            $realestatesunits->realestateid = $realestateid;  
            $realestatesunits->unitname = $unitname;
            $realestatesunits->unitarea = $unitarea;
            $realestatesunits->cavaible = 0;
            R::store($realestatesunits);
        }  
        if (!$id) {
           incomeexpenstype($realestateid, $realestatename);
        } 
        echo $realestateid;
    } catch (Exception $e) {
        echo 0 ;
    }
}

function incomeexpenstype($realestateid, $realestatename) {
    $send_data = array('parent' =>  0, 'name' => $realestatename, 'defaultValue' => 0, 
        'descripe' =>  $realestatename, 'curlpost' => 1);
    $incometypeid = CURL_IT2($send_data, 'incomeTypeController.php?do=add');
    if ($incometypeid > 0) {
         R::exec("UPDATE `realestates` SET `incometypeid`= $incometypeid WHERE id = '" . $realestateid . "' ");
    }
    $send_data = array('parent' =>  0, 'treeType' => 0, 'name' => $realestatename, 'type' =>  0, 'saveid' =>  0, 'defaultValue' => 0, 
        'descripe' =>  $realestatename, 'curlpost' => 1);
    $expenstypeid = CURL_IT2($send_data, 'expensesTypeController.php?do=add');
    if ($expenstypeid > 0) {
         R::exec("UPDATE `realestates` SET `expenstypeid`= $expenstypeid WHERE id = '" . $realestateid . "' ");
    }

}

function getexpenstype() {
     $id = filter_input(INPUT_POST, 'id');
    $realestates = R::load('realestates',$id);
    echo $realestates->expenstypeid;

}


function showajax() {
    $columns = array('realestates.id', 'realestatename', '', 'realestates.addtoday', 'employeename', 'realestates.id', 'realestates.id');
    $start_date = filter_input(INPUT_POST, 'start_date');
    $end_date = filter_input(INPUT_POST, 'end_date');
    $del = filter_input(INPUT_POST, 'del');
    $realestateid = filter_input(INPUT_POST, 'realestateid');
    $realestateunitid = filter_input(INPUT_POST, 'realestateunitid');
    $savaible = filter_input(INPUT_POST, 'savaible');
    $cavaible = filter_input(INPUT_POST, 'cavaible');

    $searchQuery = " ";
    $searchjoin = " ";
    if($realestateid != ''){
      $searchQuery .=  " and realestates.id = ".$realestateid. " ";
    }
    if($del == ''){
       $searchQuery .= " and realestates.del < 2 "; 
    }

    if ($savaible) {
        $searchQuery .=  " and realestates.savaible = ".$savaible. " ";
    }

    if ($cavaible) {
       $searchQuery .=  " and realestates.cavaible = ".$cavaible. " ";
    }

    if($realestateunitid != ''){
       $searchQuery .= " and realestatesunits.id = ".$realestateunitid. " ";
       $searchjoin .= "  LEFT JOIN realestatesunits ON realestates.id = realestatesunits.realestateid  ";
    }
    
    if($start_date != '' && $end_date != ''){
       $searchQuery .=' and  realestates.addtoday  >= "' . $start_date . ' 00-00-00" and realestates.addtoday <= "' . $end_date . ' 23-59-55" ';
    }


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( realestates.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR realestates.realestatename LIKE "%'.$_POST["search"]["value"].'%"
                    OR realestates.addtoday 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  realestates.id DESC ";
    }
   
   
    $totals = R::count('realestates','LEFT JOIN user ON realestates.adduserid = user.userid 
        '.$searchjoin.' WHERE 1 '.$searchQuery.' ');
    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    $rResult = R::getAll('SELECT realestates.* ,employeename   FROM `realestates` LEFT JOIN user
         ON realestates.adduserid = user.userid '.$searchjoin.'  WHERE 1 '.$searchQuery.' ');   
     
    $output = array(  
        "draw" => intval($_POST["draw"]),
        "recordsTotal" => count($rResult),
        "recordsFiltered" => $totals,
        "data" => array()
    );
  
   foreach ($rResult as $row) {
     $realestatesunits = R::findAll('realestatesunits',"realestateid = ? and del < 2 ",[$row['id']]);
     $allunits = '';
     foreach($realestatesunits as $units){
           $allunits .= $units->unitname . ' / ';
     }
    $sub_array = array();
    $sub_array[] = $row["id"];
    $sub_array[] = $row["realestatename"] ;
    $sub_array[] = $allunits;
    $sub_array[] = $row["addtoday"];
    $sub_array[] = $row['employeename'] ;  
    if($row["del"] < 2){  
    $sub_array[] = '<a href="realestateunits.php?do=edit&id='. $row["id"] .'" type="button" class="btn btn-default btn-lg editicon"></a>';
     $sub_array[] = '<a href="javascript:;" data-id="'. $row["id"] .'" data-controll="realestateunits" type="button" class="btn btn-default btn-lg deleteicon removecontroller"  ></a>';
    }else{
      $sub_array[] = '<a href="realestateunits.php?do=edit&id='. $row["id"] .'" type="button" class="btn btn-default btn-lm ">تفاصيل</a>';
      $sub_array[] = 'محذوف ';
    }
   
    $output['data'][] = $sub_array;
   }
   echo json_encode($output, JSON_UNESCAPED_SLASHES);

}

function removecontroller() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $id = filter_input(INPUT_POST, 'id');
    $tables = R::load('realestates',$id);
    $tables->del = 2;
    $tables->deltoday = $today;
    $tables->deluserid = $userid;     
    try {
        R::store($tables);
        R::exec("UPDATE `realestatesunits` SET `del`= 3 WHERE realestateid = '" . $id . "' ");
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }
}

function removeappend() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $id = filter_input(INPUT_POST, 'id');
    $table = filter_input(INPUT_POST, 'container');
    $tables = R::load($table,$id);
    $tables->del = 2;
    $tables->deltoday = $today;
    $tables->deluserid = $userid;    
    try {
        R::store($tables);
        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
}



function CURL_IT2($data_arr = array(), $url) {
    $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $url;
    ##appending necessary data
    $data_arr['curlpost'] = '1';
    $data_arr['sessionlist'] = json_encode($_SESSION);

    $post = $data_arr;
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        //echo 'Error : ' . curl_error($ch);
    }

    curl_close($ch);
    return $response;
}

?>