<?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;
}

/**
 * Logs
 */
class Logs {

	public function log_cembrapay_api_request( $data = array() ) {

        if( ! $data ) {
            return;
        }

        $order_id     = isset( $data['order_id'] ) ? $data['order_id'] : 0;
        $url          = isset( $data['url'] ) ? $data['url'] : '';
		$first_name   = isset( $data['first_name'] ) ? $data['first_name'] : '';
		$last_name    = isset( $data['last_name'] ) ? $data['last_name'] : '';
		$req_type     = isset( $data['req_type'] ) ? $data['req_type'] : '';
		$proc_status  = isset( $data['proc_status'] ) ? $data['proc_status'] : '';
        $request_args = isset( $data['request_args'] ) ? $data['request_args'] : array();
        $response     = isset( $data['response'] ) ? $data['response'] : '';
        $body         = isset( $data['body'] ) ? $data['body'] : '';
        $date         = isset( $data['date'] ) ? $data['date'] : new \DateTime();

        global $wpdb;

        $cembrapay_settings = Service::get_payment_gateway_settings();

        if( isset( $cembrapay_settings['logs_enable'] ) && $cembrapay_settings['logs_enable'] == 1 ) {

			$request_args['body'] = is_string( $request_args['body'] ) ? json_decode($request_args['body'], true) : $request_args['body'];

            $wpdb->insert(
                CEMBRA_LOGS_TABLE,
                array(
                    'order_id'    => $order_id,
					'first_name'  => $first_name,
					'last_name'   => $last_name,
					'req_type'    => $req_type,
					'proc_status' => $proc_status,
                    'request'     => json_encode( array( 'url' => $url, 'args' => $request_args ) ),
                    'response'    => is_wp_error( $response ) ? json_encode( $response ) : ( $body ? json_encode( $body ) : '' ),
                    'datetime'    => $date->format('Y-m-d H:i:s')
                )
            );
            
        }

    }

    public function logs_cleanup() {

        $cembrapay_settings = Service::get_payment_gateway_settings();
        $logs_enabled = $cembrapay_settings['logs_enable'];
        $logs_deletion = $cembrapay_settings['logs_deletion'];

        if( ! $logs_enabled || $logs_deletion == 5 ) {
            return;
        }

        $now = new \DateTime();
        $target_date = '';

        switch( $logs_deletion ) {
            case 1:
                $now->modify('-30 days');
                $target_date = $now->format('Y-m-d 00:00:00');
            break;
            case 2:
                $now->modify('-3 months');
                $target_date = $now->format('Y-m-d 00:00:00');
            break;
            case 3:
                $now->modify('-6 months');
                $target_date = $now->format('Y-m-d 00:00:00');
            break;
            case 4:
                $now->modify('-12 months');
                $target_date = $now->format('Y-m-d 00:00:00');
            break;
        }

        global $wpdb;

        $logs = $wpdb->get_results( 
            $wpdb->prepare( 
                "SELECT * FROM %1s WHERE datetime < '%2s'", 
                CEMBRA_LOGS_TABLE,
                $target_date
            )
        );

        if( $logs ) {
            foreach( $logs as $log ) {
                $wpdb->delete( CEMBRA_LOGS_TABLE, array( 'id' => $log->id ) );
            }
        }

    }

}

class LogsActions {

    function __construct() {

        add_action( 'admin_enqueue_scripts', array($this, 'scripts'), 200 );

		$ajax_actions = array(
			'get_logs',
			'delete_log'
		);

		foreach( $ajax_actions as $action ) {
			add_action( 'wp_ajax_' . $action, array($this, $action) );
			add_action( 'wp_ajax_nopriv_' . $action, array($this, $action) );
		}

        add_action('init', array($this, 'logs_cleanup_cron') );
        add_action('cembrapay_logs_cleanup_cron', array( $this, 'clean_logs' ));

	}

    function scripts() {

        $page    = isset($_GET['page']) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
        $tab     = isset($_GET['tab']) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : '';
        $section = isset($_GET['section']) ? sanitize_text_field( wp_unslash( $_GET['section'] ) ) : '';

        if(
			$page && $page == 'wc-settings'
            && $tab && $tab == 'checkout'
            && $section && $section == 'cembrapay'
		) {

			include( CEMBRAPATH . 'inc/data/strings.php' );

			$dateLastMonth = new \DateTime();
			$dateLastMonth->modify('-1 month');

			$today = new \DateTime();

			wp_enqueue_script( 'jquery-ui-datepicker' );
			wp_enqueue_script( 'cembrapay-admin-logs', CEMBRAURL . 'assets/build/admin/logs.js', array( 'jquery' ), '', true );
			wp_enqueue_style( 'cembrapay-admin-logs-css', CEMBRAURL . 'assets/css/admin/logs.css' );
            wp_enqueue_style( 'cembrapay-admin-logs-js', CEMBRAURL . 'assets/css/admin/logs-js.css' );
			wp_localize_script( 'cembrapay-admin-logs', 'cembrapayLogs', array(
				'ajaxUrl'     => admin_url('admin-ajax.php'),
				'nonceGet'    => wp_create_nonce('get_logs'),
				'nonceDelete' => wp_create_nonce('delete_log'),
				'pluginUrl'   => CEMBRAURL,
				'lastMonth'   => $dateLastMonth->format('Y-m-d'),
				'today'       => $today->format('Y-m-d'),
				'strings'     => $logs_strings
			));

		}

    }

