<?php
/**
 * Custom Offline Payments Gateway
 */

class TC_Gateway_Custom_Offline_Payments extends TC_Gateway_API {

    var $plugin_name = 'custom_offline_payments';
    var $admin_name = '';
    var $public_name = '';
    var $method_img_url = '';
    var $admin_img_url = '';
    var $force_ssl = false;
    var $ipn_url;
    var $automatically_activated = false;
    var $skip_payment_screen = false;

    /**
     * Support for older payment gateway API
     */
    function on_creation() {
        $this->init();
    }

    function init() {
        global $tc;

        $this->skip_payment_screen = apply_filters( $this->plugin_name . '_skip_payment_screen', $this->skip_payment_screen );
        $this->admin_name = $this->get_option( 'admin_name', __( 'Offline Payment', 'tc' ) );
        $this->public_name = $this->get_option( 'public_name', __( 'Cash on Delivery', 'tc' ) );

        $this->method_img_url = apply_filters( 'tc_gateway_method_img_url', $tc->plugin_url . 'images/gateways/custom-offline-payments.png', $this->plugin_name );
        $this->admin_img_url = apply_filters( 'tc_gateway_admin_img_url', $tc->plugin_url . 'images/gateways/small-custom-offline-payments.png', $this->plugin_name );

        add_action( 'tc_order_created', array( &$this, 'send_payment_instructions' ), 10, 5 );
        add_filter( $this->plugin_name . '_instructions', array( &$this, 'modify_instruction_message' ), 10, 2 );
    }

    function payment_form( $cart ) {
        return $this->get_option( 'info' );
    }

    function modify_instruction_message( $message, $order_id ) {

        if ( ! is_int( $order_id ) ) {
            $order = tc_get_order_id_by_name( $order_id );
            $order = new TC_Order( $order->ID );

        } else {
            $order = new TC_Order( $order_id );
        }

        $payment_info = get_post_meta( $order->id, 'tc_payment_info', true );
        $cart_info = get_post_meta( $order->id, 'tc_cart_info', true );
        $buyer_name = $cart_info[ 'buyer_data' ][ 'first_name_post_meta' ] . ' ' . $cart_info[ 'buyer_data' ][ 'last_name_post_meta' ];

        $placeholders = array( 'ORDER_ID', 'ORDER_TOTAL', 'BUYER_NAME' );
        $placeholder_values = array( strtoupper( $order->details->post_title ), tc_esc_html( apply_filters( 'tc_cart_currency_and_format', $payment_info[ 'total' ] ) ), $buyer_name );

        $message = str_replace( $placeholders, $placeholder_values, $message );

        return $message;
    }

    function send_payment_instructions( $order_id, $status, $cart_contents, $cart_info, $payment_info ) {

        global $order_instructions_sent;

        if ( $payment_info[ 'gateway_private_name' ] == $this->admin_name ) {

            $send_instructions = $this->get_option( 'instructions_email', 'no' ) == 'yes';

            if ( 'yes' == $send_instructions && 'order_received' == $status ) {

                add_filter( 'wp_mail_content_type', 'set_content_type' );
                add_filter( 'wp_mail_from', 'client_email_from_email', 999 );
                add_filter( 'wp_mail_from_name', 'client_email_from_name', 999 );

                $client_headers = '';
                $to = $this->buyer_info( 'email' );
                $message = apply_filters( $this->plugin_name . '_instructions', $this->get_option( 'instructions' ), $order_id );
                $subject = $this->get_option( 'instructions_email_subject' );

                if ( $order_instructions_sent !== $this->buyer_info( 'email' ) && ! empty( trim( $message ) ) ) {
                    @wp_mail( sanitize_email( $to ), sanitize_text_field( stripslashes( $subject ) ), tc_sanitize_string( apply_filters( 'tc_order_created_client_email_message', stripcslashes( wpautop( $message ) ) ) ), tc_sanitize_array2( apply_filters( 'tc_order_created_client_email_headers', $client_headers ) ) );
                    $order_instructions_sent = $this->buyer_info( 'email' );
                }
            }
        }
    }

