<?php



namespace App\Controllers;



use Square\SquareClient;

use Square\Models\Money;

use Square\Models\CreatePaymentRequest;

use Square\Exceptions\ApiException;

use Ramsey\Uuid\Uuid;

use App\Models\Transaction_model;

use App\Models\Member_model;

use App\Models\Dashboard_model;

use App\Models\Common_model;

use App\Models\Member_credits_model;

use App\Models\Packages_and_pricing_model;

use App\Models\Cart_model;

use App\Models\Credits_usage_tracking_model;

use App\Models\Rule_model;

use App\Models\Cart_token_model;

use App\Models\Member_address_model;

use App\Models\Zipcode_model;

use App\Models\Country_model;

class PaymentController extends BaseController

{

   



    public function __construct()

    {

        $this->session = session();

		$this->MemberModel = new Member_model();

		$this->dModel = new Dashboard_model();

		$this->cModel = new Common_model();

		$this->creditsModel = new Member_credits_model();

		$this->PackagesModel = new Packages_and_pricing_model();

		$this->cartModel = new Cart_model();

		$this->CreditsUsageTrackingModel = new Credits_usage_tracking_model();

        $this->TransactionModel = new Transaction_model();

        $this->RuleModel = new Rule_model();

        $this->Cart_token_model = new Cart_token_model();

        $this->MemberAddressModel = new Member_address_model();

        $this->ZipcodeModel = new Zipcode_model();

        $this->CountryModel = new Country_model();

    }

  

    

    public function index($token = null)

    {
        if($this->request->getmethod() == 'post')

		{

        //    echo $token;die();
            if(!session()->has('logged_user'))
		     {
                // $count = $this->request->getVar('count');
                // foreach ($count as $key => $value) 
                // {
                //     $this->Cart_token_model->where('id', $this->request->getVar('cart_token_id')[$key] )->set(array( 'count' => $value ))->update();
                // }

			  $this->session->set('token',$token);
			  return redirect()->to(base_url());

		     }

             else{



                $this->payment_form();

             }

            

        } else {

          
            //  echo $this->session->get('logged_user');die();
             $this->payment_form();

        }

    }

       

    







    public function payment_form()

