<?php
defined('BASEPATH') OR exit('No direct script access allowed');
if (isset($_SERVER['HTTP_ORIGIN'])) {
  header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
  header('Access-Control-Allow-Credentials: true');
  header('Access-Control-Max-Age: 86400'); 
}

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])){
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
  }

  if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])){
    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
  }
  exit(0);
}

class Api extends CI_Controller {

  var $auth_token;

  public function __construct() {
    parent::__construct();
    date_default_timezone_set("Asia/Riyadh");
    $this->load->model('Api_model');    
    $this->load->model('Validation_model');
    $method = $this->router->fetch_method();        
    $data = (array) json_decode(file_get_contents('php://input'));
    if($method == 'profile') {
      $data = $_POST;
    }
    if (isset(apache_request_headers()['Auth'])) {
            $this->auth_token = apache_request_headers()['Auth'];
            $data['auth_token'] = $this->auth_token;
        }
    $res = $this->Validation_model->validation_check($method, $data);
    if($res['state'] == 1) {
      $this->errorResponse($res['response']['code'], $res['response']['message']);
      die;
    }
    
  }

  public function index() {
    $res = $this->Validation_model->validation_check('login',array('email_id'=>'adarsh'));
  }

  public function response($data) {
    $result =  array(
      'code' => 1,
      'message' => 'Success',
      'responseResult' =>$data
    );
    print json_encode($result);
  }

  public function errorResponse($errorCode, $errorDesc) {
    $result =  array(
      'code' => 0,
      'message' => 'Failure',
      'errorCode'=> $errorCode,
      'errorDesc'=> $errorDesc
    );
    print json_encode($result);
  }

