<?php
require_once "../magic/session_config.php";
bdr_start_session();
// ob_start();
if(!isset($_SESSION["user_id"])){header("location:../logout.php");}
// $branch = $_SESSION["branch"];
$father = $_SESSION["user_id"];
$time_out = date("H:i:s");
$date_out = date("Y-m-d");

require_once "../magic/DataBase.php";
$database = new DataBase();

$conn = $database->getConnection();

// $log = new Log($conn,$contract_id,$father,$branch);
if ($_POST['cust_id'] != "") {
  // $days_wanted = $_POST["days_wanted"];
  $used_area   = $_POST["used_area"];
  $cust_id     = $_POST["cust_id"];
  if(isset($_POST["rent_days"])){
 $rent_days   = $_POST["rent_days"];
  }else{
     $rent_days   = "أسبوع";
  }
 

  //  $tamm_code     = $_POST["tamm_code"];  
  $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"];
  $open_comm   = $_POST["open_comm"];
  $cust_id2    = $_POST["cust_id2"];
  // sanad cash
  $sanad_comm  = $_POST["sanad_comm"];
  $money_in    = $_POST["money_in"];
  $payMethod    = $_POST["payMethod"];
  $data = array();
  $error = array();

  require_once "../op/log.php";

  $Number = '/^[0-9]+(\.[0-9]{1,2})?$/';
  if (empty($money_in) || ($money_in < 0)) {
    $money_in = 0;
  }
  if (empty($carid) || empty($cust_id) || empty($tamm_days) || empty($day_cost) || empty($km_out)) {
    $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 = $conn->prepare("SELECT monthly , freekilo , km2 , carstatus , branch , area 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"];
      $branch     = $row["branch"];
      $area       = $row["area"];
    }
    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 = htmlspecialchars(strip_tags($used_area));
  } else {
    $used_area = "جدة و مكة";
  }
  // if (!empty($days_wanted)) {
  //   if (!preg_match($Number, $days_wanted)) {
  //     $error["days_wanted"] = " أرقام فقط..";
  //   }
  // } else {
  //   $days_wanted = 3 ;
  // }

  if (!empty($sanad_comm)) {
    $sanad_comm = htmlspecialchars(strip_tags($sanad_comm));
  }else{$sanad_comm = null;}

  if (!empty($open_comm)) {
    $open_comm = htmlspecialchars(strip_tags($open_comm));
  }else{$open_comm = null;}
  if(empty($cust_id2)){$cust_id2 = null ;}
  // existing contract to current customer
  $sql = $conn->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["open_comm"] = "مستاجر قائمة سوداء إنتبه من فضلك";
  }

  if (!empty($error)) {
    $data["error"] = $error;
  } else {
    // to make unique contarcts serials to every branch
    $maxCONT = "0";
    $maxsql = $conn->prepare("SELECT max(contract_id) as maxd FROM contracts where open_at = ?");
    $maxsql->bindParam(1, $branch);
    $maxsql->execute();
    if ($maxsql->rowCount() > 0) {
      $row = $maxsql->fetch(PDO::FETCH_ASSOC);
      $maxCONT = $row['maxd'];
     
      if (empty($maxCONT)) {
            // if($branch > 10){
            //    $maxCONT= 1 ;
            // }else{
            // $maxCONT = (($branch * 100000) - 99999);
            // }
       $maxCONT = 1;
      } else {
        $maxCONT = $maxCONT + 1;
      }
    }
    $payFor = "1";
    $cont_status = 1;
    $days_wanted = $tamm_days;
    $tamm_expire = date('Y-m-d', strtotime(' + ' . $tamm_days . ' days'));
    $hour_cost   = round(($day_cost /12),2);

    $sql=$conn->prepare(" INSERT INTO contracts
        (contract_id , days_wanted , used_area , cust_id , tamm_expire , carid , day_cost , km_out , kilo_cost , free_kilo, open_comm ,
          cust_id2 , cont_status , time_out , date_out  ,hour_cost , branch  ,father, open_at , rent_days	)
    VALUES (?, ?, ?, ?, ?,   ? , ?, ?, ?, ?,  ?, ?, ?, ?, ?  ,?, ?, ?,? , ?)");
    $sql->bindParam(1,$maxCONT);
    $sql->bindParam(2,$days_wanted);
    $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,$open_comm);
    $sql->bindParam(12,$cust_id2);
    $sql->bindParam(13,$cont_status);
    $sql->bindParam(14,$time_out);
    $sql->bindParam(15,$date_out);
    $sql->bindParam(16,$hour_cost);
    $sql->bindParam(17,$area);
    $sql->bindParam(18,$father);
    $sql->bindParam(19,$branch);	
    $sql->bindParam(20,$branch);
    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>";
      $log = new Log($conn, $maxCONT, $father, $branch);
      $log->newCont($carid);
      $car = $conn->prepare("UPDATE cars set carstatus = 2 where carid=" . $carid . "");
      $car->execute();

      $back = $conn->prepare("INSERT INTO contractsback(father, contract_id, day_cost, kilo_cost)
                        VALUES  (?,?,?,?)");
      $back->bindParam(1, $father);
      $back->bindParam(2, $maxCONT);
      $back->bindParam(3, $day_cost);
      $back->bindParam(4, $kilo_cost);
      $back->execute();

      if ($money_in > 0) {
        $maxsql = $conn->prepare("SELECT max(in_id) as maxd FROM invoice");
        $maxsql->execute();
        if ($maxsql->rowCount() > 0) {
          $row = $maxsql->fetch(PDO::FETCH_ASSOC);
          $maxD = $row['maxd'] + 1;
        } else {
          $maxD = 1;
        }
        $sanad = $conn->prepare(" INSERT INTO invoice(in_id , contract_id , comm , sanad_date , money_in , payMethod ,payFor, father , branch  )
                      VALUES( ? , ? , ? , ? , ? , ? , ? ,?, ?)");
        $sanad->bindParam(1, $maxD);
        $sanad->bindParam(2, $maxCONT);
        $sanad->bindParam(3, $sanad_comm);
        $sanad->bindParam(4, $date_out);
        $sanad->bindParam(5, $money_in);
        $sanad->bindParam(6, $payMethod);
        $sanad->bindParam(7, $payFor);
        $sanad->bindParam(8, $father);
        $sanad->bindParam(9, $branch);
        if ($sanad->execute()) {
          $data["in_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> ";
        } 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["in_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);
}
// echo json_encode($data);