    {

        // if(!session()->has('logged_user'))
        //     {
        //      return redirect()->to(base_url());
        //     }

            $CartData = $this->cartModel->where('member_id',session()->get('logged_user'))->findAll();
            $count = count($CartData);
            if($count)
            {
                $credit_pack_expiry_duration = $this->RuleModel->select('value')->where('rule_key', 1 )->get()->getRow()->value;
                $gst = $this->RuleModel->select('value')->where('rule_key', 3 )->get()->getRow()->value;
                $pst = $this->RuleModel->select('value')->where('rule_key', 4 )->get()->getRow()->value;
                $today = date("Y-m-d");
                $days = "+".$credit_pack_expiry_duration." days";
                $amount = 0;
                $item_count = 0;

                if($CartData[0]['order_id'] == null)
                {
                    $orderId = 'EGF'.rand(10,100).rand(10,100).rand(10,100);
                }else{
                    $orderId = $CartData[0]['order_id'];
                }

                 $packageArray = [];

                 for($i=0;$i<$count;$i++)   
                 {
                    $packageData = $this->PackagesModel->where('id',$CartData[$i]['pack_id'])->find();

                    $packageData[0]['count'] = $CartData[$i]['count'];

                    array_push($packageArray , $packageData[0]);

                    $cost = $packageData[0]['cost'] * $CartData[$i]['count'];
                   

                    $credits_data['member_id'] = session()->get('logged_user');
                    $credits_data['pack_id'] =  $packageData[0]['id'];
                    $credits_data['package_name'] = $packageData[0]['package_name'];
                    $credits_data['package_type'] = $packageData[0]['package_type'];
                    $credits_data['credit_points'] = $packageData[0]['credit'];
                    $credits_data['running_balance'] = $packageData[0]['credit'];
                    $credits_data['expired_points'] = 0;
                    $credits_data['expiring_date'] = date('Y-m-d', strtotime($days, strtotime($today)));
                    $credits_data['cost'] = $packageData[0]['cost'];
                    $credits_data['is_active'] = 0;
                    $credits_data['order_id'] = $orderId;
                    $credits_data['cost_with_tax'] =   ( $packageData[0]['cost'] + (($packageData[0]['cost'] * ($gst + $pst) ) / 100) );
                    

                    $creditsModel_pack_count = $this->creditsModel->selectCount('id')->where('pack_id',$packageData[0]['id'])->where('order_id',$orderId)->where('member_id', session()->get('logged_user'))->get()->getRow()->id;
                    if($creditsModel_pack_count)
                    {
                        $this->creditsModel->where('pack_id',$packageData[0]['id'])->where('order_id',$orderId)->where('member_id', session()->get('logged_user'))
                             ->set(array('cost'=>$packageData[0]['cost'],'cost_with_tax'=>( $packageData[0]['cost'] + (($packageData[0]['cost'] * ($gst + $pst) ) / 100) ),'credit_points'=>$packageData[0]['credit'],'running_balance'=>$packageData[0]['credit'],'package_name'=>$packageData[0]['package_name'],'package_type'=>$packageData[0]['package_type']))->update();
                    }
                    $single_pack_no_of_count = $CartData[$i]['count'] - $creditsModel_pack_count;

                    // if($CartData[0]['order_id'] == null)
                    // {
                      for($j=0;$j<$single_pack_no_of_count;$j++)   
                      {
                          $insert_data = $this->creditsModel->save($credits_data);
                      }

                      $this->cartModel->where('id', $CartData[$i]['id'] )
                             ->where('member_id', session()->get('logged_user'))
                             ->set(array( 'order_id' => $orderId   ))->update();
                    // }
                    $amount = $amount + $cost;
                    $item_count = $item_count + $CartData[$i]['count'];
                 }



                $data['amount'] = $amount;
                $data['item_count'] = $item_count;
                $data['order_id'] = $orderId;
                $data['gst'] = $gst;
                $data['pst'] = $pst;
                $data['packageArray'] = $packageArray;
                $data['country'] = $this->CountryModel->findAll();
                $data['userdata'] = $this->MemberModel->where('id',  session()->get('logged_user'))->find();
    
                $if_trans_exist = $this->TransactionModel->where('member_id', session()->get('logged_user'))
                                                         ->where('order_id', $orderId )->find();
                if($if_trans_exist){ 
                //skip insertion
                 }else{
                //Trancaction Table initial entry for this transaction 
                $TrancactionData['status'] = 'In-Progress';
                $TrancactionData['member_id'] = session()->get('logged_user');
                $TrancactionData['order_id'] =   $orderId;
                $insert = $this->TransactionModel->save($TrancactionData);
                }

                $zip = $this->ZipcodeModel->findAll();
		        $output = '<option value="">'.$data['userdata'][0]['pincode'].'</option>';
		        foreach($zip as $row)
		        {
		        $output .= '<option value="'.$row['id'].'">'.$row['code'].'</option>';
		        }
		        $data['zipcode'] = $output;

            
                echo view('checkout',$data);  
            } else {  	return redirect()->to(base_url()."view/".md5(session()->get('logged_user')));  }

    }

  

    

   

    public function processPayment()

