<?php
require_once ("varables.php");

$myJSON['message'] = "کمبود منابع";
$myJSON['mmm'] = array();

if(isset($_POST["kopn"]) && isset($_POST["nekot"]) && isset($_POST["admid"]) && isset($_POST["meta"]))
{
	$kopon =$_POST["kopn"];
	$toke =  $_POST["nekot"];
	$user_id =  $_POST["admid"];
	$postdata = $_POST["meta"];

	$meta = json_decode($postdata,true);

    $connect = @mysqli_connect($hostname,$username,$password,$database);
    if($connect)
    {
        @mysqli_query($connect,"SET CHARACTER SET utf8mb4;");
        $query_token = "SELECT id FROM ".$tbl_sessions." WHERE token = '".$toke."' AND uid ='".$user_id."' AND type ='A' LIMIT 1";
		$tokres=@mysqli_query($connect,$query_token);
        if (!$tokres) {
            $myJSON['message']= "400" ;

        }
		else{
			$countoft = 0;
            while($rowt = @mysqli_fetch_assoc($tokres)){
				array_push($myJSON['mmm'], $rowt);
                $countoft++;
			}
			if($countoft == 0){
				$myJSON['message']= "405" ;
			}
			else{
					$q = "SELECT * FROM tbl_kopon WHERE kopon = '".$kopon."' LIMIT 1";
					$res=@mysqli_query($connect,$q);
					if($res){
						$count = 0;
						while($row = @mysqli_fetch_assoc($res))
							$count++;
						if($count>0)
						{
						$myJSON['message']="کد تخفیف تکراریست...!";
						}
						else{
							$insert = "INSERT INTO tbl_kopon (kopon) VALUES ('".$kopon."')";
							$ires=@mysqli_query($connect,$insert);
							if($ires){
								$kid = @mysqli_insert_id($connect);
								for($j=0;$j<sizeof($meta);$j++){
									$insertmeta= "INSERT INTO tbl_kopon_meta (koponid,tag, value) 
									VALUES ('".$kid."','".$meta[$j]["tag"]."','".$meta[$j]["value"]."')";
									$metares=@mysqli_query($connect,$insertmeta);
									if(!$metares){
										$myJSON['message']="کد خطا 504". @mysqli_error($connect);
										break;
									}
									else{
										$myJSON['message'] = "200";
									}
								}
							}
							else{
								$myJSON['message']="کد خطا 505". @mysqli_error($connect);
							}
						}
					}
					else{
						$myJSON['message']="کد خطا 506". @mysqli_error($connect);
					}
			}
		}
	}
	 else
		 $myJSON['message']="خطای ارتباط با پایگاه داده...!";
}
    echo json_encode($myJSON);
?>
