<?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"];
  $sanad_date = date("Y-m-d");

if($_POST['id2']  !=""){
    $contract_id   = $_POST['id2'];
    $money_in      = $_POST['money_in'];
    $payMethod     = $_POST['payMethod'];
    $comm          = $_POST['comm2'];

$data = array();
include "../actions/dbPDO.php";
$Number = '/^[0-9]+(\.[0-9]{1,2})?$/' ;

if(empty($money_in))
    {
      $error["money_in"] = "من فضلك سجل المبلغ ليتم حفظ السند ";
    }
      if(!preg_match($Number,$money_in)){ $error["money_in"] = "من فضلك تأكد من رقم المبلغ" ;}
    if(!empty($comm)){ $comm = htmlspecialchars(strip_tags($comm)) ;   }

if(!empty($error)){
  $data["error"] = $error ;
}else {
  $maxN = $db->prepare("SELECT max(sanad_id) as maxd , max(audate) as time1 FROM courts_in");
  $maxN->execute();
  if($maxN->rowCount()>0){$row = $maxN->fetch(PDO::FETCH_ASSOC);
    $maxIN = $row['maxd'];}
    if(!empty($maxIN)){
    $start = strtotime($row['time1']);
    $date_today = date("Y-m-d H:i:s");
    $end = strtotime($date_today);
    // $end = $end + 3600 ;
    $mano =   $end -$start  ;
    if($mano < 30){
      $data["sanad_id"] = $maxIN ;
      $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>" ;
          echo json_encode($data);
          exit();
    }
  }
        $maxsql= $db->prepare("SELECT max(sanad_id) as maxd FROM courts_in");
        $maxsql->execute();
        if($maxsql->rowCount()>0){$row = $maxsql->fetch(PDO::FETCH_ASSOC);
          $maxD = $row['maxd']+1;} else {$maxD = 1 ; }
   $money_in = round($money_in , 2);
  $sanad=$db->prepare(" INSERT INTO courts_in(sanad_id , contract_id , sanad_date ,
                   money_in , payMethod , comm , father )
              VALUES( ? , ? , ? , ? , ? , ? , ? )");
   $sanad->bindParam(1,$maxD);
   $sanad->bindParam(2,$contract_id);
   $sanad->bindParam(3,$sanad_date);
   $sanad->bindParam(4,$money_in);
   $sanad->bindParam(5,$payMethod);
   $sanad->bindParam(6,$comm);
   $sanad->bindParam(7,$father);   
if($sanad->execute()){
  $data["sanad_id"] = $maxD ;
  $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);
}
?>