<?php
namespace WoolentorPro\Modules\FreeShippingBar\Frontend;
use WooLentorPro\Traits\Singleton;
use WoolentorPro\Modules\FreeShippingBar\Free_Shipping_Bar_Pro;

if ( ! defined( 'ABSPATH' ) ) exit;

class Analytics {
    use Singleton;

    private function __construct() {
        add_action( 'wp_ajax_woolentor_fsb_track',          [ $this, 'track_event' ] );
        add_action( 'wp_ajax_nopriv_woolentor_fsb_track',   [ $this, 'track_event' ] );
        add_action( 'wp_ajax_woolentor_fsb_get_analytics',  [ $this, 'get_analytics_data' ] );
        add_action( 'wp_ajax_woolentor_fsb_reset_analytics',[ $this, 'reset_analytics_data' ] );
    }

    public function track_event() {
        check_ajax_referer( 'woolentor-fsb-analytics', 'nonce' );

        if ( Free_Shipping_Bar_Pro::setting( 'enable_analytics', 'off' ) !== 'on' ) {
            wp_send_json_error( [ 'message' => 'Analytics disabled.' ] );
            return;
        }

        $event_type = isset( $_POST['event_type'] ) ? sanitize_key( $_POST['event_type'] ) : '';
        if ( ! in_array( $event_type, [ 'impression', 'conversion' ], true ) ) {
            wp_send_json_error( [ 'message' => 'Invalid event type.' ] );
            return;
        }

        $bar_id  = isset( $_POST['bar_id'] )  ? sanitize_key( $_POST['bar_id'] )  : 'default';
        $variant = isset( $_POST['variant'] ) ? sanitize_key( $_POST['variant'] ) : '';
        $date    = current_time( 'Y-m-d' );

        $stats = get_option( Free_Shipping_Bar_Pro::ANALYTICS_OPTION, [] );

        $key = $date . '|' . $bar_id . '|' . $event_type . ( $variant ? '|' . $variant : '' );
        $stats[ $key ] = ( $stats[ $key ] ?? 0 ) + 1;

        update_option( Free_Shipping_Bar_Pro::ANALYTICS_OPTION, $stats, false );

        wp_send_json_success( [ 'tracked' => true ] );
    }

    public function get_analytics_data() {
        check_ajax_referer( 'ajax-nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => 'Unauthorized.' ] );
            return;
        }

        $raw  = get_option( Free_Shipping_Bar_Pro::ANALYTICS_OPTION, [] );
        $rows = [];

        foreach ( $raw as $key => $count ) {
            $parts = explode( '|', $key );
            if ( count( $parts ) < 3 ) continue;

            $rows[] = [
                'date'       => $parts[0],
                'bar_id'     => $parts[1],
                'event_type' => $parts[2],
                'variant'    => $parts[3] ?? '',
                'count'      => (int) $count,
            ];
        }

        wp_send_json_success( [ 'rows' => $rows ] );
    }

    public function reset_analytics_data() {
        check_ajax_referer( 'ajax-nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => 'Unauthorized.' ] );
            return;
        }

        delete_option( Free_Shipping_Bar_Pro::ANALYTICS_OPTION );
        wp_send_json_success( [ 'reset' => true ] );
    }
}
