<?php
session_start();
ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1); 
error_reporting(1); 



header("Content-Type: application/json;charset=utf-8"); 
include('conf.php');

//include("injection.php");
//include("encrypt.php");


mysqli_query($conn,"SET NAMES 'utf8'");
mysqli_query($conn,'SET CHARACTER SET utf8');
mysqli_query($conn,"SET character_set_client=utf8");
mysqli_query($conn,"SET character_set_connection=utf8");
mysqli_query($conn,"SET character_set_database=utf8");
mysqli_query($conn,"SET character_set_results=utf8");
mysqli_query($conn,"SET character_set_server=utf8");
mysqli_query($conn,"set character_set_server='utf8'"); 
	$new_id=0;
	$user_id='1';
	$table='form_options';
	$operation='insert_ques';
	$auth_check='user_insert';
	$token = null;
	$status='';
	$affected_rows=0;
	$error_arr=[];
	$error_database_arr=[];
	$user_auth='';
	$data_array = array();
	$headers = apache_request_headers();
	$new_id='';
	
	
	//include "auth.php";
	//if($auth_errors==1){
	//   goto to_result;
	//}
	$raw_data = file_get_contents('php://input');
	$post_data = json_decode($raw_data, true);
		
	//$post_data['id']=str_replace(' ','+',$post_data['id']);
	//$post_data['id']=decrypt_dynamic($post_data['id'],$headers['Authorization']);
	$created=date('Y-m-d H:i:s');

	
	//استدعاء ملف تخزين اللوجز والحماية من الاسبام	
	include "spam_logs.php";
	
	//استدعاء ملف التحقق من المدخلات وكشف التلاعب
	include 'purifier.php';

	
	

	

	
	//if(filter_var($post_data["option_text"], FILTER_VALIDATE_REGEXP, $text_regex) === false || $post_data["option_text"]=='' ){array_push($error_arr,'خطأ فى عنوان السؤال');$status='not_done';$message='خطأ فى المدخلات';goto to_result;}
      
	 
	  
	  //حقول الزامية
	  $post_data["option_text"] = $purifier->purify($post_data["option_text"]);if( $post_data["option_text"]=='' ){array_push($error_arr,'خطأ فى عنوان السؤال');$status='not_done';$message='خطأ فى المدخلات';goto to_result;}
	  if(filter_var($post_data["option_answer"], FILTER_VALIDATE_INT )=== false || $post_data["option_answer"]==''){array_push($error_arr,'خطأ فى الاجابة');$status='not_done';$message='خطأ فى المدخلات';goto to_result;}
	  if(filter_var($post_data["ques_id"], FILTER_VALIDATE_INT )=== false || $post_data["ques_id"]==''){array_push($error_arr,'خطأ فى لرقم السؤال');$status='not_done';$message='خطأ فى المدخلات';goto to_result;}
 	  if(filter_var($post_data["option_dgree"], FILTER_VALIDATE_FLOAT )=== false || $post_data["option_dgree"]==''){array_push($error_arr,'خطأ فى حقل درجة السؤال');$status='not_done';$message='خطأ فى المدخلات';goto to_result;}
 

	  
	  //حقول غير الزامية
	  
	  $post_data["option_images"] = $purifier->purify($post_data["option_images"]);
	  if(filter_var($post_data["option_conditions"], FILTER_SANITIZE_URL )=== false && $post_data["option_conditions"]!='' ){array_push($error_arr,'خطأ فى الفيديوهات');$status='not_done';$message='خطأ فى الشروط';goto to_result;}



	 
	 if(count($error_arr) == 0){
		  //echo 'validatation success';
		mysqli_autocommit($conn, false);
		
		$sqlSort = "SELECT IFNULL(MAX(option_sort),0) + 1 AS next_sort FROM `$table` WHERE ques_id=?";
		$stmtSort = mysqli_prepare($conn, $sqlSort);
		mysqli_stmt_bind_param($stmtSort, 'i', $post_data['ques_id']);
		mysqli_stmt_execute($stmtSort);
		$result = mysqli_stmt_get_result($stmtSort);
		$row = mysqli_fetch_assoc($result);
		$row = clean_array($row);
		$next_sort = $row['next_sort'];



		  
		  $query = mysqli_prepare(
			$conn,
			    "INSERT INTO `$table`
				( `ques_id`,`option_text`,  `option_answer`, `option_dgree`, `images`, `conditions`, `created`, `created_user`, `option_sort`)
				VALUES
				(? , ?, ?, ?, ?, ?, ?, ?,?
					
				)"
			);
		
			mysqli_stmt_bind_param($query,'isidsssii',
			$post_data['ques_id'],$post_data['option_text'],$post_data['option_answer'],$post_data['option_dgree'],$post_data['option_images'],$post_data['option_conditions'],$created,$user_id,$next_sort
			);
			
			$run=mysqli_stmt_execute($query);
			 
			 if(mysqli_error($conn)!=''){
				 $error_database_arr['err']=mysqli_error($conn);
				 $error_database_arr['err_num']= mysqli_errno($conn);
				 $error_database_arr['error_stmt']= mysqli_stmt_error($query);
			 }

			$affected_rows=mysqli_affected_rows($conn);

			if(mysqli_stmt_affected_rows($query)){
				
				
				
				
				if($run && $affected_rows>0){
					$new_id = mysqli_insert_id($conn);
					
					if(mysqli_commit($conn)){
						$status='done';
						$message='تم الارسال بنجاح';
						mysqli_autocommit($conn, true);
						log_request($conn, $new_id, $user_id, $operation, $post_data, 'success');	
					
					}else{
						mysqli_rollback($conn);
						$status='not_done';
						$message='حدث خطأ أثناء معالجة البيانات';
					}



					
				}else{
					

					if(count($error_database_arr) == 0){
					
						$status='not_done';
						$message='لم يتم ادخال البيانات . ربما تكون مكررة';
					}else{
											
						$status='not_done';
						$message='لم يتم ادخال البيانات . ربما هناك خطأ فى محتوى الحقل <br/>'.$error_database_arr['err'];	
						
					}
				}
			}else{
				
				$status='not_done';
				$message='خطأ فى كود الادخال';
			}
			  
		 }else{
			  $status='not_done';
			  $message='خطأ فى البيانات';
			  //print_r($error_arr);
		 }
	  
	  
	to_result:

	$result = array(
		//'token' => $token,
		'status' => $status,
		'message' => $message,
		'affected_rows'=>$affected_rows,
		'errors' => $error_arr,
		'errors_database' => $error_database_arr,
		'structure' => $table,
		'reload' => 'true',
		'new_id'=>$new_id,
		'current_text'=> $post_data['option_text'],
		'current_answer'=> $post_data['option_answer'],
		'current_dgree'=> $post_data['option_dgree'],
		'current_images'=> $post_data['option_images'],
		'current_conditions'=> $post_data['option_conditions']

	);


echo json_encode($result,JSON_UNESCAPED_UNICODE);

 
	  
	  

?>