    {

        try { 

       

        if ($_SERVER['REQUEST_METHOD'] != 'POST') {

            error_log('Received a non-POST request');

            echo 'Request not allowed';

            http_response_code(405);

            return;

        }



        include 'app/Libraries/LocationInfo.php';



        $json = file_get_contents('php://input');

        $data = json_decode($json);

        $gst = $this->RuleModel->select('value')->where('rule_key', 3 )->get()->getRow()->value;

        $pst = $this->RuleModel->select('value')->where('rule_key', 4 )->get()->getRow()->value;

        $token = $data->token;

        $idempotencyKey = $data->idempotencyKey;

        $amount = $data->amount;

        $order_id = $data->order_id;

        $add = $data->address;

        parse_str( $add, $address);

           





        //print_r($add);die();



        $Final_amount =  round( ( $amount + (($amount * ($gst + $pst) ) / 100) ) , 2 );
        $Final_amount = $Final_amount * 100;

        

        $square_client = new SquareClient([

            'accessToken' => getenv('SQUARE_ACCESS_TOKEN'),

            'environment' => getenv('ENVIRONMENT'),

            'userAgentDetail' => 'golf_evo', // Remove or replace this detail when building your own app

        ]);

        

        $payments_api = $square_client->getPaymentsApi();

        

        // To learn more about splitting payments with additional recipients,

        // see the Payments API documentation on our [developer site]

        // (https://developer.squareup.com/docs/payments-api/overview).

        

        $money = new Money();

        // Monetary amounts are specified in the smallest unit of the applicable currency.

        // This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.

        $money->setAmount($Final_amount);

       

        // Set currency to the currency for the location

        $money->setCurrency($location_info->getCurrency());

       

       //print_r($money); die();

        

        try {

            // Every payment you process with the SDK must have a unique idempotency key.

            // If you're unsure whether a particular payment succeeded, you can reattempt

            // it with the same idempotency key without worrying about double charging

            // the buyer.

            $create_payment_request = new CreatePaymentRequest($token, $idempotencyKey, $money);

            $create_payment_request->setLocationId($location_info->getId());

        

            $response = $payments_api->createPayment($create_payment_request);

        

            if ($response->isSuccess()) {

               

            $data = json_encode($response->getResult());

            $result = json_decode( $data ,true);

            //Trancaction Table Data
            $TrancactionData['status'] = 'Success';
            //$TrancactionData['member_id'] = session()->get('logged_user');
            $TrancactionData['first_name'] = $address['name'];
            $TrancactionData['last_name'] = $address['last_name'];
            $TrancactionData['address'] = $address['address'];
            $TrancactionData['country'] = $address['country'];
            $TrancactionData['city'] = $address['city'];
            $TrancactionData['zip_code'] = $address['pincode'];
            if($address['country']=='Canada'){  $TrancactionData['state'] = $address['canada_state'];  }else{  $TrancactionData['state'] = $address['state'];}

            $TrancactionData['transaction_id'] =  $result['payment']['id'];

            $TrancactionData['payment_order_id'] =  $result['payment']['order_id'];

            $TrancactionData['transaction'] = json_encode($response->getResult());

            $update = $this->TransactionModel->where('member_id', session()->get('logged_user'))

                                             ->where('order_id', $order_id )

                                             ->set($TrancactionData)->update();

            if( $update)

            {

                $this->creditsModel->where('order_id', $order_id )->where('member_id', session()->get('logged_user'))

                     ->set(array( 'is_active' => 1 , 'transaction_id' => $result['payment']['id']  ))->update();

                $this->cartModel->where('order_id', $order_id )->delete();

            }

           

            echo json_encode($response->getResult());



    

            } else {

                $data = json_encode($response->getErrors());

                $result = json_decode( $data ,true);

                //Trancaction Table Data

                $TrancactionData['status'] = 'Failed';

               // $TrancactionData['member_id'] = session()->get('logged_user');
               $TrancactionData['first_name'] = $address['name'];
               $TrancactionData['last_name'] = $address['last_name'];
               $TrancactionData['address'] = $address['address'];
               $TrancactionData['country'] = $address['country'];
               $TrancactionData['city'] = $address['city'];
               $TrancactionData['zip_code'] = $address['pincode'];
               if($address['country']=='Canada'){  $TrancactionData['state'] = $address['canada_state'];  }else{  $TrancactionData['state'] = $address['state'];}
   
                //$TrancactionData['order_id'] =   $order_id;

                $TrancactionData['transaction'] = json_encode($response->getErrors());

                $update = $this->TransactionModel->where('member_id', session()->get('logged_user'))

                                                 ->where('order_id', $order_id )

                                                 ->set($TrancactionData)->update();

                if( $update)

                {

                    

                    $this->creditsModel->where('order_id', $order_id )->delete();

                    $this->cartModel->where('order_id', $order_id )->set(array('order_id'=>null))->update();

                }

               

                echo json_encode(array('errors' => $response->getErrors()));

            }

        } catch (ApiException $e) {

            echo json_encode(array('errors' => $e));

        }

    } catch (\Exception $e) {

        // Handle exceptions



        // Example: Logging the exception

        log_message('error', 'Exception: ' . $e->getMessage());

        

        // Example: Displaying a custom error message

        echo 'An exception occurred: ' . $e->getMessage();

    } catch (\Error $e) {

        // Handle errors



        // Example: Logging the error

        log_message('error', 'Error: ' . $e->getMessage());

        

        // Example: Displaying a custom error message

        echo 'An error occurred: ' . $e->getMessage();

    }

    }



   





