<?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("realestateunitsownersview/add.html");
    $smarty->assign("realestateunits", 1);
    $smarty->display("footer.html");
} elseif ($do == "show") {
    $smarty->display("header.html");
    $smarty->display("realestateunitsownersview/show.html");
    $smarty->assign("realestateunits", 1);
    $smarty->display("footer.html");
} elseif ($do == "edit") {
    $id = filter_input(INPUT_GET, 'id');
    $editdata = R::load('realestateunitspaids', $id);
    $smarty->assign('editdata', $editdata);
    $realestate = R::load('realestates', $editdata->realestateid);
    $smarty->assign('realestate', $realestate);
    $supplier = R::getRow('select * from supplier WHERE supplierid = ? ', [$editdata->supplierid]);
    $smarty->assign('supplier', $supplier);
    $realestateunitpaidinstallments = R::findAll('realestateunitpaidinstallments','realestateunitpaidid = ? and del < 2',[$id]);
    $smarty->assign('realestateunitpaidinstallments', $realestateunitpaidinstallments);
    $smarty->display("header.html");
    $smarty->display("realestateunitsownersview/edit.html");
    $smarty->assign("realestateunits", 1);
    $smarty->display("footer.html");
}else if ($do == 'savedata') {
  savedata();
}else if ($do == 'showajax') {
  showajax();
}else if ($do == 'removeappend') {
   removeappend();  
}else if ($do == 'removecontroller') {
  removecontroller();
}else if ($do == 'savepayed') {
  savepayed();
}else if ($do == 'editid') {
  editid();
}