    function process_payment( $cart ) {

        global $tc;

        tc_final_cart_check( $cart );
        $this->save_cart_info();
        $order_id = $tc->generate_order_id();

        $payment_info = [];
        $payment_info[ 'currency' ] = $tc->get_cart_currency();
        $payment_info = $this->save_payment_info( $payment_info );
        $tc->create_order( $order_id, $this->cart_contents(), $this->cart_info(), $payment_info, false );
        tc_redirect( $tc->get_confirmation_slug( true, $order_id ), true );
    }

    function order_confirmation( $order, $payment_info = '', $cart_info = '' ) {

        global $tc;

        $session = $tc->session->get();
        $tc_payment_info = isset( $session[ 'tc_payment_info' ] ) ? tc_sanitize_array2( $session[ 'tc_payment_info' ] ) : tc_sanitize_array2( $payment_info );
        $total = (float) $tc_payment_info[ 'total' ];
        $automatic_status = $this->get_option( 'automatic_status' );
        $paid = false;

        // Get default status for 100% discount and/or free orders
        if ( $total > 0 ) {
            $paid = ( 'order_paid' == $automatic_status ) ? true : false;
        }

        $order = tc_get_order_id_by_name( $order );
        $tc->update_order_payment_status( $order->ID, $paid );
    }

    /**
     * Generate Order Confirmation Page upon success checkout
     *
     * @param $order
     * @param string $cart_info
     * @return string
     */
    function order_confirmation_message( $order, $cart_info = '' ) {

        global $tc;

        $order = tc_get_order_id_by_name( $order );
        $order = new TC_Order( $order->ID );
        $content = '';

        switch ( $order->details->post_status ) {

            case 'order_received':
                $content .= '<p>' . sprintf( __( 'Your payment via %s for this order totaling <strong>%s</strong> is not yet complete.', 'tc' ), $this->public_name, apply_filters( 'tc_cart_currency_and_format', $order->details->tc_payment_info[ 'total' ] ) ) . '</p>';
                $content .= '<p>' . __( 'Current order status:', 'tc' ) . ' <strong>' . __( 'Pending Payment', 'tc' ) . '</strong></p>';
                break;

            case 'order_fraud':
                $content .= '<p>' . __( 'Your payment is under review. We will back to you soon.', 'tc' ) . '</p>';
                break;

            case 'order_paid':
                $content .= '<p>' . sprintf( __( 'Your payment via %s for this order totaling <strong>%s</strong> is complete.', 'tc' ), $this->public_name, apply_filters( 'tc_cart_currency_and_format', $order->details->tc_payment_info[ 'total' ] ) ) . '</p>';
                break;

            case 'order_cancelled':
                $content .= '<p>' . sprintf( __( 'Your payment via %s for this order totaling <strong>%s</strong> is cancelled.', 'tc' ), $this->public_name, apply_filters( 'tc_cart_currency_and_format', $order->details->tc_payment_info[ 'total' ] ) ) . '</p>';
                break;

            case 'order_refunded':
                $content .= '<p>' . sprintf( __( 'Your payment via %s for this order totaling <strong>%s</strong> is refunded.', 'tc' ), $this->public_name, apply_filters( 'tc_cart_currency_and_format', $order->details->tc_payment_info[ 'total' ] ) ) . '</p>';
                break;

        }

        $content = tc_esc_html( apply_filters( 'tc_order_confirmation_message_content_' . $this->plugin_name, $content ) );
        $content = tc_esc_html( apply_filters( 'tc_order_confirmation_message_content', $content, $order ) );

        $content .= '<br /><br />' . tc_esc_html( apply_filters( $this->plugin_name . '_instructions', $tc->get_setting( 'gateways->custom_offline_payments->instructions' ), $order->details->ID ) );

        $tc->remove_order_session_data();
        $tc->maybe_skip_confirmation_screen( $this, $order );

        return stripcslashes( wpautop( $content ) );
    }