    public function payment_success( $local_order_id  = null)

    { 
//    $data['TransactionData'] = $this->TransactionModel->where('order_id', $local_order_id )->where('member_id', session()->get('logged_user'))->find();
// $memberCredits = $this->creditsModel->where('order_id', $local_order_id )
//                                     ->where('member_id', session()->get('logged_user'))
//                                     ->select('package_name')
//                                     ->select('cost')
//                                     ->selectSum('credit_points', 'credit_points')
//                                     ->selectSum('cost', 'costSum')
//                                     ->selectCount('package_name', 'pack_count')
//                                     ->groupBy('package_name')->findAll();     
// $Subtotal = 0;
// foreach ($memberCredits as $key => $ele) {
// $Subtotal = $Subtotal + $ele['costSum'];
// }
// $data['memberCredits'] =$memberCredits;
// $data['order_id'] = $local_order_id;
// $timestamp = strtotime($data['TransactionData'][0]['created_at']);
// $data['formattedDate']  = date('l, F j, Y', $timestamp);
// $data['Subtotal'] = $Subtotal;
// $data['gst'] = $this->RuleModel->select('value')->where('rule_key', 3 )->get()->getRow()->value;
// $data['pst'] = $this->RuleModel->select('value')->where('rule_key', 4 )->get()->getRow()->value;
// $data['card_brand'] =  json_decode($data['TransactionData'][0]['transaction'] , true)['payment']['card_details']['card']['card_brand'];
// $data['last_4'] =  json_decode($data['TransactionData'][0]['transaction'] , true)['payment']['card_details']['card']['last_4'];
// echo view('success_mail',$data);
//         die();      

        if( $local_order_id != null)

        {

            $data['TransactionData'] = $this->TransactionModel->where('order_id', $local_order_id )->where('member_id', session()->get('logged_user'))->find();

            if($data['TransactionData']){

                $memberCredits = $this->creditsModel->where('order_id', $local_order_id )

                                                    ->where('member_id', session()->get('logged_user'))

                                                    ->select('package_name')

                                                    ->select('cost')

                                                    ->selectSum('credit_points', 'credit_points')

                                                    ->selectSum('cost', 'costSum')

                                                    ->selectCount('package_name', 'pack_count')

                                                    ->groupBy('package_name')->findAll();



                if($data['TransactionData'][0]['is_mail_triggered'] == 0){

                    $sendmail_controller = new Sendmail_controller();

                    $mail = $sendmail_controller->index(session()->get('logged_user_email') , $local_order_id , 5); 

                    if($mail == true){

                        $this->TransactionModel->where('order_id', $local_order_id )->set(array('is_mail_triggered'=>1))->update();

                    }

                    $admin_email = $this->RuleModel->select('value')->where('rule_key', 10 )->get()->getRow()->value;
                    $sendmail_controller->index($admin_email , $local_order_id , 5);

                }      

               

                $Subtotal = 0;

                foreach ($memberCredits as $key => $ele) {

                $Subtotal = $Subtotal + $ele['costSum'];

                }

                $data['memberCredits'] =$memberCredits;



                $data['order_id'] = $local_order_id;

                $timestamp = strtotime($data['TransactionData'][0]['created_at']);

                $data['formattedDate']  = date('l, F j, Y', $timestamp);

                $data['Subtotal'] = $Subtotal;

                $data['gst'] = $this->RuleModel->select('value')->where('rule_key', 3 )->get()->getRow()->value;

                $data['pst'] = $this->RuleModel->select('value')->where('rule_key', 4 )->get()->getRow()->value;

                $data['card_brand'] =  json_decode($data['TransactionData'][0]['transaction'] , true)['payment']['card_details']['card']['card_brand'];

                $data['last_4'] =  json_decode($data['TransactionData'][0]['transaction'] , true)['payment']['card_details']['card']['last_4'];


                echo view('payment',$data);

            }else{

                // echo 'invalid order_id';
                return redirect()->to(base_url());

            }

        }



    }