function savedata() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $supplierid = filter_input(INPUT_POST, 'supplierid');
    $realestateid = filter_input(INPUT_POST, 'realestateid');
    $valuerents = filter_input(INPUT_POST, 'valuerents');
    $advancepayment = filter_input(INPUT_POST, 'advancepayment');
    $totalpaid = filter_input(INPUT_POST, 'totalpaid');
    $numberinstallments = filter_input(INPUT_POST, 'numberinstallments');
    $id = filter_input(INPUT_POST, 'id');

    if (!$id) {
        $realestateunitspaids = R::dispense('realestateunitspaids');
        $realestateunitspaids->del = 0;
        $realestateunitspaids->addtoday = $today;          
        $realestateunitspaids->adduserid = $userid;
        $realestateunitspaids->deltoday = '';      
        $realestateunitspaids->deluserid = '';
        $realestateunitspaids->realestateunitpaidhistoryid = 0;
    }else{
        $realestateunitspaids = R::load('realestateunitspaids',$id);
        $realestateunitspaids->del = 1;
        $realestateunitspaids->updatetoday = $today;          
        $realestateunitspaids->updateuserid = $userid; 
        R::exec("UPDATE `realestates` SET `savaible`= 0 WHERE id = '" . $realestateunitspaids->realestateid . "' ");  
        if ($realestateunitspaids->advancepayment > 0) {
            $expense = R::getRow('select * from expenses WHERE expensesid = ? ', [$realestateunitspaids->expenseid]);
            CURL_IT2(array(),'expensesController.php?do=delete&id='.$realestateunitspaids->expenseid.'&dailyentry='.$expense['dailyentryid']);
            R::exec("UPDATE `realestateunitpaidhistory` SET `del`= 3 WHERE id = '" . $realestateunitspaids->realestateunitpaidhistoryid . "' ");  
        }
    }
    R::exec("UPDATE `realestates` SET `savaible`= 1 WHERE id = '" . $realestateid . "' ");  
    $realestateunitspaids->supplierid  = $supplierid;
    $realestateunitspaids->clientid  = 0;
    $realestateunitspaids->realestateid  = $realestateid;
    $realestateunitspaids->realestateunitid  = 0;
    $realestateunitspaids->valuerents  = $valuerents;
    $realestateunitspaids->advancepayment= $advancepayment;
    $realestateunitspaids->totalpaid = (int)$totalpaid;
    $realestateunitspaids->expenseid = 0;
    $realestateunitspaids->incomeid = 0;

    if ($realestateunitspaids->totalpaid == 0) {
       $realestateunitspaids->payed = 0;
    }else if($realestateunitspaids->valuerents > $realestateunitspaids->totalpaid) {
       $realestateunitspaids->payed = 1;   
    }else{
       $realestateunitspaids->payed = 2;
       R::exec("UPDATE `realestates` SET `savaible`= 0 WHERE id = '" . $realestateunitspaids->realestateid . "' ");  
    }
    $realestateunitspaids->numberinstallments  = $numberinstallments;
    try {
        $realestateunitpaidid = R::store($realestateunitspaids);
        if ($advancepayment > 0) {
            paieds($supplierid, $realestateid, $advancepayment, $realestateunitpaidid, 0);
        }
        for ($i = 1; $i <= $numberinstallments; $i++) {
            $valuerent = filter_input(INPUT_POST, 'valuerent_' . $i);
            $totalpaid = (int)filter_input(INPUT_POST, 'totalpaid_' . $i);
            $installmentdate = filter_input(INPUT_POST, 'installmentdate_' . $i);
            $realestateunitpaidinstallmentid = filter_input(INPUT_POST, 'realestateunitpaidinstallmentid_' . $i);
            if (!$valuerent) {continue;}         
            if (!$realestateunitpaidinstallmentid) {
                $realestateunitpaidinstallments = R::dispense('realestateunitpaidinstallments');
                $realestateunitpaidinstallments->del = 0;
                $realestateunitpaidinstallments->addtoday = $today;  
                $realestateunitpaidinstallments->adduserid = $userid;
                $realestateunitpaidinstallments->deltoday = '';  
                $realestateunitpaidinstallments->deluserid = '';
                $realestateunitpaidinstallments->expenseid = 0;
                $realestateunitpaidinstallments->incomeid = 0;
                $realestateunitpaidinstallments->realestateunitpaidhistoryid = 0;
            }else{
                $realestateunitpaidinstallments = R::load('realestateunitpaidinstallments',$realestateunitpaidinstallmentid); 
                $realestateunitpaidinstallments->del = 1;
                $realestateunitpaidinstallments->updatetoday = $today;          
                $realestateunitpaidinstallments->updateuserid = $userid;
                if ($realestateunitpaidinstallments->totalpaid > 0) {
                    $expense = R::getRow('select * from expenses WHERE expensesid = ? ', [$realestateunitpaidinstallments->expenseid]);
                    CURL_IT2(array(),'expensesController.php?do=delete&id='.$realestateunitpaidinstallments->expenseid.'&dailyentry='.$expense['dailyentryid']);
                    R::exec("UPDATE `realestateunitpaidhistory` SET `del`= 3 WHERE id = '" . $realestateunitpaidinstallments->realestateunitpaidhistoryid . "' "); 
                }

            }
            $realestateunitpaidinstallments->totalpaid = $totalpaid;
            $realestateunitpaidinstallments->realestateunitpaidid = $realestateunitpaidid;  
            $realestateunitpaidinstallments->supplierid = $supplierid;  
            $realestateunitpaidinstallments->clientid  = 0;
            $realestateunitpaidinstallments->realestateid = $realestateid;  
            $realestateunitpaidinstallments->realestateunitid  = 0;
            $realestateunitpaidinstallments->valuerent = $valuerent;
            $realestateunitpaidinstallments->installmentdate = $installmentdate;
            if ($realestateunitpaidinstallments->totalpaid == 0) {
               $realestateunitpaidinstallments->payed = 0;
            }else if($realestateunitpaidinstallments->valuerent > $realestateunitpaidinstallments->totalpaid) {
               $realestateunitpaidinstallments->payed = 1;   
            }else{
               $realestateunitpaidinstallments->payed = 2;


            }
            $realestateunitpaidinstallmentid = R::store($realestateunitpaidinstallments);
            if ($realestateunitpaidinstallments->totalpaid > 0) {
              paieds($supplierid, $realestateid, $realestateunitpaidinstallments->totalpaid, $realestateunitpaidid, $realestateunitpaidinstallmentid);
            }
        } 
        echo $realestateunitpaidid;
    } catch (Exception $e) {
        echo 0 ;
    }
}


function savepayed() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $realestateunitpaidid = filter_input(INPUT_POST, 'realestateunitpaidid');
    $realestateunitpaidinstallmentid = filter_input(INPUT_POST, 'realestateunitpaidinstallmentid');
    $payed = filter_input(INPUT_POST, 'payed');
    
    $realestateunitspaids = R::load('realestateunitspaids',$realestateunitpaidid);
    $realestateunitspaids->totalpaid = (int)$realestateunitspaids->totalpaid  +  (int)$payed;
    if ($realestateunitspaids->totalpaid == 0) {
       $realestateunitspaids->payed = 0;
    }else if($realestateunitspaids->valuerents > $realestateunitspaids->totalpaid) {
       $realestateunitspaids->payed = 1;   
    }else{
       $realestateunitspaids->payed = 2;
        R::exec("UPDATE `realestates` SET `savaible`= 0 WHERE id = '" . $realestateunitspaids->realestateid . "' ");  
    }
    try {
        $realestateunitpaidid = R::store($realestateunitspaids);
        $realestateunitpaidinstallments = R::load('realestateunitpaidinstallments',$realestateunitpaidinstallmentid); 
        $realestateunitpaidinstallments->totalpaid = (int)$realestateunitpaidinstallments->totalpaid + (int)$payed;
        if ($realestateunitpaidinstallments->totalpaid == 0) {
           $realestateunitpaidinstallments->payed = 0;
        }else if($realestateunitpaidinstallments->valuerent > $realestateunitpaidinstallments->totalpaid) {
           $realestateunitpaidinstallments->payed = 1;   
        }else{
           $realestateunitpaidinstallments->payed = 2;
        }
        R::store($realestateunitpaidinstallments);
        paieds($realestateunitspaids->supplierid, $realestateunitspaids->realestateid, $payed, $realestateunitpaidid, $realestateunitpaidinstallmentid);
        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
}


