<?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");
if (empty($do)) {  
    $smarty->display("header.html");
    $smarty->display("transactionsSalesView/add.html");
    $smarty->assign("transactionsestatesjs", 1);
    $smarty->display("footer.html");
} elseif ($do == "show") {
    include_once("../public/authentication.php");
    $smarty->display("header.html");
    $smarty->display("transactionsSalesView/show.html");
    $smarty->assign("transactionsestatesjs", 1);
    $smarty->display("footer.html");
} elseif ($do == "edit") {
    include_once("../public/authentication.php");
    $id = filter_input(INPUT_GET, 'id');
    $editdata = R::load('transactionsestates', $id);
    $editdata->delegate = R::getRow('SELECT * FROM `user` WHERE userid = ? ',[$editdata->delegateid]);
    $editdata->delegaterelief = R::getRow('SELECT * FROM `user` WHERE userid = ? ',[$editdata->delegatereliefid]);
    $editdata->delegatedata = R::getRow('SELECT * FROM `user` WHERE userid = ? ',[$editdata->delegatedataid]);
    $editdata->delegateclearance = R::getRow('SELECT * FROM `user` WHERE userid = ? ',[$editdata->delegateclearanceid]);
    $smarty->assign('editdata', $editdata);
    $smarty->display("header.html");
    $smarty->display("transactionsSalesView/edit.html");
    $smarty->assign("transactionsestatesjs", 1);
    $smarty->display("footer.html");
}else if ($do == 'savedata') {
  savedata();
}else if ($do == 'showajax') {
  showajax(); 
}else if ($do == 'removecontroller') {
  removecontroller();
}


function savedata() {
    // include "../library/phpqrcode/qrlib.php";    
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $transactionestate = filter_input(INPUT_POST, 'transactionestate');
    $transactionvalue = filter_input(INPUT_POST, 'transactionvalue');
    $delegateid = filter_input(INPUT_POST, 'delegateid');
    $fullcommission = filter_input(INPUT_POST, 'fullcommission');
    $services = filter_input(INPUT_POST, 'services');
    $externalcommission = filter_input(INPUT_POST, 'externalcommission');
    $delegatereliefid = filter_input(INPUT_POST, 'delegatereliefid');
    $reliefvalue = filter_input(INPUT_POST, 'reliefvalue');
    $delegatedataid = filter_input(INPUT_POST, 'delegatedataid');
    $datavalue = filter_input(INPUT_POST, 'datavalue');
    $delegateclearanceid = filter_input(INPUT_POST, 'delegateclearanceid');
    $delegateclearanceidvalue = filter_input(INPUT_POST, 'delegateclearanceidvalue');
    $onlinevalue = filter_input(INPUT_POST, 'onlinevalue');
    $netservices = filter_input(INPUT_POST, 'netservices');
    $representativecommission = filter_input(INPUT_POST, 'representativecommission');
    $officecommission = filter_input(INPUT_POST, 'officecommission');
    $savevalue = filter_input(INPUT_POST, 'savevalue');
    $etransactionestateid = filter_input(INPUT_POST, 'transactionestateid');

    if (!$etransactionestateid) {
        $transactionsestates = R::dispense('transactionsestates');        
        $transactionsestates->del = 0;
        $transactionsestates->addtoday = $today;          
        $transactionsestates->adduserid = $userid;
        $transactionsestates->deltoday = '';      
        $transactionsestates->deluserid = '';
        $transactionsestates->incomeid = 0;
        $transactionsestates->incometypeid = 7;
    }else{
        $transactionsestates = R::load('transactionsestates', $etransactionestateid); 
        $income = R::getRow('SELECT * FROM `income` WHERE incomeId = ? ',[$transactionsestates->incomeid]);
        $incomeoldname = $transactionsestates->transactionestate;
        $transactionsestates->del = 1;
        $transactionsestates->updatetoday = $today;          
        $transactionsestates->updateuserid = $userid; 
    }
    $transactionsestates->transactionestate  = $transactionestate;
    $transactionsestates->transactionvalue  = $transactionvalue;
    $transactionsestates->delegateid  = $delegateid;
    $transactionsestates->fullcommission  = $fullcommission;
    $transactionsestates->services  = $services;
    $transactionsestates->externalcommission  = $externalcommission;
    $transactionsestates->delegatereliefid  = $delegatereliefid;
    $transactionsestates->reliefvalue  = $reliefvalue;
    $transactionsestates->delegatedataid  = $delegatedataid;
    $transactionsestates->datavalue  = $datavalue;
    $transactionsestates->delegateclearanceid  = $delegateclearanceid;
    $transactionsestates->delegateclearanceidvalue  = $delegateclearanceidvalue;
    $transactionsestates->onlinevalue = $onlinevalue;
    $transactionsestates->netservices = $netservices;
    $transactionsestates->representativecommission = $representativecommission;
    $transactionsestates->officecommission = $officecommission;
    $transactionsestates->savevalue = $savevalue;
    $transactionsestates->saveid =  $_SESSION['saveid'];
    try {
        $transactionestateid = R::store($transactionsestates);

        if (!$etransactionestateid) {
            $send_data = array(
                'clientid' => -1,
                'saveid' => $_SESSION['saveid'],
                'Costcenterid' => -1,
                'Value' => $savevalue,
                'comment' => 'اضافة نوع ايراد  معاملات تجاري واسم الايراد ' . $transactionsestates->transactionestate,
                'name' => $transactionsestates->transactionestate,
                'parent' => 7,
            );
            $incomeController = CURL_IT2($send_data, 'incomeController.php?do=add');
            $obj = json_decode($incomeController);
            R::exec("UPDATE `transactionsestates` SET `incomeid`= $obj->id WHERE id = '" . $transactionestateid . "' ");
        }else{

            $send_data = array(
                'incomeId' => $income['incomeId'],
                'oldname' => $incomeoldname,
                'dailyentryid' => $income['dailyentryid'],
                'clientid' => -1,
                'saveid' => $_SESSION['saveid'],
                'Costcenterid' => -1,
                'Value' => $savevalue,
                'comment' =>'تعديل نوع ايراد معاملات تجاري واسم الايراد ' . $transactionsestates->transactionestate,
                'name' => $transactionsestates->transactionestate,
                'parent' => 7,
            );
            CURL_IT2($send_data, 'incomeController.php?do=update');
        }
        echo $transactionestateid;
    } catch (Exception $e) {
        echo 0 ;
    }
}