    function gateway_admin_settings( $settings, $visible ) {
        ?>
        <div id="<?php echo esc_attr( $this->plugin_name ); ?>" class="postbox" <?php echo( ! $visible ? 'style="display:none;"' : '' ); ?>>
            <h3><span><?php printf( __( '%s Settings', 'tc' ), wp_unslash( $this->admin_name ) ); ?></span>
                <span class="description"><?php _e( 'A simple pass-thru payment method for accepting offline payments (Cash on Delivery, Money Orders, Bank Deposits, Cheques etc.)', 'tc' ) ?></span>
            </h3>
            <div class="inside">
                <?php
                $fields = array(
                    'public_name' => array(
                        'title' => __( 'Public title', 'tc' ),
                        'type' => 'text',
                        'description' => __( 'Enter the title of this payment method that will be visible to customers on the front end (eg. Cash on delivery, Checque payment, etc.)', 'tc' ),
                        'default' => $this->public_name
                    ),
                    'admin_name' => array(
                        'title' => __( 'Admin title', 'tc' ),
                        'type' => 'text',
                        'description' => __( 'Enter the title of this pamyment method that will be used in the back end (admin) area of your website', 'tc' ),
                        'default' => $this->admin_name
                    ),
                    'info' => array(
                        'title' => __( 'Payment method additional info', 'tc' ),
                        'type' => 'wp_editor',
                        'description' => __( 'Additional information that will be visible to the customers on the front end when they select this payment method', 'tc' )
                    ),
                    'instructions' => array(
                        'title' => __( 'Payment instruction', 'tc' ),
                        'type' => 'wp_editor',
                        'description' => __( 'The instruction that will be displayed to customers once they finish the checkout using this payment method. You can use the following placeholders: ORDER_ID, ORDER_TOTAL, BUYER_NAME', 'tc' )
                    ),
                    'instructions_email' => array(
                        'title' => __( 'Send instruction via email', 'tc' ),
                        'type' => 'select',
                        'options' => array(
                            'no' => __( 'No', 'tc' ),
                            'yes' => __( 'Yes', 'tc' )
                        ),
                        'default' => 'no',
                        'description' => __( 'Choose Yes if you want to send an email with the payment instruction to the customer once they finish their order. The e-mail will be sent only the order has a status "Order Received".', 'tc' )
                    ),
                    'instructions_email_subject' => array(
                        'title' => __( 'Instruction email subject', 'tc' ),
                        'type' => 'text',
                        'default' => __( 'Payment instruction', 'tc' )
                    ),
                    'automatic_status' => array(
                        'title' => __( 'Automatic payment status', 'tc' ),
                        'type' => 'select',
                        'options' => array(
                            'order_received' => __( 'Order Received', 'tc' ),
                            'order_paid' => __( 'Order Paid', 'tc' )
                        ),
                        'default' => 'order_received',
                        'description' => __( 'Set the payment status for the orders made using this payment method. If you want customers to receive their tickets immediately upon finishing the checkout using this payment method, select "Order Paid"', 'tc' )
                    ),
                    'admin_gateway' => array(
                        'title' => __( 'Visible to admins only', 'tc' ),
                        'type' => 'select',
                        'options' => array(
                            'no' => __( 'No', 'tc' ),
                            'yes' => __( 'Yes', 'tc' )
                        ),
                        'default' => 'no',
                        'description' => __( 'Select whether you want this payment method to be available to website admins only', 'tc' )
                    ),
                );

                $form = new TC_Form_Fields_API( $fields, 'tc', 'gateways', $this->plugin_name );
                ?>
                <table class="form-table">
                    <?php $form->admin_options(); ?>
                </table>
            </div>
        </div>
        <?php
    }
}

tc_register_gateway_plugin( 'TC_Gateway_Custom_Offline_Payments', 'custom_offline_payments', __( 'Offline Payments', 'tc' ) );
