<?php
namespace BooklyPro\Frontend\Modules\Mellat;

use Bookly\Lib as BooklyLib;
use Bookly\Lib\Entities\Payment;
use Bookly\Lib\Notifications\Cart\Sender;
use Bookly\Lib\UserBookingData;
use Bookly\Lib\Utils\Common;
use BooklyPro\Lib\Payment\Mellat;

/**
 * Class Controller
 * @package BooklyPro\Frontend\Modules\Mellat
 */
class Controller extends BooklyLib\Base\Component
{
    /**
     * Init Express Checkout transaction.
     */
    public static function ecInit()
    {
        $form_id = self::parameter( 'bookly_fid' );
        if ( $form_id ) {
            // Create a mellat object.
            $mellat   = new Mellat();
            $userData = new UserBookingData( $form_id );

            if ( $userData->load() ) {
				$cart_info = $userData->cart->getInfo( Payment::TYPE_MELLAT );
				$cart_info->setGatewayTaxCalculationRule( 'tax_increases_the_cost' );
                //$cart_info->setPaymentMethodSettings( get_option( 'bookly_mellat_send_tax' ), 'tax_increases_the_cost' );

                $product = new \stdClass();
                $product->name  = $userData->cart->getItemsTitle( 126 );
                $product->price = $cart_info->getGatewayAmount();
                $product->qty   = 1;
                $mellat->setProduct( $product );
                $mellat->setTotalTax( $cart_info->getGatewayTax() );

                // and send the payment request.
                $mellat->sendECRequest( $form_id );
            }
        }
    }

    /**
     * Process Express Checkout return request.
     */
    public static function ecReturn()
    {
        $form_id = self::parameter( 'bookly_fid' );
        $mellat  = new Mellat();
        $error_message = '';
            $response = $mellat->sendNvpRequest( $form_id, array() );

            if ( $response['code']  == true) {
						$payment = new Payment();
                        $payment
                            ->setType( Payment::TYPE_MELLAT )
                            ->setStatus( Payment::STATUS_COMPLETED );
                        $userData = new UserBookingData( $form_id );
                        if ( $userData->load() ) {
							$cart_info = $userData->cart->getInfo( Payment::TYPE_MELLAT );
							
							$coupon = $userData->getCoupon();
                            if ( $coupon ) {
                                $coupon->claim();
                                $coupon->save();
                            }
                            $paid     = (float) $cart_info->getPayNow();//$response['AMT'];
                            $expected = (float) $cart_info->getPayNow();
                            if ( $expected == $paid ) {
                                $payment
                                    ->setCartInfo( $cart_info )
                                    ->save();
                                $order = $userData->save( $payment );
                                $payment->setDetailsFromOrder( $order, $cart_info )->save();
                                Sender::send( $order );
                            }
						} else {
							// Information about customer’s cart (order) is no longer available.
                            $payment
                                ->setTotal( $paid )
                                ->setPaid( $paid )
                                ->setTax( $response['TAXAMT'] )
                                ->save();
						}
						$userData->setPaymentStatus( Payment::TYPE_MELLAT, 'success' );
						$userData->sessionSave();
						@wp_redirect( remove_query_arg( Mellat::$remove_parameters, Common::getCurrentPageURL() ) );
						
						/*
                        $userData = new Lib\UserBookingData( $form_id );
                        $userData->load();
                        list ( $total, $deposit ) = $userData->cart->getInfo();
                            $coupon = $userData->getCoupon();
                            if ( $coupon ) {
                                $coupon->claim();
                                $coupon->save();
                            }
                            $payment = new Lib\Entities\Payment();
                            $payment
                                ->set( 'type',    Lib\Entities\Payment::TYPE_MELLAT )
                                ->set( 'status',  Lib\Entities\Payment::STATUS_COMPLETED )
                                ->set( 'total',   $total )
                                ->set( 'paid',    $deposit )
								->set( 'paid_type', $total == $deposit ? Lib\Entities\Payment::PAY_IN_FULL : Lib\Entities\Payment::PAY_DEPOSIT )
                                //->set( 'token',   intval($response['refid']) )
                                ->set( 'created', current_time( 'mysql' ) )
                                ->save();
                            $ca_list = $userData->save( $payment->get( 'id' ) );
                            Lib\NotificationSender::sendFromCart( $ca_list );
                            $payment->setDetails( $ca_list, $coupon )->save();
							$userData->setPaymentStatus( Lib\Entities\Payment::TYPE_MELLAT, 'success' );
                        
                        @wp_redirect( remove_query_arg( Lib\Payment\Mellat::$remove_parameters, Lib\Utils\Common::getCurrentPageURL() ) );*/
                        exit;
            } else {
                $error_message = $response["msg"];
			}
        
        if ( ! empty( $error_message ) ) {
            header( 'Location: ' . wp_sanitize_redirect( add_query_arg( array(
                    'bookly_action'    => 'mellat-ec-error',
                    'bookly_fid'    => $form_id,
                    'error_msg' => urlencode( $error_message ),
                ), Common::getCurrentPageURL()
                ) ) );
            exit;
        }
    }
	
    /**
     * Process Express Checkout cancel request.
     */
    public static function ecCancel()
    {
        $userData = new UserBookingData( self::parameter( 'bookly_fid' ) );
        $userData->load();
        $userData->setPaymentStatus( Payment::TYPE_MELLAT, 'cancelled' );
		$userData->sessionSave();
		
        @wp_redirect( remove_query_arg( Mellat::$remove_parameters, Common::getCurrentPageURL() ) );
        exit;
    }

    /**
     * Process Express Checkout error request.
     */
    public static function ecError()
    {
        $userData = new UserBookingData( self::parameter( 'bookly_fid' ) );
        $userData->load();
        $userData->setPaymentStatus( Payment::TYPE_MELLAT, 'error', self::parameter( 'error_msg' ) );
		$userData->sessionSave();
		
        @wp_redirect( remove_query_arg( Mellat::$remove_parameters, Common::getCurrentPageURL() ) );
        exit;
    }
}