function paieds($supplierid, $realestateid, $advancepayment, $realestateunitpaidid, $realestateunitpaidinstallmentid) {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $supplier = R::getRow('select * from supplier WHERE supplierid = ? ', [$supplierid]);
    $realestates = R::load('realestates', $realestateid);
    $expensesname = ' مصروف للعقار  ' . $realestates->realestatename;
    $expensecomment = ' مصروف للعقار  ' . $realestates->realestatename . ' من  المأجر  ' . $supplier['suppliername'] . ' بتاريخ  ' . $today;
    $send_data = array(
      'expensetype' => $realestates->expenstypeid,
      'supplier' => $supplierid,
      'searchvalue' => '2',
      'productid' => '',
      'Costcenterid' =>  '-1',
      'paymethod' =>  '0',
      'saveid' =>   $_SESSION['saveid'],
      'bankid' =>  '-1',
      'checkNo' =>  '',
      'expensesname' => $expensesname,
      'expensevalue' => $advancepayment,
      'realestateid' => $realestateid,
      'realestateunitid' => 0,
      'expensecomment' =>  $expensecomment
    );
    $expenseid = CURL_IT2($send_data, 'expensesController.php?do=add');
    if ((int)$expenseid > 1) {
        $realestateunitpaidhistorys = R::dispense('realestateunitpaidhistorys');
        $realestateunitpaidhistorys->del = 1;
        $realestateunitpaidhistorys->addtoday = $today;          
        $realestateunitpaidhistorys->adduserid = $_SESSION['userid'];
        $realestateunitpaidhistorys->clientid = 0;     
        $realestateunitpaidhistorys->supplierid = $supplierid;     
        $realestateunitpaidhistorys->realestateunitpaidid = $realestateunitpaidid;
        $realestateunitpaidhistorys->realestateunitpaidinstallmentid = $realestateunitpaidinstallmentid;
        $realestateunitpaidhistorys->advancepayment = $advancepayment;
        $realestateunitpaidhistorys->expenseid = (int)$expenseid;
        $realestateunitpaidhistorys->incomeid = 0;
        $realestateunitpaidhistoryid = R::store($realestateunitpaidhistorys);
        if ($realestateunitpaidinstallmentid == 0) {
             R::exec("UPDATE `realestateunitspaids` SET `expenseid`= $expenseid, `realestateunitpaidhistoryid`= $realestateunitpaidhistoryid  WHERE id = '" . $realestateunitpaidid . "' ");
        }else{
           R::exec("UPDATE `realestateunitpaidinstallments` SET `expenseid`= $expenseid , `realestateunitpaidhistoryid`= $realestateunitpaidhistoryid WHERE id = '" . $realestateunitpaidinstallmentid . "' ");  
        }
          
    }else{
        echo '0';
        exit();
    }

}
function showajax() {
    $columns = array('realestateunitspaids.id', 'suppliername', 'realestatename', 'realestates.addtoday', 'employeename', 'realestateunitspaids.id', 'realestateunitspaids.id');
    $start_date = filter_input(INPUT_POST, 'start_date');
    $end_date = filter_input(INPUT_POST, 'end_date');
    $del = filter_input(INPUT_POST, 'del');
    $supplierid = filter_input(INPUT_POST, 'supplierid');
    $realestateid = filter_input(INPUT_POST, 'realestateid');
    $data3 = filter_input(INPUT_POST, 'data3');

    $searchQuery = " ";
    $searchjoin = " ";
    if($supplierid != ''){
      $searchQuery .=  " and realestateunitspaids.supplierid = ".$supplierid. " ";
    }

    if($realestateid != ''){
      $searchQuery .=  " and realestateunitspaids.realestateid = ".$realestateid. " ";
    }

    if($del == ''){
       $searchQuery .= " and realestateunitspaids.del < 2 "; 
    }

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


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

    $rResult = R::getAll('SELECT realestateunitspaids.* ,employeename ,suppliername ,realestatename   FROM `realestateunitspaids` LEFT JOIN user ON realestateunitspaids.adduserid = user.userid 
        LEFT JOIN supplier ON realestateunitspaids.supplierid = supplier.supplierid
        LEFT JOIN realestates ON realestateunitspaids.realestateid = realestates.id
     '.$searchjoin.'  WHERE realestateunitspaids.clientid = 0 '.$searchQuery.' ');   
    
    
     
    $output = array(  
        "draw" => intval($_POST["draw"]),
        "recordsTotal" => count($rResult),
        "recordsFiltered" => $totals,
        "data" => array()
    );
  
   foreach ($rResult as $row) {
        $sub_array = array();
        $sub_array[] = $row["id"];
        $sub_array[] = $row["suppliername"];
        $sub_array[] = $row["realestatename"];
        $sub_array[] = $row["addtoday"];
        $sub_array[] = $row['employeename'] ;  
        if($row["del"] < 2){  
        $sub_array[] = '<a href="realestateunitsowners.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="realestateunitsowners" type="button" class="btn btn-default btn-lg deleteicon removecontroller"  ></a>';
        }else{
          $sub_array[] = '<a href="realestateunitsowners.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 editid() {
    $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('realestateunitspaids',$id);
    try {

        $realestateunitpaidinstallments = R::findAll('realestateunitpaidinstallments','realestateunitpaidid = ? and del < 2',[$id]);
        $valuerent = 0;
        foreach($realestateunitpaidinstallments  as  $realestateunitpaidinstallment){
            if ($realestateunitpaidinstallment->totalpaid == 0) {
                $valuerent  += $realestateunitpaidinstallment->valuerent;
                $realestateunitpaidinstallment->del = 2;
                R::store($realestateunitpaidinstallment);
            }
        }

       

        R::exec("UPDATE `realestateunitpaidinstallments` SET `valuerent`= valuerent + $valuerent, payed = 1 WHERE realestateunitpaidid = '" . $id . "' order by id desc limit 1 ");
         R::exec("UPDATE `realestateunitspaids` SET `numberinstallments`= $real WHERE id = '" . $id . "' ");
           
       
        // // $tables->totalpaid = (int)$tables->totalpaid - $valuerent;
        // R::store($tables);
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }
}

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('realestateunitspaids',$id);
    $tables->del = 2;
    $tables->deltoday = $today;
    $tables->deluserid = $userid;     
    try {
        R::store($tables);
        R::exec("UPDATE `realestates` SET `savaible`= 0 WHERE id = '" . $tables->realestateid . "' ");

        $expense = R::getRow('select * from expenses WHERE expensesid = ? ', [$tables->expenseid]);
        CURL_IT2(array(),'expensesController.php?do=delete&id='.$tables->expenseid.'&dailyentry='.$expense['dailyentryid']);



        $realestateunitpaidinstallments = R::findAll('realestateunitpaidinstallments','realestateunitpaidid = ? and del < 2',[$id]);
        foreach($realestateunitpaidinstallments  as  $realestateunitpaidinstallment){
            $realestateunitpaidinstallment->del = 2;
            R::store($realestateunitpaidinstallment);

        $expense = R::getRow('select * from expenses WHERE expensesid = ? ', [$realestateunitpaidinstallment->expenseid]);
        CURL_IT2(array(),'expensesController.php?do=delete&id='.$realestateunitpaidinstallment->expenseid.'&dailyentry='.$expense['dailyentryid']);



         

            R::exec("UPDATE `realestateunitpaidhistorys` SET `del`= 2 WHERE id = '" . $realestateunitpaidinstallment->realestateunitpaidhistoryid . "' ");
        }

       
        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);


        R::exec("UPDATE `realestates` SET `savaible`= 0 WHERE id = '" . $tables->realestateid . "' ");

        $expense = R::getRow('select * from expenses WHERE expensesid = ? ', [$tables->expenseid]);
        CURL_IT2(array(),'expensesController.php?do=delete&id='.$tables->expenseid.'&dailyentry='.$expense['dailyentryid']);


        R::exec("UPDATE `realestateunitpaidhistorys` SET `del`= 2 WHERE id = '" . $tables->realestateunitpaidhistoryid . "' ");
        R::exec("UPDATE `realestateunitspaids` SET `totalpaid`= totalpaid - $tables->totalpaid, `numberinstallments`= numberinstallments - 1 WHERE id = '" . $tables->realestateunitpaidid . "' ");



        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;
}



?>