    public function payment_failed( $local_order_id  = null)

    { 

        if( $local_order_id != null)

        {

            $data['TransactionData'] = $this->TransactionModel->where('order_id', $local_order_id )->where('member_id', session()->get('logged_user'))->find();

            if($data['TransactionData']){

                $sendmail_controller = new Sendmail_controller();

                $mail = $sendmail_controller->index(session()->get('logged_user_email') , $local_order_id , 7); 

                $admin_email = $this->RuleModel->select('value')->where('rule_key', 10 )->get()->getRow()->value;
                $sendmail_controller->index($admin_email , $local_order_id , 7 ,'admin');

                $data['category'] = json_decode($data['TransactionData'][0]['transaction'] , true)[0]['category'];

                $data['code'] = json_decode($data['TransactionData'][0]['transaction'] , true)[0]['code'];

                $data['detail'] = json_decode($data['TransactionData'][0]['transaction'] , true)[0]['detail'];

                $data['order_id'] = $data['TransactionData'][0]['order_id'];

                $timestamp = strtotime($data['TransactionData'][0]['created_at']);

                $data['formattedDate']  = date('l, F j, Y', $timestamp);

               

                echo view('payment_failed',$data);

            }else{

                // echo 'invalid order_id';
                return redirect()->to(base_url());

            }

        }



    }







}


// $data['TransactionData'] = $this->TransactionModel->where('order_id', $code )->where('member_id', session()->get('logged_user'))->find();
// $memberCredits = $this->creditsModel->where('order_id', $code )
//                                     ->where('member_id', session()->get('logged_user'))
//                                     ->select('package_name')
//                                     ->select('cost')
//                                     ->selectSum('credit_points', 'credit_points')
//                                     ->selectSum('cost', 'costSum')
//                                     ->selectCount('package_name', 'pack_count')
//                                     ->groupBy('package_name')->findAll();     
// $Subtotal = 0;
// foreach ($memberCredits as $key => $ele) {
// $Subtotal = $Subtotal + $ele['costSum'];
// }
// $data['memberCredits'] =$memberCredits;
// $data['order_id'] = $code;
// $timestamp = strtotime($data['TransactionData'][0]['created_at']);
// $data['formattedDate']  = date('l, F j, Y', $timestamp);
// $data['Subtotal'] = $Subtotal;
// $data['gst'] = $this->RuleModel->select('value')->where('rule_key', 3 )->get()->getRow()->value;
// $data['pst'] = $this->RuleModel->select('value')->where('rule_key', 4 )->get()->getRow()->value;
// $data['card_brand'] =  json_decode($data['TransactionData'][0]['transaction'] , true)['payment']['card_details']['card']['card_brand'];
// $data['last_4'] =  json_decode($data['TransactionData'][0]['transaction'] , true)['payment']['card_details']['card']['last_4'];
// echo view('success_mail',$data);
              

            

  

   