  public function login(){
    $data = (array) json_decode(file_get_contents('php://input'));
    $res = $this->Api_model->login($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function register(){
    $data = (array) json_decode(file_get_contents('php://input'));
    $res = $this->Api_model->register($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function forgot(){
    $data = (array) json_decode(file_get_contents('php://input'));
    $res = $this->Api_model->forgot($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function popular() {
    $res = $this->Api_model->popular();
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function category() {
    $res = $this->Api_model->category();
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function locality($city_id = '') {
    $res = $this->Api_model->locality($city_id);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function favourite(){
    $data = (array) json_decode(file_get_contents('php://input'));
    $data['auth_token'] = $this->auth_token;
    $res = $this->Api_model->favourite($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function favouritelist() {
    $data['auth_token'] = $this->auth_token;
    $res = $this->Api_model->favouritelist($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function bookedlist() {    
    $data = (array) json_decode(file_get_contents('php://input'));
    $data['auth_token'] = $this->auth_token;
    $res = $this->Api_model->bookedlist($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function bookingdetails() {    
    $data = (array) json_decode(file_get_contents('php://input'));
    $data['auth_token'] = $this->auth_token;
    $res = $this->Api_model->bookingdetails($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function cancel() {    
    $data = (array) json_decode(file_get_contents('php://input'));
    $data['auth_token'] = $this->auth_token;
    $res = $this->Api_model->cancel($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function confirm() {
    $data = (array) json_decode(file_get_contents('php://input'));
    $data['auth_token'] = $this->auth_token;
    $res = $this->Api_model->confirm($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function userinfo() {
    $data['auth_token'] = $this->auth_token;
    $res = $this->Api_model->userinfo($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function profile() {
    $data = $_POST;
    if(isset($_FILES['profile_picture'])) {
      $data['file'] = $_FILES['profile_picture'];
    } 
    $data['auth_token'] = $this->auth_token;
    $res = $this->Api_model->update_profile($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function tempbooking() {
    $data = (array) json_decode(file_get_contents('php://input'));
    $data['auth_token'] = $this->auth_token;
    $res = $this->Api_model->tempbooking($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function recommend() {
    $data = (array) json_decode(file_get_contents('php://input'));
    $data['auth_token'] = $this->auth_token;

    $res = $this->Api_model->recommend($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function discover() {
    $data = (array) json_decode(file_get_contents('php://input'));
    //$data['auth_token'] = $this->auth_token;
    $res = $this->Api_model->discover($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function event() {
    $data = (array) json_decode(file_get_contents('php://input'));
    $data['auth_token'] = (isset($this->auth_token))?$this->auth_token:'';
    $res = $this->Api_model->event($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function search() {
    $data = (array) json_decode(file_get_contents('php://input'));
    //$data['auth_token'] = $this->auth_token;

    $res = $this->Api_model->search($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function searchEvent($str = null) {
    $data['str'] = $str;
    $res = $this->Api_model->searchEvent($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function get_cms_data() {
    $res = $this->Api_model->get_cms_data();
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function save_organizer(){
    $data = (array) json_decode(file_get_contents('php://input'));
    $res = $this->Api_model->save_organizer($data);
    if($res['status']!=0){
      $this->response($res['status']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }  
  }

  public function payNow($auth_token='',$amount=0,$booking_id='',$event_id=''){
    if(empty($auth_token) || empty($amount) || empty($booking_id)){
      redirect('https://timeout.sa/staging/failure');
    }
    $payData = array('auth_token'=>$auth_token,'amount'=>$amount,'booking_id'=>$booking_id);
    $res = $this->Api_model->payNow($payData);

    if($res['status']==1){
       $this->paymentGateway($amount,$res['transaction_id'],$event_id,$booking_id,$res['custData']);
    }
    else{
       redirect('https://timeout.sa/staging/failure?event_id='.$eventid);
    }
  }

  public function paymentSuccessUrl(){
    $response = '';
    $transaction_id = '';
    BayanPayPayment();
    $BayanPayArray = $this->bayanPayArray('0','0','0','0');
    $BayanPayOnlineObject = new BayanPayBitmapPaymentIntegration($BayanPayArray);

    if(isset($_REQUEST['responseParameter']) && $_REQUEST['responseParameter'] != ''){
    $response = $BayanPayOnlineObject->decryptData($_REQUEST['responseParameter'],$BayanPayOnlineObject->merchantKey,$BayanPayOnlineObject->iv);

    $ref_id = explode('|',$response['Transaction_related_information']);
    $transaction_id = $ref_id[1];
    $last_id = explode('|',$response['Merchant_Information']);
    $lastid = $last_id[1];
        $eventid = $last_id[2];
        $booking_id = $last_id[3];
    $this->Api_model->update_payment($response,$transaction_id,$lastid,'1') ;

    redirect('https://timeout.sa/staging/bookingdetails?booking_id='.$booking_id);
    }
  }

  public function paymentFailureUrl(){
  $lastid = '';
  $response = '';
  $transaction_id = '';
  BayanPayPayment();
  $BayanPayArray = $this->bayanPayArray('0','0','0','0');
  $BayanPayOnlineObject = new BayanPayBitmapPaymentIntegration($BayanPayArray);
    
    if(isset($_REQUEST['responseParameter']) && $_REQUEST['responseParameter'] != ''){
        $response = $BayanPayOnlineObject->decryptData($_REQUEST['responseParameter'],$BayanPayOnlineObject->merchantKey,$BayanPayOnlineObject->iv);

        $ref_id = explode('|',$response['Transaction_related_information']);
        $transaction_id = $ref_id[1];
        $last_id = explode('|',$response['Merchant_Information']);
        $lastid = $last_id[1];
        $eventid = $last_id[2];
        $booking_id = $last_id[3];
      $this->Api_model->update_payment($response,$transaction_id,$lastid,'0');

      redirect('https://timeout.sa/staging/failure?event_id='.$eventid);
    }
  }

  public function paymentGateway($amount='0',$lastid='0',$event_id='0',$booking_id='0',$custData=array()){
    BayanPayPayment();
    $BayanPayArray = $this->bayanPayArray($amount,$lastid,$event_id,$booking_id,$custData);
    $BayanPayOnlineObject = new BayanPayBitmapPaymentIntegration($BayanPayArray);

    $requestParameter = $BayanPayOnlineObject->BayanPostData;
    if($BayanPayOnlineObject->url){
      $requestUrl = 'https://payments.bayanpay.sa/direcpay/secure/PaymentTxnServlet';
    }
    else{
      $requestUrl = 'https://staging.bayanpay.sa/direcpay/secure/PaymentTxnServlet';
    }

    $this->load->view('payment/payment',array('requestUrl'=>$requestUrl,
                              'requestParameter'=>$requestParameter));
  }

  function baseurl(){
      if(isset($_SERVER['HTTPS']))
          $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
      else
          $protocol = 'http';
      return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  }

  function bayanPayArray($amount='0',$lastid='',$event_id='',$booking_id='',$custData=array()){
    $settings = getSettings();

    $BayanPayArray = 
      array(
        'BayanPay_Online_setting' => array(
          'merchantKey'           => $settings['merchant_key'],
          'merchantId'            => $settings['merchant_id'],
          'collaboratorId'        => 'BAYANPAY',
          'iv'                    => '0123456789abcdef',
          'url'                   => false
        ),
        'Block_Existence_Indicator'=> array(
          'transactionDataBlock'  => true,
          'billingDataBlock'      => true,
          'shippingDataBlock'     => true,
          'paymentDataBlock'      => false,
          'merchantDataBlock'     => true,
          'otherDataBlock'        => false,
          'DCCDataBlock'          => false
        ),
        'Field_Existence_Indicator_Transaction' => array(
          'merchantOrderNumber'   => time(), 
          'amount'                => $amount,
          'successUrl'            => base_url('Api/paymentSuccessUrl'),
          'failureUrl'            => base_url('Api/paymentFailureUrl'),
          'transactionMode'       => 'INTERNET',
          'payModeType'           => 'CC',
          'transactionType'       => '01',
          'currency'              => 'SAR'
        ),
        'Field_Existence_Indicator_Billing' => array(
          'billToFirstName'       => $custData->name, 
          'billToLastName'        => '',
          'billToStreet1'         => '',
          'billToStreet2'         => '',
          'billToCity'            => '',
          'billToState'           => '',
          'billtoPostalCode'      => '',
          'billToCountry'         => '',
          'billToEmail'           => $custData->email,
          'billToMobileNumber'    => $custData->phone,
          'billToPhoneNumber1'    => '',
          'billToPhoneNumber2'    => '',
          'billToPhoneNumber3'    => ''
        ),
        'Field_Existence_Indicator_Shipping' => array(
          'shipToFirstName'       => $custData->name, 
          'shipToLastName'        => '', 
          'shipToStreet1'         => '', 
          'shipToStreet2'         => '', 
          'shipToCity'            => '',
          'shipToState'           => '',
          'shipToPostalCode'      => '',
          'shipToCountry'         => '',
          'shipToPhoneNumber1'    => '',
          'shipToPhoneNumber2'    => '',
          'shipToPhoneNumber3'    => '',
          'shipToMobileNumber'    => $custData->phone
        ),
        'Field_Existence_Indicator_Payment' => array(
          'cardNumber'            => '4111111111111111',
          'expMonth'              => '08',
          'expYear'               => '2020',
          'CVV'                   => '123',
          'cardHolderName'        => 'Soloman',
          'cardType'              => 'Visa',
          'custMobileNumber'      => '9820998209',
          'paymentID'             => '123456',
          'OTP'                   => '123456',
          'gatewayID'             => '1026',
          'cardToken'             => '1202'
        ),
        'Field_Existence_Indicator_Merchant' => array(
          'UDF1'                  => $lastid,                
          'UDF2'                  => $event_id,                
          'UDF3'                  => $booking_id               
        ),
        'Field_Existence_Indicator_OtherData'  => array(
          'custID'                => $custData->userId,  
          'transactionSource'     => 'IVR',            
          'productInfo'           => '',             
          'isUserLoggedIn'        => '',              
          'itemTotal'             => '', 
          'itemCategory'          => '',             
          'ignoreValidationResult'=> 'FALSE'
        ),
        'Field_Existence_Indicator_DCC' => array(
          'DCCReferenceNumber'    => $lastid.$event_id.$booking_id,
          'foreignAmount'         => $amount,
          'ForeignCurrency'       => 'SAR'
        )
      );
    return $BayanPayArray;
  }
  
  public function checker_bookingDetails(){
    $data = (array) json_decode(file_get_contents('php://input'));
    $res = $this->Api_model->checkerbookingdetails($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function checker_login(){
    $data = (array) json_decode(file_get_contents('php://input'));
    $res = $this->Api_model->checker_login($data);
    if($res['status']!=0){
      $this->response($res['data']);
    } else {
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function reset_password(){
    $data = (array) json_decode(file_get_contents('php://input'));
    $res = $this->Api_model->reset_password($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }

  public function verifyMail($unique_id = '') {
    $res = $this->Api_model->verifyMail(array('unique_id'=>$unique_id));
  }

  public function checkSeatAvailability(){
    $data = (array) json_decode(file_get_contents('php://input'));
    $data['auth_token'] = $this->auth_token;
    $res = $this->Api_model->checkSeatAvailability($data);
    if($res['status']!=0){
      $this->response($res['data']);
    }
    else{
      $this->errorResponse($res['code'],$res['message']);
    }
  }
}
?>