<?php
require_once "wanted.php";
    class VAT{
        private $conn;
        public function __construct($conn)
        {
            $this->conn          = $conn;
        }
    function lastPeriod( $contract_id){
        $conn = $this->conn;
        $last_sql = $conn->prepare("SELECT max(end) as last from vat where contract_id = ?");
        $last_sql->bindParam(1,$contract_id);
        $last_sql->execute();
    if($last_sql->rowCount()>0){
        $segl = $last_sql->fetch(PDO::FETCH_ASSOC);
        return $segl['last'];
      }else{
        return "0";
      }
    }
    function lastVat( $contract_id){
        $conn = $this->conn;
        $last_sql = $conn->prepare("SELECT max(vat_id) as lastVat from vat where contract_id = ?");
        $last_sql->bindParam(1,$contract_id);
        $last_sql->execute();
    if($last_sql->rowCount()>0){
        $segl = $last_sql->fetch(PDO::FETCH_ASSOC);
        return $segl['lastVat'];
      }else{
        return "0";
      }
    }
    function maxD(){
        $conn = $this->conn;
        $maxsql= $conn->prepare("SELECT max(vat_id) as maxd FROM vat");
        $maxsql->execute();
      if($maxsql->rowCount()>0){$row = $maxsql->fetch(PDO::FETCH_ASSOC);
         $maxD = $row['maxd']+1;} else {$maxD = 19000 ; }
         return $maxD;
    }
    function contractINFO($contract_id){
        $conn = $this->conn;
        $sql = $conn->prepare("SELECT date_out , date_in , time_out , time_in , kilo_cost ,kilos_cost ,
        free_kilo , km_in , km_out ,day_cost , hour_cost,addtion_cost , violations ,addtion_desc ,
        days_qty,	cont_status ,deduction , wesam_ins , open_kilo FROM contracts WHERE contract_id = ? LIMIT 1");
        $sql->bindParam(1,$contract_id);
        $sql->execute();
    if($sql->rowCount()>0){$row = $sql->fetch(PDO::FETCH_ASSOC);
        return $row;    
        }else{ return "no data found" ;}
    }

    function hourCal($time_out,$time_in,$day_cost){
        $data = array();
            $time1 = new DateTime($time_out);
            $time2 = new DateTime($time_in);
        if($time2 > $time1){ $hour_qty = intval($time2->diff($time1)->format("%h")); }
        else{
            $data['hour_qty'] = 0;
            $data['hours_cost'] = 0;
            $data['day_hour'] = 0;
            return $data;
        }
        if($hour_qty > 1){ 
        if($hour_qty < 6){
                $data['hours_cost'] = round((($hour_qty - 1) * ($day_cost / 12)),2);
                $data['hour_qty'] = $hour_qty;
                $data['day_hour'] = 0;
            return $data;
        }
        else if($hour_qty > 5){
            $data['hour_qty'] = $hour_qty;
            $data['hours_cost'] = $day_cost ;
            $data['day_hour'] = 1;
            return $data;
        }else{
            $data['hour_qty'] = 0;
            $data['hours_cost'] = 0;
            $data['day_hour'] = 0;
            return $data;
        }
        }
    } 
    function kmCal($km_out,$km_in,$day_km,$free_kilo,$kilo_cost){
            $data = array();
                $kilo_qty = $km_in - ($km_out + ($day_km * $free_kilo)) ;
            if($kilo_qty < 0){$kilo_qty = 0 ;}
            if($kilo_qty > 0){$kilos_cost = ( $kilo_qty * $kilo_cost)/100 ;} 
                    else {$kilos_cost = 0 ;}
                $data['kilos_cost'] = intval($kilos_cost);
                $data['used_km']    = $km_in - $km_out ;
                $data['kilo_qty']   = $kilo_qty ;
            return $data;    
    }
    // create vat invoice
    function createVat($contract_id,$end,$father){
        $conn             = $this->conn ;
        $vat            = new VAT($conn);
        $contINFO       = $vat->contractINFO($contract_id);
            $date_in            = $contINFO["date_in"];
            $date_out           = $contINFO["date_out"];
            $time_in            = $contINFO["time_in"];
            $time_out           = $contINFO["time_out"];
            $day_km             = $contINFO["days_qty"];
            $cont_status        = $contINFO["cont_status"];
            $oraginal_day_cost           = $contINFO["day_cost"];
            $day_cost           = $oraginal_day_cost + $contINFO["wesam_ins"];
            $day_cost           = $day_cost + $contINFO["open_kilo"];
            $kilo_cost          = $contINFO["kilo_cost"];
            $free_kilo          = $contINFO["free_kilo"];
            $km_in              = $contINFO["km_in"];
            $km_out             = $contINFO["km_out"];
            $time_in            = $contINFO["time_in"];
            $time_in            = $contINFO["time_in"];
            $addtion_desc       = $contINFO["addtion_desc"];
            $addtion_cost       = $contINFO["addtion_cost"];
            $violations         = $contINFO["violations"];
            $deduction          = $contINFO["deduction"];
        if (empty($addtion_cost)) {
            $addtion_cost = 0;
        }
        if (empty($violations)) {
            $violations = 0;
        }
        if (empty($deduction)) {
            $deduction = 0;
        }
        if (empty($day_km)) {
            $day_km = 0;
        }
        $last = $vat->lastPeriod($contract_id);
        if($last > 0){
            $d1 = new DateTime($last);
            $d2 = new DateTime($end);
            if(($d1==$d2)&&($cont_status == 1)){
                return false;
            }
            else if($d1 > $d2){
                return false ;
            }
        }
       

        if(!empty($last)){$date_out = $last ; }
        $date1 = new DateTime($date_out);
        $date2 = new DateTime($end);
            $days_qty = $date2->diff($date1)->format("%a");
                    $days_cost 		=  $days_qty * $day_cost ;
                    // $used_km 		= 0 ;
    if(!empty($time_in)){
        $hourCal    = $vat->hourCal($time_out,$time_in,$oraginal_day_cost);
        $hour_qty   = isset($hourCal['hour_qty'])? $hourCal['hour_qty'] : 0 ;
        $hours_cost = isset($hourCal['hours_cost'])? $hourCal['hours_cost'] : 0  ;
        $day_hour   = isset($hourCal['day_hour'])? $hourCal['day_hour'] : 0 ;
        $day_km = $day_km + $day_hour ;
        
        $kmCal = $vat->kmCal($km_out,$km_in,$day_km,$free_kilo,$kilo_cost);
        $kilos_cost = $kmCal['kilos_cost'];
        $kilo_qty   = $kmCal['kilo_qty'];
       
    } else
             {	$kilos_cost = 0 ; 	$kilo_qty	  = 0 ;
                //  $used_km = 0 ;
                }

             if(empty($date_in)){
                $hours_cost 	= 0 ;
                $kilos_cost 	= 0 ;
                $addtion_cost   = 0 ;
                $violations     = 0 ;
                $deduction		= 0 ;
                $addtion_desc   = "";
            } else{        
                $date_in2 = date('Y-m-d', strtotime($date_in));
                $end2 	  = date('Y-m-d', strtotime($end));
            if($end2 < $date_in2){
                $hours_cost 	= 0 ;
                $kilos_cost 	= 0 ;
                $addtion_cost 	= 0 ;
                $violations   	= 0 ;
                $deduction		= 0 ;
                $addtion_desc 	= "";
                 }
         }
              $net_cost 	= round((( $days_cost + $kilos_cost + $hours_cost + $addtion_cost)- $deduction),2) ;
              if($net_cost < 1){
                return false ;
                exit();
              }
              $vat_req 		= round(($net_cost  * 0.15),2) ;
              
              $after_vat 	= round(($vat_req + $net_cost + $violations),2) ;

        if (empty($deduction)) {
            $deduction = 0;
        }
        $total_rent = $days_cost + $hours_cost + $kilos_cost;
        $maxD = $vat->maxD();
        $myday 		= date("Y-m-d H:i:s");
    //remove at phase 2 e-invoice
        $myday2 		= new DateTime($myday);
        $mydate_in 		= new DateTime($date_in);

        if( $myday2->format('U') < $date2->format('U')  ){
            $duedate = $myday;
             } else if(!empty($date_in)){
               if( $mydate_in->format('U') > $date2->format('U')){
                  $duedate      = $end.' '.$time_out;  
                      }
                     else{
                         $duedate      = $end.' '.$time_in;
                         }
             }else{
                     $duedate      = $end.' '.$time_out; 
                     }


        // $duedate =  $myday ;

        $new_vat = $conn->prepare("INSERT INTO `vat` (`vat_id`, `contract_id`, `cont_status`, `start`, `end`, `days_qty`, `day_cost`, `days_cost`,
              `kilo_qty`, `kilos_cost`, `hour_qty`, `hours_cost`, `total_rent`, `addtion_cost`, `violations`, `deduction`, `net_cost`, `vat_req`, `after_vat`,  `father`,addtion_desc,duedate)
              VALUES (?, ?, ?, ?, ?,?, ?, ?, ?, ?,?, ?, ?, ?, ?,?, ?, ?, ?, ?,?,?)");
        $new_vat->bindParam(1, $maxD);
        $new_vat->bindParam(2, $contract_id);
        $new_vat->bindParam(3, $cont_status);
        $new_vat->bindParam(4, $date_out);
        $new_vat->bindParam(5, $end);
        $new_vat->bindParam(6, $days_qty);
        $new_vat->bindParam(7, $day_cost);
        $new_vat->bindParam(8, $days_cost);
        $new_vat->bindParam(9, $kilo_qty);
        $new_vat->bindParam(10, $kilos_cost);
        $new_vat->bindParam(11, $hour_qty);
        $new_vat->bindParam(12, $hours_cost);

        $new_vat->bindParam(13, $total_rent);
        $new_vat->bindParam(14, $addtion_cost);
        $new_vat->bindParam(15, $violations);
        $new_vat->bindParam(16, $deduction);
        $new_vat->bindParam(17, $net_cost);
        $new_vat->bindParam(18, $vat_req);

        $new_vat->bindParam(19, $after_vat);
        $new_vat->bindParam(20, $father);
        $new_vat->bindParam(21, $addtion_desc);
        $new_vat->bindParam(22, $duedate);
        if ($new_vat->execute()) {
            return true;
        }else{
            return false ;
        }

    }
    // update vat
    function updateVat($contract_id,$end,$father){
        $conn             = $this->conn ;
        $vat            = new VAT($conn);
        $vat_id         = $vat->lastVat($contract_id);
        
            $contINFO           = $vat->contractINFO($contract_id);
            $date_in            = $contINFO["date_in"];
            $date_out           = $contINFO["date_out"];
            $time_in            = $contINFO["time_in"];
            $time_out           = $contINFO["time_out"];
            $day_km             = $contINFO["days_qty"];
            $cont_status        = $contINFO["cont_status"];
            $oraginal_day_cost  = $contINFO["day_cost"];
            $day_cost           = $oraginal_day_cost + $contINFO["wesam_ins"];
            $day_cost           = $day_cost + $contINFO["open_kilo"];
            $kilo_cost          = $contINFO["kilo_cost"];
            $free_kilo          = $contINFO["free_kilo"];
            $km_in              = $contINFO["km_in"];
            $km_out             = $contINFO["km_out"];
            $time_in            = $contINFO["time_in"];
            $time_in            = $contINFO["time_in"];
            $addtion_desc       = $contINFO["addtion_desc"];
            $addtion_cost       = $contINFO["addtion_cost"];
            $violations         = $contINFO["violations"];
            $deduction          = $contINFO["deduction"];
        if (empty($addtion_cost)) {
            $addtion_cost = 0;
        }
        if (empty($violations)) {
            $violations = 0;
        }
        if (empty($deduction)) {
            $deduction = 0;
        }
        if (empty($day_km)) {
            $day_km = 0;
        }
        $del = $conn->prepare("DELETE FROM vat where vat_id = $vat_id");
        $del->execute();

        $last = $vat->lastPeriod($contract_id);
        if($last > 0){
            $d1 = new DateTime($last);
            $d2 = new DateTime($end);
            if(($d1==$d2)&&($cont_status == 1)){
                return false;
            }
            else if($d1 > $d2){
                return false ;
            }
        }
        if(!empty($last)){$date_out = $last ; }
        $date1 = new DateTime($date_out);
        $date2 = new DateTime($end);
            $days_qty = $date2->diff($date1)->format("%a");
                    $days_cost 		=  $days_qty * $day_cost ;
                    // $used_km 		= 0 ;
    if(!empty($time_in)){
        $hourCal    = $vat->hourCal($time_out,$time_in,$oraginal_day_cost);
        $hour_qty   = isset($hourCal['hour_qty'])? $hourCal['hour_qty'] : 0 ;
        $hours_cost = isset($hourCal['hours_cost'])? $hourCal['hours_cost'] : 0  ;
        $day_hour   = isset($hourCal['day_hour'])? $hourCal['day_hour'] : 0 ;
        $day_km = $day_km + $day_hour ;
        
        $kmCal = $vat->kmCal($km_out,$km_in,$day_km,$free_kilo,$kilo_cost);
        $kilos_cost = $kmCal['kilos_cost'];
        $kilo_qty   = $kmCal['kilo_qty'];
       
    } else
             {	$kilos_cost = 0 ; 	$kilo_qty	  = 0 ;
                //  $used_km = 0 ;
                }

             if(empty($date_in)){
                $hours_cost 	= 0 ;
                $kilos_cost 	= 0 ;
                $addtion_cost   = 0 ;
                $violations     = 0 ;
                $deduction		= 0 ;
                $addtion_desc   = "";
            } else{        
                $date_in2 = date('Y-m-d', strtotime($date_in));
                $end2 	  = date('Y-m-d', strtotime($end));
            if($end2 < $date_in2){
                $hours_cost 	= 0 ;
                $kilos_cost 	= 0 ;
                $addtion_cost 	= 0 ;
                $violations   	= 0 ;
                $deduction		= 0 ;
                $addtion_desc 	= "";
                 }
         }
              $net_cost 	= round((( $days_cost + $kilos_cost + $hours_cost + $addtion_cost)- $deduction),2) ;
              $vat_req 		= round(($net_cost  * 0.15),2) ;
              
              $after_vat 	= round(($vat_req + $net_cost + $violations),2) ;

        if (empty($deduction)) {
            $deduction = 0;
        }
        $total_rent = $days_cost + $hours_cost + $kilos_cost;
        // $maxD = $vat->maxD();
        $myday 		= date("Y-m-d H:i:s");
        $myday2 		= new DateTime($myday);
        $mydate_in 		= new DateTime($date_in);
        if( $myday2->format('U') < $date2->format('U')  ){
            $duedate = $myday;
             } else if(!empty($date_in)){
               if( $mydate_in->format('U') > $date2->format('U')){
                  $duedate      = $end.' '.$time_out;  
                      }
                     else{
                         $duedate      = $end.' '.$time_in;
                         }
             }else{
                     $duedate      = $end.' '.$time_out; 
                     }

        $new_vat = $conn->prepare("INSERT INTO `vat` (`vat_id`, `contract_id`, `cont_status`, `start`, `end`, `days_qty`, `day_cost`, `days_cost`,
              `kilo_qty`, `kilos_cost`, `hour_qty`, `hours_cost`, `total_rent`, `addtion_cost`, `violations`, `deduction`, `net_cost`, `vat_req`, `after_vat`,  `father`,addtion_desc,duedate)
              VALUES (?, ?, ?, ?, ?,?, ?, ?, ?, ?,?, ?, ?, ?, ?,?, ?, ?, ?, ?,?,?)");
        $new_vat->bindParam(1, $vat_id);
        $new_vat->bindParam(2, $contract_id);
        $new_vat->bindParam(3, $cont_status);
        $new_vat->bindParam(4, $date_out);
        $new_vat->bindParam(5, $end);
        $new_vat->bindParam(6, $days_qty);
        $new_vat->bindParam(7, $day_cost);
        $new_vat->bindParam(8, $days_cost);
        $new_vat->bindParam(9, $kilo_qty);
        $new_vat->bindParam(10, $kilos_cost);
        $new_vat->bindParam(11, $hour_qty);
        $new_vat->bindParam(12, $hours_cost);

        $new_vat->bindParam(13, $total_rent);
        $new_vat->bindParam(14, $addtion_cost);
        $new_vat->bindParam(15, $violations);
        $new_vat->bindParam(16, $deduction);
        $new_vat->bindParam(17, $net_cost);
        $new_vat->bindParam(18, $vat_req);

        $new_vat->bindParam(19, $after_vat);
        $new_vat->bindParam(20, $father);
        $new_vat->bindParam(21, $addtion_desc);
        $new_vat->bindParam(22, $duedate);
        if ($new_vat->execute()) {
            return true;
        }else{
            return false ;
        }
    }
}
// include_once "../actions/dbPDO.php";
// $contract_id = 400383 ;
// $father = 3;
// $end = "2020-10-31";

// $vat = new VAT($conn);
// $vat->createVat($contract_id,$end,$father);
?>

