<?php
require_once "../magic/session_config.php";
bdr_start_session();
ob_start();
include "../actions/dbPDO.php";
  $branch = $_SESSION["branch"];
  $father = $_SESSION["user_id"];

if(isset($_POST["km_in"])){
if($_POST['contract_id'] !=""){

    $time_in       = $_POST['time_in'];
    $date_in       = $_POST['date_in'];
    $contract_id   = $_POST['contract_id'];
    $day_cost      = $_POST['day_cost'];
    $km_in         = $_POST['km_in'];
    $kilo_cost     = $_POST['kilo_cost'];
    $free_kilo     = $_POST['free_kilo'];
    $addtion_cost  = $_POST['addtion_cost'];
    $addtion_desc  = $_POST['addtion_desc'];
    $violations    = $_POST['violations'];
    $ins_claim     = $_POST["ins_claim"];
    $deduction     = $_POST["deduction"];
    $comm          = $_POST["comm"];
    $carid         = $_POST["carid"];

    $vat_req 		= 0 ;
  	$after_vat 	= 0 ;
  	$vat_in 		= 0 ;

    $last = $db->prepare("SELECT  minn , km3 , freekilo from cars where carid = ? ");
    $last->bindParam(1,$carid);
    $last->execute();
if($last->rowCount()>0){$free = $last->fetch(PDO::FETCH_ASSOC);
        $minn 		= $free["minn"];
        $km3 			= $free["km3"];
        $freekm   = $free["freekilo"];
}
  $dc ='/^[0-9]+(\.[0-9]{1,2})?$/' ;
  $Number ="/^[0-9]+$/";
  $data  = array();
  $error = array();

if(empty($day_cost)){  $error["day_cost"] = "من فضلك سجل إيجار اليوم "; }
      if(!preg_match($Number,$day_cost)){ $error["day_cost"] = $error["day_cost"]."من فضلك تأكد من رقم المبلغ" ;}
      else if($minn > $day_cost){ $error["day_cost"] = "لقد تخطيت الحد الأدني للإيجار" ;}
  if(empty($free_kilo))
          {
            $error["free_kilo"] = "من فضلك سجل الكيلو المسموح";
          }
        if(!preg_match($Number,$free_kilo)){ $error["free_kilo"] = "أرقام فقط" ;}
        else if($freekm < $free_kilo){ $error["free_kilo"] = "لقد تخطيت الكيلو المسموح اليومي " ;}
if(empty($kilo_cost))
                {
                  $error["kilo_cost"] = "من فضلك سجل سعر الكيلو بالهللة";
                }
              if(!preg_match($Number,$kilo_cost)){ $error["kilo_cost"] = "أرقام فقط" ;}
              if($km3 > $kilo_cost){ $error["kilo_cost"] = "لقد تخطيت الحد الأدني للكسعر الكيلو" ;}
    if(empty($km_in)){ $error["km_in"] = "سجل عداد الدخول من فضلك ليتم غلق العقد ..." ; }
    else   if(!preg_match($Number,$km_in)){ $error["km_in"] = "أرقام صحيحة فقط" ;}
    if(!empty($addtion_cost))  { if(!preg_match($dc,$addtion_cost)){ $error["addtion_cost"] = "تأكد من الرقم" ;}}
    if(!empty($violations))    { if(!preg_match($Number,$violations)){ $error["violations"] = "أرقام صحيحة فقط" ;}}
    if(!empty($ins_claim))     { if(!preg_match($Number,$ins_claim)){ $error["ins_claim"] = "أرقام صحيحة فقط" ;}}
    if(!empty($deduction))     { if(!preg_match($dc,$deduction)){ $error["deduction"] = "أرقام صحيحة فقط" ;}}

if(!empty($addtion_desc)){  $addtion_desc = htmlspecialchars(strip_tags($addtion_desc)) ;}
if(!empty($comm)){  $comm = htmlspecialchars(strip_tags($comm)) ;}
if(!empty($error)){
  $data["error"] = $error ;
}else {
  $out_info = $db->prepare("SELECT  date_out , km_out , time_out from contracts where contract_id = ? ");
  $out_info->bindParam(1,$contract_id);
  $out_info->execute();
    if($out_info->rowCount()>0){$basic = $out_info->fetch(PDO::FETCH_ASSOC);
        $date_out 	= $basic["date_out"];
        $km_out 		= $basic["km_out"];
        $time_out   = $basic["time_out"];
      }
      $date1 = new DateTime($date_out);
      $date2 = new DateTime($date_in);
      $days_qty   = $date2->diff($date1)->format("%a");
      $days_cost  = intval( $days_qty * $day_cost) ;

  $time1 = new DateTime($time_out);
  $time2 = new DateTime($time_in);
  if($time2 > $time1){ $hour_qty = $time2->diff($time1)->format("%h"); }else{$hour_qty = 0;}

  $hour_cost = round(($day_cost / 12),2) ;

        if($hour_qty > 1) {if ($hour_qty < 6) {
          $hours_cost = round((($hour_qty - 1) * ($day_cost / 12)),2);
      } else   {
      $hours_cost = $day_cost;
      $day_km   = $day_km + 1 ;
      }}

  $kilo_qty = $km_in - ($km_out + ($days_qty * $free_kilo)) ;
  if($kilo_qty < 0){$kilo_qty = 0 ;}
  if($kilo_qty > 10){$kilos_cost = ( $kilo_qty * $kilo_cost)/100 ;} else {$kilos_cost = 0 ;}
  $kilos_cost = intval($kilos_cost);

  $net_cost = round(($days_cost + $kilos_cost + $hours_cost + $addtion_cost + $violations + $ins_claim),2) ;

  $tot_in = $db->prepare("SELECT sum(money_in) as inn from invoice WHERE contract_id =? ");
  $tot_in->bindParam(1,$contract_id);
  $tot_in->execute();
  if($tot_in->rowCount()>0){$toty_in = $tot_in->fetch(PDO::FETCH_ASSOC);
  $total_in = $toty_in["inn"];
  }
  $tot_out = $db->prepare("SELECT sum(money_out) as outt from outvoice WHERE contract_id = ? ");
  $tot_out->bindParam(1,$contract_id);
  $tot_out->execute();
  if($tot_out->rowCount()>0){$toty_out = $tot_out->fetch(PDO::FETCH_ASSOC);
           $total_out = $toty_out["outt"];}
  $payed = round(($total_in - $total_out ),2);

  $vat_start = date('Y-m-d', strtotime("2018-01-10"));
  $date_in = date('Y-m-d', strtotime($date_in));
  if($date_in > $vat_start){
  $vat_req 		= round((($net_cost - $deduction) * 0.05),2) ;
  $after_vat 	= $vat_req + $net_cost ;
  $wanted 		= round(($after_vat - $payed),2) ;
      if(!empty($date_in)){
          $vat_in = round((($payed * 5)/105),2) ;
            if($after_vat == $payed){ $vat_in = $vat_req ;}
      }
  } else {$wanted 		=	$net_cost - ( $payed + $deduction) ;}

  if($wanted == 0){$cont_status = 2 ;} else {$cont_status = 3 ;}

    $contt=$db->prepare(" UPDATE contracts SET date_in = ?, days_qty = ?, day_cost = ? , days_cost = ?,
                            km_in = ? , kilo_qty = ?, kilo_cost = ?, kilos_cost= ? , free_kilo =? ,
                            time_in = ? , hour_qty = ? , hour_cost = ?, hours_cost = ? , addtion_cost = ? , addtion_desc = ?,
      violations = ? , ins_claim = ? , net_cost = ?, total_in = ?, total_out = ?, deduction = ? , wanted = ?,cont_status = ? , comm = ?,
      closer = ?,audate = ? ,vat_req = ? , after_vat = ? , vat_in = ?  WHERE contract_id = ? ");
   $contt->bindParam(1,$date_in);
   $contt->bindParam(2,$days_qty);
   $contt->bindParam(3,$day_cost);
   $contt->bindParam(4,$days_cost);
   $contt->bindParam(5,$km_in);
   $contt->bindParam(6,$kilo_qty);
   $contt->bindParam(7,$kilo_cost);
   $contt->bindParam(8,$kilos_cost);
   $contt->bindParam(9,$free_kilo);
   $contt->bindParam(10,$time_in);
   $contt->bindParam(11,$hour_qty);
   $contt->bindParam(12,$hour_cost);
   $contt->bindParam(13,$hours_cost);
   $contt->bindParam(14,$addtion_cost);
   $contt->bindParam(15,$addtion_desc);
   $contt->bindParam(16,$violations);
   $contt->bindParam(17,$ins_claim);
   $contt->bindParam(18,$net_cost);
   $contt->bindParam(19,$total_in);
   $contt->bindParam(20,$total_out);
   $contt->bindParam(21,$deduction);
   $contt->bindParam(22,$wanted);
   $contt->bindParam(23,$cont_status);
   $contt->bindParam(24,$comm);
   $contt->bindParam(25,$father);
   $contt->bindParam(26,$audate);
   $contt->bindParam(27,$vat_req);
   $contt->bindParam(28,$after_vat);
   $contt->bindParam(29,$vat_in);
   $contt->bindParam(30,$contract_id);
   if($contt->execute()){
        $data["msg"] = "<div class='alert alert-success'>
              <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
              <b>تم إقفال العقد بنجاح ....</b>
              </div>" ;
  $car= $db->prepare("UPDATE cars set carstatus = 1 where carid=".$carid."");
  $car->execute();
  }
  else { $data["msg"] = "<div class='alert alert-danger'>
              <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
              <b>يوجد خطأ في تسجيل البيانات ... راجع  من فضلك</b>
              </div> " ;}
  }
  echo json_encode($data);
  }
  }
  if(isset($_POST["audate"])){
    $contract_id = $_POST["audate"];
    $au=$db->prepare(" UPDATE contracts SET printed = 1 WHERE contract_id = ? ");
    $au->bindParam(1,$contract_id);
    $au->execute();
  }

?>