function showajax() {
    // $columns = array('id', 'id', 'transactionestate', 'transactionvalue','delegateid', 'fullcommission', 'delegatereliefid', 'reliefvalue', 'delegatedataid', 'datavalue', 'delegateclearanceid', 'delegateclearanceidvalue', 'onlinevalue', 'externalcommission', 'representativecommission', 'officecommission', 'savevalue', 'saveid', 'incomeid', 'addtoday','adduserid', 'id', 'id', 'del');

     $columns = array('id', 'id', 'transactionestate', 'transactionvalue','delegateid', 'fullcommission', 'delegatereliefid', 'reliefvalue', 'delegatedataid', 'datavalue', 'delegateclearanceid', 'delegateclearanceidvalue', 'representativecommission', 'officecommission', 'savevalue', 'saveid', 'incomeid', 'addtoday','adduserid', 'id', 'id', 'del');

    $start_date = $_POST['start_date'];
    $end_date   = $_POST['end_date'];
    $del        = $_POST['del'];
    $delegateid = $_POST['delegateid'];
    $delegatereliefid  = $_POST['delegatereliefid'];
    $delegatedataid  = $_POST['delegatedataid'];
    $delegateclearanceid  = $_POST['delegateclearanceid'];
    $saveid        = $_POST['saveid'];
    $adduserid        = $_POST['adduserid'];
    $id        = $_POST['id'];

    $searchQuery = " ";

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

    if($delegateid != ''){
      $searchQuery .=  " and transactionsestates.delegateid = ".$delegateid. " ";
    }

    if($delegatereliefid != ''){
      $searchQuery .=  " and transactionsestates.delegatereliefid = ".$delegatereliefid. " ";
    }

    if($delegatedataid != ''){
      $searchQuery .=  " and transactionsestates.delegatedataid = ".$delegatedataid. " ";
    }

    if($delegateclearanceid != ''){
      $searchQuery .=  " and transactionsestates.delegateclearanceid = ".$delegateclearanceid. " ";
    }

    if($saveid != ''){
       $searchQuery .= " and transactionsestates.saveid = ".$saveid. " ";
    }

    if($adduserid != ''){
       $searchQuery .= " and transactionsestates.adduserid = ".$adduserid. " ";
    }

    if($del == 1){
       $searchQuery .= " and transactionsestates.del > 1 "; 
    }

   
    
    if($start_date != '' && $end_date != ''){
       $searchQuery .='and  transactionsestates.addtoday  >= "' . $start_date . ' 00-00-00" and transactionsestates.addtoday <= "' . $end_date . ' 23-79-77" ';
    }else{
        // $today = date("Y-m-d");
        // $searchQuery .='and  students.addtoday  >= "' . $today . ' 00-00-00" and students.addtoday <= "' . $today . ' 23-79-77" ';
    }


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( transactionsestates.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR transactionsestates.transactionestate LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.transactionvalue LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.delegateid LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.fullcommission LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.services LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.externalcommission LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.delegatereliefid LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.reliefvalue LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.delegatedataid LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.datavalue LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.delegateclearanceid LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.delegateclearanceidvalue LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.onlinevalue LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.netservices LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.representativecommission LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.officecommission LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.savevalue LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.saveid LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.incomeid LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.addtoday LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.adduserid LIKE "%'.$_POST["search"]["value"].'%"
                    OR transactionsestates.del LIKE "%'.$_POST["search"]["value"].'%"
        )
     ";
    }


    if(isset($_POST["order"]))
    {
    $searchQuery .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'  ';
    }
    else
    {
     $searchQuery .= "ORDER BY  transactionsestates.id DESC ";
    }
    
     $totals = R::count('transactionsestates','WHERE transactionsestates.incometypeid = 7 '.$searchQuery.' ');
    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    $rResult = R::getAll('SELECT transactionsestates.* ,userdelegateid.employeename as userdelegate
    ,userdelegatereliefid.employeename as userdelegaterelief,
    userdelegatedataid.employeename as userdelegatedata,
    userdelegateclearanceid.employeename as userdelegateclearance,
    useradduserid.employeename as useradduser ,savename  FROM `transactionsestates` 
        LEFT JOIN user as userdelegateid ON transactionsestates.delegateid = userdelegateid.userid
        LEFT JOIN user as userdelegatereliefid ON transactionsestates.delegatereliefid = userdelegatereliefid.userid
        LEFT JOIN user as userdelegatedataid ON transactionsestates.delegatedataid = userdelegatedataid.userid
        LEFT JOIN user as userdelegateclearanceid ON transactionsestates.delegateclearanceid = userdelegateclearanceid.userid
        LEFT JOIN user as useradduserid ON transactionsestates.adduserid = useradduserid.userid
        LEFT JOIN save ON transactionsestates.saveid = save.saveid
        WHERE transactionsestates.incometypeid = 7 '.$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["id"];
        $sub_array[] = $row["transactionestate"];
        $sub_array[] = $row["transactionvalue"];
        $sub_array[] = $row["userdelegate"];
        $sub_array[] = $row["fullcommission"];
        $sub_array[] = $row["userdelegaterelief"];
        $sub_array[] = $row["reliefvalue"];
        $sub_array[] = $row["userdelegatedata"];
        $sub_array[] = $row["datavalue"];
        $sub_array[] = $row["userdelegateclearance"];
        $sub_array[] = $row["delegateclearanceidvalue"];
        // $sub_array[] = $row["onlinevalue"];
        // $sub_array[] = $row["externalcommission"];
        $sub_array[] = $row["representativecommission"];
        $sub_array[] = $row["officecommission"];
        $sub_array[] = $row["savevalue"];
        $sub_array[] = $row["savename"];
        $sub_array[] = $row["addtoday"];
        $sub_array[] = $row['useradduser'];  
        if($row["del"] < 2){  
             $sub_array[] = '<a href="transactionsSalesController.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="transactionsSalesController" type="button" class="btn btn-default btn-lg deleteicon removecontroller"  ></a>';
        }else{
          $sub_array[] = '<a href="transactionsSalesController.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('transactionsestates',$id);
    $tables->del = 2;
    $tables->deltoday = $today;
    $tables->deluserid = $userid;     
    try {
        R::store($tables);
        $send_data = array(
            'curlpost' => 1
        );
        $income = R::getRow('SELECT * FROM `income` WHERE incomeId = ? ',[$tables->incomeid]);
        $dailyentryid = $income['dailyentryid'];
        CURL_IT2($send_data, "incomeController.php?do=delete&id=$tables->incomeid&action=$dailyentryid");
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }
}



function CURL_IT2($data_arr, $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;
}




?>