    function get_logs() {

		if ( ! isset( $_POST['security'] ) || ! wp_verify_nonce( $_POST['security'], 'get_logs' ) ) {
			wp_send_json_error( array('message' => esc_html__( 'Security verification failed', 'cembrapay' ) ) );
		}

		global $wpdb;

		$filters = isset($_POST['filters']) ? array_map( 'sanitize_text_field', array_map( 'wp_unslash', $_POST['filters'] ) ) : array();
		$page    = isset($_POST['page']) ? abs( sanitize_text_field( wp_unslash( $_POST['page'] ) ) ) : 0;
		$offset  = $page * 20;

		$date_from           = isset($filters['dateFrom']) ? $filters['dateFrom'] . ' 00:00:00' : '';
		$date_to             = isset($filters['dateTo']) ? $filters['dateTo'] . ' 23:59:59' : '';
		$customer_first_name = isset($filters['customerFirstName']) ? $filters['customerFirstName'] : '';
		$customer_last_name  = isset($filters['customerLastName']) ? $filters['customerLastName'] : '';
		$order_id            = isset($filters['orderId']) ? $filters['orderId'] : '';
		$request_type        = isset($filters['requestType']) ? $filters['requestType'] : '';
		$relationship        = isset($filters['relationship']) ? $filters['relationship'] : '';

		$query = $wpdb->prepare( "SELECT * FROM %1s", CEMBRA_LOGS_TABLE );

		if( ( $date_from && $date_to ) || $customer_first_name || $customer_last_name || $order_id || $request_type ) {
			$query .= " WHERE 1=1";
		}

		if( $order_id ) {

			//Only filter by order ID, disregard other filters

			$query .= $wpdb->prepare( " AND order_id = %1d", $order_id );

		} else {

			if( $date_from && $date_to ) {
				$query .= $wpdb->prepare( " AND datetime BETWEEN '%1s' AND '%2s'", $date_from, $date_to );
			}

			if( $customer_first_name ) {
				$customer_first_name = '%' . $wpdb->esc_like( $customer_first_name ) . '%';
				$query .= $wpdb->prepare( " %1s first_name LIKE '%2s'", $relationship, $customer_first_name );
			}

			if( $customer_last_name ) {
				$customer_last_name = '%' . $wpdb->esc_like( $customer_last_name ) . '%';
				$query .= $wpdb->prepare( " %1s last_name LIKE '%2s'", $relationship, $customer_last_name );
			}

			if( $request_type ) {
				$query .= $wpdb->prepare( " %1s req_type = '%s'", $relationship, $request_type );
			}

		}

		$query .= " ORDER BY datetime DESC LIMIT 20 OFFSET " . $offset;

		
		$logs = $wpdb->get_results( $query, ARRAY_A );

		if( is_wp_error( $logs ) ) {
			wp_send_json_error( $logs );
		}

		if( $logs ) {
			wp_send_json_success( array( 'logs' => $logs ) );
		}

		wp_send_json_error( array('message' => esc_html__( 'Reached the end of the logs query. No more logs found.', 'cembrapay' )) );

	}

	function delete_log() {

		if ( ! isset( $_POST['security'] ) || ! wp_verify_nonce( $_POST['security'], 'delete_log' ) ) {
			wp_send_json_error( array('message' => esc_html__( 'Security verification failed', 'cembrapay' ) ) );
		}

		$log_id = isset($_POST['logId']) ? sanitize_text_field( wp_unslash( $_POST['logId'] ) ) : '';

		if( ! $log_id ) {
			wp_send_json_error( array('message' => 'Log ID is required') );
		}

		global $wpdb;

		$delete = $wpdb->delete( CEMBRA_LOGS_TABLE, array( 'id' => $log_id ) );

		if( $delete ) {
			wp_send_json_success( array('message' => esc_html__( 'Log deleted', 'cembrapay' )) );
		}

		wp_send_json_error( array('message' => esc_html__( 'Failed to delete log', 'cembrapay' )) );

	}

    function logs_cleanup_cron() {

        $use_action_scheduler = false;

        if( class_exists('ActionScheduler') && function_exists('as_next_scheduled_action') && function_exists('as_schedule_recurring_action') ) {
            $use_action_scheduler = true;
        }

        if( $use_action_scheduler ) {
            if ( ! \as_next_scheduled_action('cembrapay_logs_cleanup_cron')) {
                \as_schedule_recurring_action(strtotime('00:00:00'), DAY_IN_SECONDS, 'cembrapay_logs_cleanup_cron');
            }
        }

        if( ! $use_action_scheduler ) {
            if ( ! \wp_next_scheduled('cembrapay_logs_cleanup_cron') ) {
                \wp_schedule_event(strtotime('00:00:00'), 'daily', 'cembrapay_logs_cleanup_cron');
            }
        }

    }

    function clean_logs() {

        $logs = new Logs;
        $logs = $logs->logs_cleanup();

    }

}
?>