<?php
session_start();
if(isset($_SESSION['user_id']) && isset($_SESSION['user_name']) && $_SESSION['user_cate'] === "vendor"){
        $user_id = $_SESSION['user_id'] ;
        $username = $_SESSION['user_name'] ;
        $ticket = $_SESSION['last_ticket'] ;
        $company = $_SESSION['company'] ;
        $vendor_image = $_SESSION['vendor_image'] ;
    }else{
        header("Location:vendor_login.php") ;
}
$msg = "";
include('Admin/config/setup.php');
require('config.php');
require('razorpay-php/Razorpay.php');
use Razorpay\Api\Api;
$year = date("Y");
$startdate = $year."-01-01";
$enddate = $year."-12-31";

// $newsql = "SELECT * FROM user WHERE userid='$userid'";
// $newquery=mysqli_query($conn, $newsql);
// while( $row=mysqli_fetch_array($newquery) ) {
// 	$email = $row["email"];
// 	$mobile = $row["mobile"];
// }

$action = $_POST['action'];
if($action == "buy_pack"){
    $user_id = $_POST['userId'];
    $id = 1;
    // $ticket = $_POST['ticket'];
    $order_date = date("Y-m-d H-i-s");
    $rid = $_POST['rid'];
    // $tran_id = $_POST['tran_id'];
    $name = $username ;
    $ven_sql = $config->query("SELECT * FROM master_login WHERE Master_id = '$user_id' ");
    $ven_res = $ven_sql->fetch_assoc();
    $email = $ven_res['Master_Username'] ;
    $mobile = $ven_res['Master_phone'] ;
    $pack_sql = $config->query("SELECT * FROM package_master WHERE pack_id = '$rid' ");
    $res = $pack_sql->fetch_assoc();
    $payable = $res['pack_cost'];
    $pack_sub_cate = $res['pack_sub_cate'];
    
    $sub_sql = $config->query("SELECT * FROM sub_category WHERE Sub_Category_id = '$pack_sub_cate' ");
    $sub = $sub_sql->fetch_assoc();
    $cate = $sub['Main_Category_sub'];
    
    $sql = $config->query("INSERT INTO order_master(customer_id, transaction_id, order_category, order_sub_category, order_package, order_price, order_on, order_status)
    VALUES('$user_id'  ,'$tran_id' ,'$cate' ,'$pack_sub_cate' ,'$rid' ,'$payable' ,'$order_date' ,1) " );
}





$types = $_POST['types'];
if($types == "jobs"){
	$id = $_POST['id'];
	$idno = $_POST['idno'];
	$category = $_POST['category'];
	$subcategory = $_POST['subcategory'];
	$type = $_POST['type'];
	$name = $_POST['name'];
	$district = $_POST['district'];
	$area = $_POST['area'];
	$gender = $_POST['gender'];
	$packageid = $_POST['packageid'];
	$minsalary = $_POST['minsalary'];
	$maxsalary = $_POST['maxsalary'];
	$experience = $_POST['experience'];
	$color = $_POST['color'];
	$contact = $_POST['contact'];
	$payable = $_POST['payable'];
	$brandpremium = $homepremium = 0; 
	foreach($_POST['extra'] as $extra){
		if($extra == "Brand"){
			$brandpremium = 1;
		}
		if($extra == "Premium"){
			$homepremium = 1;
		}
	}
	$duration = $amount = 0;
	$newsql = "SELECT * FROM jobs_packages WHERE packageid='$packageid'";
	$newquery=mysqli_query($conn, $newsql);
	while( $row=mysqli_fetch_array($newquery) ) {
		$duration = $row["duration"];
		$amount = $row["amount"];
	}
	$expiredat = date("Y-m-d", strtotime("$todaydate +".$duration." days"));

	$brandlogo = "";
	if(isset($_FILES['brandlogo'])){
		$frontFile1 = $_FILES['brandlogo']['name'];
		$tmp_dir1 = $_FILES['brandlogo']['tmp_name'];
		$imgSize1 = $_FILES['brandlogo']['size'];
		
		$colorcode = "";

		$upload_dir = '../admin/uploads/'; // upload directory
		$imgExt = strtolower(pathinfo($frontFile1,PATHINFO_EXTENSION)); // get image extension
		// valid image extensions
		$valid_extensions = array('jpeg', 'jpg', 'png'); // valid extensions
		// rename uploading image
		$userpic1 = $frontFile1;
		// allow valid image file formats
		move_uploaded_file($tmp_dir1,$upload_dir.$userpic1);
		$brandlogo = $userpic1;
	}
		

	if($type == "Image"){
		$postimage = "";
		$frontFile1 = $_FILES['postimage']['name'];
		$tmp_dir1 = $_FILES['postimage']['tmp_name'];
		$imgSize1 = $_FILES['postimage']['size'];
		$colorcode = "";

		$upload_dir = '../admin/uploads/'; // upload directory
		$imgExt = strtolower(pathinfo($frontFile1,PATHINFO_EXTENSION)); // get image extension
		// valid image extensions
		$valid_extensions = array('jpeg', 'jpg', 'png'); // valid extensions
		// rename uploading image
		$userpic1 = $frontFile1;
		// allow valid image file formats
		if(in_array($imgExt, $valid_extensions)){
			move_uploaded_file($tmp_dir1,$upload_dir.$userpic1);
			$postimage = $userpic1;
			
			$query = "INSERT INTO `jobpost`(`idno`, `postid`, `category`, `subcategory`, `name`, `description`, `image`, `city`, `area`, `gender`, `minsalary`, `maxsalary`, `experience`, `packagetype`, `color`, `premium`, `brand`, `brandlogo`, `mobile`, `createdat`, `createdby`, `expiredat`, `status`, `duration`, `pricing`, `packageid`, `paymentstatus`, `payable`) VALUES ($idno, '$id', $category, $subcategory, '$name', '', '$postimage', '$district', '$area', '$gender',  $minsalary, $maxsalary, $experience, '$type', '$color', $homepremium, $brandpremium, '$brandlogo', '$contact', '$currenttime', '$userid', '$expiredat', 'Pending', $duration, '$amount', '$packageid', '', '$payable')";
			$query_result = mysqli_query($conn,$query);
		} else {
			$msg = "Sorry, your file extension is wrong.";
			$alert = "danger";
		}
	} else {
		$description = $_POST['description'];
		$description = mysqli_real_escape_string($conn, $_POST['description']);
		$query = "INSERT INTO `jobpost`(`idno`, `postid`, `category`, `subcategory`, `name`, `description`, `image`, `city`, `area`, `gender`, `minsalary`, `maxsalary`, `experience`, `packagetype`, `color`, `premium`, `brand`, `brandlogo`, `mobile`, `createdat`, `createdby`, `expiredat`, `status`, `duration`, `pricing`, `packageid`, `paymentstatus`, `payable`) VALUES ($idno, '$id', $category, $subcategory, '$name', '$description', '', '$district', '$area', '$gender',  $minsalary, $maxsalary, $experience, '$type', '$color', $homepremium, $brandpremium, '$brandlogo', '$contact', '$currenttime', '$userid', '$expiredat', 'Pending', $duration, '$amount', '$packageid', '', '$payable')";
		$query_result = mysqli_query($conn,$query);
	}
	if($query_result){
	  $msg = "Jobpost Added Successfully";
	  $alert = "success";
	} else {
	  $msg = "Jobpost Failed to Add";
	  $alert = "error";
	}
} 


//echo $query;

$api = new Api($keyId, $keySecret);

//

// We create an razorpay order using orders api

// Docs: https://docs.razorpay.com/docs/orders

//

$orderData = [

	'receipt'         => 3456,

	'amount'          => $payable * 100, // 2000 rupees in paise

	'currency'        => 'INR',

	'payment_capture' => 1 // auto capture

];

$razorpayOrder = $api->order->create($orderData);

$razorpayOrderId = $razorpayOrder['id'];

$_SESSION['razorpay_order_id'] = $razorpayOrderId;

$displayAmount = $amount = $payable;

echo $_SESSION['razorpay_order_id'];

if ($displayCurrency !== 'INR')

{
	$url = "https://api.fixer.io/latest?symbols=$displayCurrency&base=INR";
	$exchange = json_decode(file_get_contents($url), true);
	$displayAmount = $exchange['rates'][$displayCurrency] * $payable / 100;
}
$checkout = 'automatic';

if (isset($_GET['checkout']) and in_array($_GET['checkout'], ['automatic', 'manual'], true))

{
	$checkout = $_GET['checkout'];
}

$data = [
	"key"               => $keyId,
	"amount"            => $payable,
	"name"              => $name,
	"description"       => $id,
	"image"             => "https://s29.postimg.org/r6dj1g85z/daft_punk.jpg",
	"prefill"           => [
	"name"              => $name,
	"email"             => $email,
	"contact"           => $mobile,
	],
	"notes"             => [
	"address"           => "",
	"merchant_order_id" => "12312321",
	],
	"theme"             => [
	"color"             => "#F37254"
	],
	"order_id"          => $razorpayOrderId,
];

if ($displayCurrency !== 'INR')
{
	$data['display_currency']  = $displayCurrency;
	$data['display_amount']    = $displayAmount;
}
$json = json_encode($data);
?>

<div class="utf_dashboard_content"> 
	<div id="titlebar" class="dashboard_gradient">
		<div class="row">
		  <div class="col-md-12">
			<h2>Payment</h2>
			<nav id="breadcrumbs">
			  <ul>
				<li><a href="dashboard.php">Home</a></li>
				<li>Payment</li>
			  </ul>
			</nav>
		  </div>
		</div>
	</div>
  
	
	<div class="row">
		
		<div class="col-md-12">	

		<center><img src="assets/img/pleasewait.gif" class="image-fluid" /></center>

		<button id="rzp-button1" class="btn btn-success" style="visibility : hidden;">Pay <?php echo $gross; ?> with Razorpay</button>

		<script src="https://checkout.razorpay.com/v1/checkout.js"></script>

		<form name='razorpayform' action="paymentsuccess.php" id="checkoutform" method="POST">

			<input type="hidden" name="razorpay_payment_id" id="razorpay_payment_id">

			<input type="hidden" name="razorpay_signature"  id="razorpay_signature" >

			<input type="hidden" name="types"  id="types" value="<?php echo $types; ?>">
			<input type="hidden" name="idno"  id="idno" value="<?php echo $idno; ?>">

			<input type="hidden" name="orderid"  id="orderid" value="<?php echo $id; ?>">

			<input type="hidden" name="name"  id="name" value="<?php echo $name; ?>">

			<input type="hidden" name="email" id="email" value="<?php echo $email; ?>">

			<input type="hidden" name="mobile"  id="mobile"  value="<?php echo $mobile; ?>" >

			<input type="hidden" name="address1" id="address1" value="">

			<input type="hidden" name="address2"  id="address2" value="" >

			<input type="hidden" name="district"  id="district" value="" >

			<input type="hidden" name="state"  id="state" value="" >

			<input type="hidden" name="pincode"  id="pincode" value="" >

			<input type="hidden" name="subtotal"  id="subtotal" value="<?php echo $payable; ?>" >

			<input type="hidden" name="tax"  id="tax" value="0" >

			<input type="hidden" name="round"  id="round" value="0" >

			<input type="hidden" name="payable"  id="payable" value="<?php echo $payable; ?>" >

		</form>
		</div>
	</div>

</div>  
<?php include('footer.php'); ?>

<script type="text/javascript">

$(document).ready(function(){
    $("#rzp-button1").click();

});

// Checkout details as a json

var options = <?php echo $json; ?>;

/**

 * The entire list of Checkout fields is available at

 * https://docs.razorpay.com/docs/checkout-form#checkout-fields

 */

options.handler = function (response){

    document.getElementById('razorpay_payment_id').value = response.razorpay_payment_id;

    document.getElementById('razorpay_signature').value = response.razorpay_signature;

    document.razorpayform.submit();

};

// Boolean whether to show image inside a white frame. (default: true)

options.theme.image_padding = false;

options.modal = {

    ondismiss: function() {

        window.location.replace("paymentsuccess.php");

    },

    // Boolean indicating whether pressing escape key

    // should close the checkout form. (default: true)

    escape: false,

    // Boolean indicating whether clicking translucent blank

    // space outside checkout form should close the form. (default: false)

    backdropclose: false

};

var rzp = new Razorpay(options);

document.getElementById('rzp-button1').onclick = function(e){

    rzp.open();

    e.preventDefault();

}


</script>