<?php
require_once "../magic/session_config.php";
bdr_start_session();
ob_start();
if(!isset($_SESSION["user_id"])){header("location:../logout.php");}
include "../actions/dbPDO.php";
include "../op/close_up.php";
include_once('../op/contractHistory.php');

  $branch = $_SESSION["branch"];
  $father = $_SESSION["user_id"];
  $sanad_date = date("Y-m-d");

if(isset($_POST["carid"])){
    if($_POST['contract_id'] !=""){
          $contract_id   = $_POST['contract_id'];
          $day_cost      = $_POST['day_cost'];
          $km_in         = $_POST['km_in'];
          $time_in       = $_POST['time_in'];
          $date_in       = $_POST['date_in'];
          $kilo_cost     = $_POST['kilo_cost'];
          $free_kilo     = $_POST['free_kilo'];
          $addtion_cost  = $_POST['addtion_cost'];
          $addtion_desc  = $_POST['addtion_desc'];
          $dept_comm     = $_POST['dept_comm'];
          $violations    = $_POST['violations'];
          $ins_claim     = $_POST["ins_claim"];
        if(isset($_POST["km_out"])){
            $km_out        = $_POST['km_out'];
          } 
          $hour_cost     = round(($day_cost /12),2);
          $deduction     = $_POST["deduction"];
        if(isset($_POST["comm"])){
            $comm          = $_POST["comm"];
          } 
         
$contHistory = new  ContHistory($db,$contract_id,$father) ;
// $name ='/^[-a-zA-Z0-9_\p{Arabic}-+ـ\s]*$/u';
$Number ="/^[0-9]+$/";
$dc ='/^[0-9]+(\.[0-9]{1,2})?$/' ;

$data = array();
$error = array();

if(empty($day_cost)){  $error["day_cost"] = "من فضلك سجل إيجار اليوم "; }
      if(!preg_match($dc,$day_cost)){ $error["day_cost"] = "من فضلك تأكد من رقم المبلغ" ;}
  if(empty($free_kilo))
          {
            $error["free_kilo"] = "من فضلك سجل الكيلو المسموح";
          }
        if(!preg_match($Number,$free_kilo)){ $error["free_kilo"] = "أرقام فقط" ;}

        $kilo_cost = htmlspecialchars(strip_tags($kilo_cost)) ;
if($kilo_cost < 0){
  $kilo_cost  = 0; 
} 

    if(!empty($km_in)){
       if(!preg_match($Number,$km_in)){ $error["km_in"] = "أرقام صحيحة فقط" ;}
      }else{$km_in = null;}
    if(!empty($addtion_cost)){ if(!preg_match($dc,$addtion_cost)){ $error["addtion_cost"] = "أرقام صحيحة فقط" ;}}else{$addtion_cost = 0;}
    if(!empty($dept_comm))  { $dept_comm = htmlspecialchars(strip_tags($dept_comm)) ;}else{$dept_comm = null ; }
    if(!empty($violations))    { if(!preg_match($Number,$violations)){ $error["violations"] = "أرقام صحيحة فقط" ;}}else{$violations = 0 ;}
    if(!empty($ins_claim))     { if(!preg_match($Number,$ins_claim)){ $error["ins_claim"] = "أرقام صحيحة فقط" ;}}else{$ins_claim = 0;}
    if(!empty($deduction))     { if(!preg_match($dc,$deduction)){ $error["deduction"] = "أرقام فقط" ;}}else{$deduction = 0;}
if(!empty($addtion_desc)){  $addtion_desc = htmlspecialchars(strip_tags($addtion_desc)) ;}else{$addtion_desc = null;}
if(!empty($comm)){  $comm = htmlspecialchars(strip_tags($comm)) ;}else{$comm = null ;}

// if(!isset($km_out)){
//       $ksql =$db->prepare("SELECT km_out from contracts where contract_id = ?");
//       $ksql->bindParam(1,$contract_id);
//       $ksql->execute();
//   if($ksql->rowCount()>0){$kk = $ksql->fetch(PDO::FETCH_ASSOC);
//     $km_out = $kk['km_out'];}
// }

if(!empty($error)){
  $data["error"] = $error ;
}else {
  if(empty($date_in)){
      if(!isset($km_out)){
             $contt = $db->prepare(" UPDATE contracts SET day_cost = ? , km_in = ? , kilo_cost = ? , free_kilo =? , addtion_cost = ? , addtion_desc = ?,
      violations =? ,dept_comm = ? , ins_claim = ? ,comm = ? , deduction = ? ,hour_cost = ?  WHERE contract_id = ? ");
   $contt->bindParam(1,$day_cost);
   $contt->bindParam(2,$km_in);
   $contt->bindParam(3,$kilo_cost);
   $contt->bindParam(4,$free_kilo);
   $contt->bindParam(5,$addtion_cost);
   $contt->bindParam(6,$addtion_desc);
   $contt->bindParam(7,$violations);
   $contt->bindParam(8,$dept_comm);
   $contt->bindParam(9,$ins_claim);
   $contt->bindParam(10,$comm);
   $contt->bindParam(11,$deduction);
   $contt->bindParam(12,$hour_cost);
  //  $contt->bindParam(13,$km_out);
   $contt->bindParam(13,$contract_id);
      }
      else{
             $contt = $db->prepare(" UPDATE contracts SET day_cost = ? , km_in = ? , kilo_cost = ? , free_kilo =? , addtion_cost = ? , addtion_desc = ?,
      violations =? ,dept_comm = ? , ins_claim = ? ,comm = ? , deduction = ? ,hour_cost = ? ,km_out =? WHERE contract_id = ? ");
   $contt->bindParam(1,$day_cost);
   $contt->bindParam(2,$km_in);
   $contt->bindParam(3,$kilo_cost);
   $contt->bindParam(4,$free_kilo);
   $contt->bindParam(5,$addtion_cost);
   $contt->bindParam(6,$addtion_desc);
   $contt->bindParam(7,$violations);
   $contt->bindParam(8,$dept_comm);
   $contt->bindParam(9,$ins_claim);
   $contt->bindParam(10,$comm);
   $contt->bindParam(11,$deduction);
   $contt->bindParam(12,$hour_cost);
    $contt->bindParam(13,$km_out);
   $contt->bindParam(14,$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>" ; 
        
    $check_new = $contHistory->checkHistory($day_cost,$kilo_cost,$addtion_cost,$violations,$ins_claim,$deduction);     
    if($check_new){
      $contHistory->create($day_cost,$kilo_cost,$addtion_cost,$violations,$ins_claim,$deduction,$father);
    }
          }

 else{ $data["msg"] = "<div class='alert alert-danger'>
            <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
            <b>يوجد خطأ في تسجيل البيانات 22 ... راجع  من فضلك</b></div> " ; }
  }else{

 // do close contract if wanted Zero
 
    $contt=$db->prepare(" UPDATE contracts SET day_cost = ? , km_in = ? , kilo_cost = ? , free_kilo =? , addtion_cost = ? , addtion_desc = ?,
      violations =? ,dept_comm = ? , ins_claim = ? ,comm = ? , deduction = ? , date_in = ? , time_in = ?  WHERE contract_id = ? ");
   $contt->bindParam(1,$day_cost);
   $contt->bindParam(2,$km_in);
   $contt->bindParam(3,$kilo_cost);
   $contt->bindParam(4,$free_kilo);
   $contt->bindParam(5,$addtion_cost);
   $contt->bindParam(6,$addtion_desc);
   $contt->bindParam(7,$violations);
   $contt->bindParam(8,$dept_comm);
   $contt->bindParam(9,$ins_claim);
   $contt->bindParam(10,$comm);
   $contt->bindParam(11,$deduction);
   $contt->bindParam(12,$date_in);
   $contt->bindParam(13,$time_in);
   $contt->bindParam(14,$contract_id);
   if($contt->execute()){
      auto_close($db,$contract_id) ;
 $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>" ;
          }
 else{ $data["msg"] = "<div class='alert alert-danger'>
            <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
            <b>يوجد خطأ في تسجيل البيانات 33... راجع  من فضلك</b>
            </div> " ; }
}}
echo json_encode($data);
}
}

//add second custmoers to the current contract
if(isset($_POST["cust_id2"])){
  $contract_id   = $_POST['contract_id'];
  $cust_id2      = $_POST['cust_id2'];

$contt=$db->prepare(" UPDATE contracts SET cust_id2 =?  WHERE contract_id = ? ");
 $contt->bindParam(1,$cust_id2);
 $contt->bindParam(2,$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>" ;
$data["contract_id"]= $contract_id ;
}
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);
}
//replace customer company
if(isset($_POST["company"])){
  $contract_id   = $_POST['company'];

$sql = $db->prepare("SELECT cust_id , cust_id2 from contracts where contract_id = ?");
$sql->bindParam(1,$contract_id);
$sql->execute();
$contract = $sql->fetch(PDO::FETCH_ASSOC);
    $cust_id = $contract["cust_id"] ;
    $cust_id2 =  $contract["cust_id2"];

    if($cust_id2 < 1){
      $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> " ; 
      exit;
    }else{
      $contt=$db->prepare(" UPDATE contracts SET cust_id = ? ,cust_id2 =?  WHERE contract_id = ? ");
      $contt->bindParam(1,$cust_id2);
      $contt->bindParam(2,$cust_id);
      $contt->bindParam(3,$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>" ;
     $data["contract_id"]= $contract_id ;
     }
     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);
    }



}
//change current contract branch
if(isset($_POST["branch"])){
  $contract_id        = $_POST['contract_id'];
  $current_branch     = $_POST['branch'];
  $carid              = $_POST['carid'];
  $date_in            = $_POST['date_in'];

  $contt=$db->prepare(" UPDATE contracts SET branch =?  WHERE contract_id = ? ");
 $contt->bindParam(1,$current_branch);
 $contt->bindParam(2,$contract_id);
 if($contt->execute()){

   if(empty($date_in)){
      $car=$db->prepare(" UPDATE cars SET branch = ?  WHERE carid = ? ");
      $car->bindParam(1,$current_branch);
      $car->bindParam(2,$carid);
      $car->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>" ;
// $data["contract_id"]= $contract_id ;
}
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["tamm_expire"])){
  $contract_id      = $_POST['contract_id'];
  $tamm_expire      = $_POST['tamm_expire'];

$contt=$db->prepare(" UPDATE contracts SET tamm_expire =?  WHERE contract_id = ? ");
 $contt->bindParam(1,$tamm_expire);
 $contt->bindParam(2,$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>" ;
}
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["used_area"])){
  $contract_id    = $_POST['contract_id'];
  $used_area      = $_POST['used_area'];
  $rent_days      = $_POST['rent_days'];
  $free_dd        = $_POST['free_dd'];
  $tamm           = $_POST['tamm'];

      // $name ='/^[-a-zA-Z0-9_\p{Arabic}-+ـ\s]*$/u';
      // $Number ="/^[1-9]\d*(\.\d+)?$/";
      $Number ="/^[0-9]+$/";

  $data = array();
  $error = array();

    if(empty($used_area)||empty($rent_days)){  $error["used_area"] = "من فضلك سجل منطقة الإستخدام و مدة العقد ليتم الحفظ  "; }
    $used_area = htmlspecialchars(strip_tags($used_area)) ;
    $rent_days = htmlspecialchars(strip_tags($rent_days)) ;
    if(!empty($free_dd)){
    if(!preg_match($Number,$free_dd)){ $error["free_dd"] = "أرقام صحيحة فقط..";}
        }else{$free_dd = 0;}
    if(!empty($tamm)){
        if(!preg_match($Number,$tamm)){ $error["tamm"] = "أرقام صحيحة فقط..";}
         }else{$tamm = 0;}
  if(!empty($error)){
    $data["error"] = $error ;
  }else {
    // include "../actions/dbPDO.php";
    $contt=$db->prepare(" UPDATE contracts SET used_area = ? , rent_days = ? , free_dd = ? ,tamm = ? WHERE contract_id = ? ");
 $contt->bindParam(1,$used_area);
 $contt->bindParam(2,$rent_days);
 $contt->bindParam(3,$free_dd);
 $contt->bindParam(4,$tamm);
 $contt->bindParam(5,$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>" ;
            }
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);
}
// chan contracts state from ساري مغلق مديون محكمة محامي
if(isset($_POST["state"])){
  $contract_id      = $_POST['id'];
  $cont_status      = $_POST['state'];
  if($cont_status == 4){
    $cont_status = 3 ;
  }else{
    $cont_status = 4 ;
  }

$contt=$db->prepare(" UPDATE contracts SET cont_status = ?  WHERE contract_id = ? ");
 $contt->bindParam(1,$cont_status);
 $contt->bindParam(2,$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>" ;
}
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["state5"])){
  $contract_id      = $_POST['id'];
$contt=$db->prepare(" UPDATE contracts SET cont_status = 5  WHERE contract_id = $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>" ;
}
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);
}
?>
