<?php
/**
* @package CembraPay Payment Gateway for WooCommerce
* @author  Adrian Emil Tudorache
* @license GPL-2.0+
* @link    https://www.tudorache.me/
*/

namespace CembraPayWoo;

if ( ! defined( 'ABSPATH' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	exit;
}

/**
 * Admin REST endpoints
 */
class REST {

    /**
     * Constructor
     */
    public function __construct() {
        add_action( 'rest_api_init', array( $this, 'routes' ) );
    }

    /**
     * Authenticate user using Basic Auth
     * The user needs to exist and have the 'administrator' role
     * on the current website
     * 
     * @param \WP_REST_Request $request
     * 
     * @return bool
     */
	public function auth_user( \WP_REST_Request $request ): bool {
		
		$valid = false;
  
		$headers = $request->get_headers();
  
		if( isset( $headers['authorization'] ) && isset( $headers['authorization'][0] ) ) {
			$auth = str_replace('Basic ', '', $headers['authorization'][0]);
			$auth = base64_decode( $auth );
			$auth = explode( ':', $auth );
			$user = isset( $auth[0] ) && isset( $auth[1] ) ? wp_authenticate( $auth[0], $auth[1] ) : null;
			if( ! is_wp_error( $user ) && isset( $user->caps['administrator'] ) ) {
				$valid = true;
			}
		}
  
		return $valid;
  
	}

    /**
     * Register REST routes
     * 
     * @return void
     */
    public function routes() {

        $namespace = 'cembrapay/v1';

        register_rest_route( $namespace, '/get-connection-status', array(
            'methods'  => \WP_REST_Server::READABLE,
            'callback' => array( $this, 'get_connection_status' ),
			'permission_callback' => function ($request) {
				return current_user_can( 'manage_options' ) || $this->auth_user( $request );
			}
        ) );

        register_rest_route( $namespace, '/get-cembrapay-order-status', array(
            'methods'  => \WP_REST_Server::CREATABLE,
            'callback' => array( $this, 'get_cembrapay_order_status' ),
			'permission_callback' => function ($request) {
				return current_user_can( 'manage_options' ) || $this->auth_user( $request );
			},
            'args' 	   => array(
                'orderId' => array(
					'required' => true,
                    'sanitize_callback' => function( $value, $request, $param ) {
                        return sanitize_text_field( esc_html( $value ) );
                    },
                    'validate_callback' => function( $value, $request, $param ) {
                        return is_numeric( $value );
                    }
                ),
            )
        ) );

    }

    /**
     * Get CembraPay API connection status
     * 
     * @param \WP_REST_Request $request
     * 
     * @return \WP_REST_Response
     */
    public function get_connection_status( \WP_REST_Request $request ): \WP_REST_Response {

        $cembrapay = new CembraPay;
        
        $token = $cembrapay->token();

        return new \WP_REST_Response( array(
            'status'  => $token ? 1 : 0,
            'message' => $token ? esc_html__( 'Connected', 'cembrapay' ) : esc_html__( 'Disconnected', 'cembrapay' )
        ), 200 );

    }

    public function get_cembrapay_order_status( \WP_REST_Request $request ): \WP_REST_Response {
            
        $order_id = $request['orderId'];

        $cembrapay = new CembraPay( $order_id, 'status' );
		$status = $cembrapay->request();

        $order = wc_get_order( $order_id );

        $status_checks = $order->get_meta( '_cembrapay_status_checks', true );

        $date = new \DateTime();

        $last_check = null;
        $date_format = null;
        $time_format = null;
        
        if( $status_checks ) {

            $last_status_check_key = array_key_last($status_checks);
            $last_check = $status_checks[ $last_status_check_key ];
            unset($status_checks[ $last_status_check_key ]);

            $date->setTimestamp($last_status_check_key);

            $date_format = get_option('date_format');
            $time_format = get_option('time_format');

            foreach( $status_checks as $timestamp => $status_check ) {
                $status_checks[$timestamp]['date'] = (new \DateTime())->setTimestamp($timestamp)->format( $date_format . ' ' . $time_format );
            }
            
        }
    
        return new \WP_REST_Response( array(
            'lastCheck' => $last_check,
            'lastCheckDateTime' => $date->format( $date_format . ' ' . $time_format ),
            'moreChecks' => $status_checks,
        ), 200 );

    }

}
?>