<?php
require_once "../magic/session_config.php";
bdr_start_session(); 
ob_start();
if (!isset($_SESSION["user_id"])) {  header("location:../../logout.php"); }


require_once "../magic/DataBase.php";
require_once "../magic/Whats.php";
require_once "../op/close_up.php";
require_once "../op/log.php";

  $branch     = $_SESSION["branch"];
  $father     = $_SESSION["user_id"];
  $sanad_date = date("Y-m-d");
   $contract_id   = $_POST['id2'];
    $money_in      = $_POST['money_in'];
    $payMethod     = $_POST['payMethod'];
    $comm          = $_POST['comm2'];

if(isset($_POST['id2'])){

$data = array();

$dataBase = new DataBase();
	$conn = $dataBase->getConnection();

$Number = '/^[0-9]+(\.[0-9]{1,2})?$/' ;
if(empty($father)){
    return;
}

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

if(!empty($error)){
  $data["error"] = $error ;
}else {
  $maxN = $conn->prepare("SELECT max(in_id) as maxd , max(audate) as time1 FROM invoice where contract_id = ? AND branch = ?");
  $maxN->bindParam(1,$contract_id) ;
  $maxN->bindParam(2,$branch) ;
  $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["in_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();
    }
  }
  $payType  = "كاش";
   switch ( $payMethod) {
            case '1':      $payType  = "كاش";         break;
            case '2':      $payType  = "تحويل الراجحي";  break;
            case '3':      $payType  = "نقاط بيع";    break;
            case '4':      $payType  = "فواتير";      break;
            case '5':      $payType  = "تحويل الاهلي";  break;
        }

        $payFor = "1";
        $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 ; }
   $money_in = round($money_in , 2);
  $sanad=$conn->prepare(" INSERT INTO invoice(in_id , contract_id , sanad_date , money_in , payMethod ,
          payFor , comm , father , branch  )
     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,$payFor);
   $sanad->bindParam(7,$comm);
   $sanad->bindParam(8,$father);
   $sanad->bindParam(9,$branch);
if($sanad->execute()){
  $data["in_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>" ;
$whats = new Whats();
//  $whats->updateSent(1);
$whats->insert((int) $contract_id, (int) $maxD, $money_in);
// sleep(1);
  if($payMethod > 1){
    $log = new Log($conn,$contract_id,$father,$branch);
    $log->sanadPOS($maxD,$money_in,$payMethod);
               }
  auto_close($conn,$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);
}

// send whatss
// require_once "../magic/Whats.php";
// if(isset($_POST['in_id'])){
//     $branch     = $_SESSION["branch"];
//     $contract_id   = $_POST['contract_id'];

//  $whats = new Whats();
//  $invoice_id = $_POST['in_id'];
//  $msg = "
//         عميلنا العزيز \n

// نشكر لك سدادك لمبلغ تأجير السيارة وقدره $money_in ريال سعودي ، تم تأكيد استلام المبلغ بنجاح. \n

// مع تحياتنا،\n
// شركة الوسام لتأجير السيارات\n


// Dear Customer,\n

// Thank you for completing your car rental payment of SAR $money_in.\n
// The payment has been successfully received.\n

// Best regards,\n
// Al Wisam Car Rental Company\n";
// // sendText($msg,$contract_id ,$invoice_id , $branch)
//   $whats->hossamSend($msg,$contract_id , $invoice_id , $branch);

// }

