<?php
require_once "../magic/session_config.php";
bdr_start_session();
ob_start();
$branch = $_SESSION["branch"];
$father = $_SESSION["user_id"];
include "dbPDO.php";
if($_POST['cust_id'] !=""){
    $rent_days   = $_POST["rent_days"];                $used_area     = $_POST["used_area"];
    $cust_id     = $_POST["cust_id"];                  $tamm_days     = $_POST["tamm_days"];
    $carid       = $_POST["carid"];
    $day_cost    = $_POST["day_cost"];                 $km_out        = $_POST["km_out"];
    $kilo_cost   = $_POST["kilo_cost"];                $free_kilo     = $_POST["free_kilo"];
    $comm        = $_POST["comm"];
    $cust_id2    = $_POST["cust_id2"];
    $after_vat   = $_POST["after_vat"];
    $start       = $_POST["start"] ;    $kest      = $_POST["kest"] ; 
    // sanad cash
    $printed_no  = $_POST["printed_no"];    $money_in   = $_POST["money_in"];      $payMethod = $_POST["payMethod"];
 
$data = array();
$error = array();

$Number = '/^[0-9]+(\.[0-9]{1,2})?$/' ;
if(empty($money_in)||empty($carid) || empty($cust_id)||empty($tamm_days) || empty($day_cost)|| empty($km_out)|| empty($after_vat))
    {  $error["msg22"] ="<div class='alert alert-danger'>
      <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
        <b>من فضلك سجل بيانات العقد كاملة ليتم حفظ العقد  </b>
      </div> " ;    }
    if(!empty($carid)){
      $sql = $db->prepare("SELECT monthly , freekilo , km2 , carstatus FROM cars WHERE carid = '$carid' LIMIT 1");
      $sql->execute();
      if($sql->rowCount()>0){$row = $sql->fetch(PDO::FETCH_ASSOC);
            $minn       = $row["monthly"];
            $freekilo   = $row["freekilo"];
            $km3        = $row["km2"];
            $carstatus  = $row["carstatus"];
          }
          if($carstatus != 1){exit() ;}
      if($day_cost < $minn){  $day_cost  = $minn ;}
      if($kilo_cost < $km3){  $kilo_cost = $km3 ;}
      if($free_kilo < $freekilo){  $free_kilo = $freekilo ;}
    }
if(!preg_match($Number,$tamm_days)){ $error["tamm_days"] = " أرقام فقط.." ;}
if(!preg_match($Number,$day_cost)){ $error["day_cost"] = "  أرقام صحيحة فقط.." ;}
if(!preg_match($Number,$km_out)){ $error["km_out"] = " أرقام فقط.." ;}
if(empty($money_in)){$money_in = "0";}
if(!preg_match($Number,$money_in)){ $error["money_in"] = "  أرقام صحيحة فقط.." ;}
if(empty($used_area)){$used_area = "جدة و مكة";}

if(!empty($used_area)){ $used_area = htmlspecialchars(strip_tags($used_area)) ;   }
if(empty($rent_days)){$rent_days = "يومين";}

if(!empty($rent_days)){ $rent_days = htmlspecialchars(strip_tags($rent_days)) ;   }
if(!empty($printed_no)){ $printed_no = htmlspecialchars(strip_tags($printed_no)) ;   }
if(!empty($comm)){ $comm = htmlspecialchars(strip_tags($comm)) ;   }
    // existing contract to current customer
    $sql = $db->prepare("SELECT dgree FROM customers  WHERE cust_id = ? LIMIT 1");
    $sql->bindParam(1,$cust_id);
    $sql->execute();
    if($sql->rowCount()>0){$row = $sql->fetch(PDO::FETCH_ASSOC);
      $dgree   = $row["dgree"];}
      if($dgree < 50){$error["comm"] = "مستاجر قائمة سوداء إنتبه من فضلك" ;}
$rent_days = "شهر";
if(!empty($error)){
  $data["error"] = $error ;
  }else {
  $maxCONT = "0";
            $maxsql= $db->prepare("SELECT max(contract_id) as maxd from aksat_contract");
            $maxsql->execute();
            if($maxsql->rowCount()>0){$row = $maxsql->fetch(PDO::FETCH_ASSOC);
              $maxCONT = $row['maxd']+1; }else{$maxCONT = 101  ;}
  $tamm_expire = date('Y-m-d', strtotime(' + '.$tamm_days.' days'));
    if(empty($cust_id2)){$cust_id2 = null ;}
    $time_out = date("H:i:s");

    $sql=$db->prepare(" INSERT INTO aksat_contract
        (contract_id , rent_days , used_area , cust_id ,tamm_expire , carid , day_cost , km_out , kilo_cost , free_kilo, comm ,
          cust_id2 , start , after_vat ,kest, branch  ,father,time_out,cost)
    VALUES (?, ?, ?, ?, ?, ? , ?, ?, ?, ?,  ?, ?, ?, ? , ?, ?, ?,?,?)");
      $sql->bindParam(1,$maxCONT);
      $sql->bindParam(2,$rent_days);
      $sql->bindParam(3,$used_area);
      $sql->bindParam(4,$cust_id);
      $sql->bindParam(5,$tamm_expire);
      $sql->bindParam(6,$carid);
      $sql->bindParam(7,$day_cost);
      $sql->bindParam(8,$km_out);
      $sql->bindParam(9,$kilo_cost);
      $sql->bindParam(10,$free_kilo);
      $sql->bindParam(11,$comm);
      $sql->bindParam(12,$cust_id2);
      $sql->bindParam(13,$start);
      $sql->bindParam(14,$after_vat);
      $sql->bindParam(15,$kest);
      $sql->bindParam(16,$branch);
      $sql->bindParam(17,$father);
      $sql->bindParam(18,$time_out);
      $sql->bindParam(19,$after_vat);
      if($sql->execute()){
  $data["contract_id"] = $maxCONT ;
  $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 = 2 where carid=".$carid."");
  $car->execute();
if($money_in > 0){
  $friest_pay = "دفعة أولي" ;
  $maxsql= $db->prepare("SELECT max(ak_id) as maxd FROM aksat_in");
  $maxsql->execute();
  if($maxsql->rowCount()>0){$row = $maxsql->fetch(PDO::FETCH_ASSOC);
      $maxD = $row['maxd']+1;} else {$maxD = 1 ; }
        $end   = date('Y-m-d', strtotime($start. ' + 1  month'));
        $end   = date('Y-m-d', strtotime($end. ' -1 days'));
      
  $sanad=$db->prepare(" INSERT INTO aksat_in(ak_id , contract_id , wanted ,  start ,endd,payed , date_payed , comm , father , branch , payMethod  )
   VALUES( ? , ? , ? , ?, ? , ? , ? ,?,?,?,?)");
   $sanad->bindParam(1,$maxD);
   $sanad->bindParam(2,$maxCONT);
   $sanad->bindParam(3,$money_in);
   $sanad->bindParam(4,$start);
   $sanad->bindParam(5,$end);
   $sanad->bindParam(6,$money_in);
   $sanad->bindParam(7,$start);
   $sanad->bindParam(8,$friest_pay);
   $sanad->bindParam(9,$father);
   $sanad->bindParam(10,$branch);
   $sanad->bindParam(11,$payMethod);
   if($sanad->execute()){
   $data["ak_id"] = $maxD ;
   $data["msg33"] = "<div class='alert alert-success'>
              <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
                <b> تم تسجيل السند بنجاح.. </b></div> ";
    $after_vat = $after_vat - $money_in ; $ak_no = 1 ; $maxD = $maxD+1 ;
      // $mon = 29 ; $last = 29 ;
    $sanad=$db->prepare(" INSERT INTO aksat_in(ak_id , ak_no ,contract_id , wanted ,  start ,endd )
     VALUES( ? , ? , ? , ?, ? , ? )");
     
       if(($after_vat > 0) && ($kest > 0)){
         //main aksat loop
  while($after_vat >= $kest){
        $start = date('Y-m-d', strtotime($start. ' + 1  month'));
        $end   = date('Y-m-d', strtotime($start. ' + 1  month'));
        $end   = date('Y-m-d', strtotime($end. ' -1 days'));
      
      $sanad->bindParam(1,$maxD);
      $sanad->bindParam(2,$ak_no);
      $sanad->bindParam(3,$maxCONT);
      $sanad->bindParam(4,$kest);
      $sanad->bindParam(5,$start);
      $sanad->bindParam(6,$end);
      $sanad->execute() ;
      $maxD = $maxD+1 ; $ak_no = $ak_no + 1 ;
      $after_vat = $after_vat - $kest ;
    }//
    //end of main aksat loop
    //last kest
     if(($after_vat > 0 )&&($after_vat < $kest )){
       $last_pay = "دفعة اخيرة";
      $sanad=$db->prepare(" INSERT INTO aksat_in(ak_id , ak_no ,contract_id , wanted ,  start ,endd , comm )
       VALUES( ? , ? , ? , ?, ? , ? ,?)");
      
        $start = date('Y-m-d', strtotime($start. ' + 1  month'));
        $end = date('Y-m-d', strtotime($start. ' + 1  month'));
        $end   = date('Y-m-d', strtotime($end. ' -1 days'));
      
      $sanad->bindParam(1,$maxD);
      $sanad->bindParam(2,$ak_no);
      $sanad->bindParam(3,$maxCONT);
      $sanad->bindParam(4,$after_vat);
      $sanad->bindParam(5,$start);
      $sanad->bindParam(6,$end);
      $sanad->bindParam(7,$last_pay);
      $sanad->execute() ;
    }
  }
    else //change contract to tashgheel
    {
      $sql = $db->prepare(" UPDATE aksat_contract set status = 3 where contract_id = ?");
      $sql->bindParam(1,$maxCONT);
      $sql->execute();
           $maxsql= $db->prepare("SELECT max(tash_id) as maxd FROM tash_in");
           $maxsql->execute();
         if($maxsql->rowCount()>0){$row = $maxsql->fetch(PDO::FETCH_ASSOC);
           $maxD = $row['maxd']+1;} else {$maxD = 1 ; }
           $ww = $db->prepare("SELECT tash FROM aksat_contract where contract_id = ?");
           $ww->bindParam(1,$maxCONT);
           $ww->execute();
         if($ww->rowCount()>0){$w = $ww->fetch(PDO::FETCH_ASSOC);
           $wanted = $w['tash'] ;}
 $start = date('Y-m-d', strtotime($start. ' + 3 month'));
 $endd  = date('Y-m-d', strtotime($start. ' - 1 days'));
 $endd  = date('Y-m-d', strtotime($endd. ' + 1 month'));
 $new_tash = $db->prepare("INSERT INTO tash_in(tash_id, contract_id, wanted, start, endd)
                                 values(?,?,?,?,?)");
      $new_tash->bindParam(1,$maxD);
      $new_tash->bindParam(2,$maxCONT);
      $new_tash->bindParam(3,$wanted);
      $new_tash->bindParam(4,$start);
      $new_tash->bindParam(5,$endd);
      $new_tash->execute();
    }
  
              }
      else{ $data["msg33"] = "<div class='alert alert-danger'>
                    <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
                    <b>يوجد خطأ في تسجيل البيانات ... راجع  من فضلك</b></div>  ";}
  }else{$data["ak_id"] = 0 ;}
}
 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);
}
?>
