<?php 
/**
 * ST_ProQyz_Activity_Rest
 *
 * @package Spacetree/lib/proqyz/writing
 * @since   2.0.3.1
 * v2.1.0 - updated (testing - copy of vscode php)
 */

defined( 'ABSPATH' ) || exit;

class ST_ProQyz_Activity_Rest {

    /**
     * ST_ProQyz_Activity_Rest version.
     *
     * @var string
     */
    public $version = '1.0.0';
    public $review_id = null;

    protected static $_instance = null;

    /**
     * Main ST_ProQyz_Activity_Rest Instance.
     *
     * Ensures only one instance of ST_ProQyz_Activity_Rest is loaded or can be loaded.
     *
     * @since 1.0
     * @static
     * @return ST_ProQyz_Activity_Rest - Main instance.
     */
    public static function instance() {
        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * Constructor method to initialize the plugin.
     */
    public function __construct() {
        $this->includes();
        $this->register_rest_api_routes();
        $this->add_cors_support();
    }

    /**
     * Include necessary files (if any).
     */
    public function includes() {
        // Include other necessary files if needed.
    }

    /**
     * Register REST API routes.
     */
    public function register_rest_api_routes() {
        add_action('rest_api_init', [$this, 'register_proqyz_activity_route']);
    }

    /**
     * Register the REST API route for AI evaluation.
     */
    public function register_proqyz_activity_route() {
        register_rest_route('spacetree/proqyz', '/activity', [
            'methods'  => 'GET',
            'callback' => [$this, 'handle_proqyz_activity_request'],
            'permission_callback' => '__return_true', // Handle permissions here as necessary
        ]);

        register_rest_route('spacetree/proqyz', '/stats', [
            'methods'  => 'GET',
            'callback' => [$this, 'handle_proqyz_stats_request'],
            'permission_callback' => '__return_true', // Handle permissions here as necessary
        ]);
    }

    /**
     * Handle the ProQyz Activity request.
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function handle_proqyz_activity_request($request) {
        // Ensure the script continues processing even if the user disconnects
        ignore_user_abort(true);

        // Perform AI evaluation processing here (e.g., saving to database or calling external APIs)
        global $wpdb, 
        $table_proqyz_v3_progress_submissions;

        $writing_count = $wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$table_proqyz_v3_progress_submissions} 
            WHERE `status` = 1 
            AND `quiz_category` = 'ielts-writing' 
            AND `session_status` = 1
        ");

        $reading_count = $wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$table_proqyz_v3_progress_submissions} 
            WHERE `status` = 1 
            AND `quiz_category` = 'ielts-reading' 
            AND `session_status` = 1
        ");

        $listening_count = $wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$table_proqyz_v3_progress_submissions} 
            WHERE `status` = 1 
            AND `quiz_category` = 'ielts-listening' 
            AND `session_status` = 1
        ");

        $speaking_count = $wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$table_proqyz_v3_progress_submissions} 
            WHERE `status` = 1 
            AND `quiz_category` = 'ielts-speaking' 
            AND `session_status` = 1
        ");

        // todays only
        // Calculate start and end of the day
        $start_of_day = strtotime('today midnight'); // 00:00:00 of today
        $end_of_day = strtotime('tomorrow midnight') - 1; // 23:59:59 of today

        // Query for today's rows
        $writing_todays = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) 
            FROM {$table_proqyz_v3_progress_submissions} 
            WHERE `status` = 1 
            AND `quiz_category` = 'ielts-writing' 
            AND `session_status` = 1
            AND `date` BETWEEN %d AND %d
        ", $start_of_day, $end_of_day));

        $reading_todays = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) 
            FROM {$table_proqyz_v3_progress_submissions} 
            WHERE `status` = 1 
            AND `quiz_category` = 'ielts-reading' 
            AND `session_status` = 1
            AND `date` BETWEEN %d AND %d
        ", $start_of_day, $end_of_day));

        $listening_todays = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) 
            FROM {$table_proqyz_v3_progress_submissions} 
            WHERE `status` = 1 
            AND `quiz_category` = 'ielts-listening' 
            AND `session_status` = 1
            AND `date` BETWEEN %d AND %d
        ", $start_of_day, $end_of_day));

        $speaking_todays = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) 
            FROM {$table_proqyz_progress_submissions} 
            WHERE `status` = 1 
            AND `quiz_category` = 'ielts-speaking' 
            AND `session_status` = 1
            AND `date` BETWEEN %d AND %d
        ", $start_of_day, $end_of_day));

        // Calculate start and end of the current month
        $start_of_month = strtotime('first day of this month midnight'); // 00:00:00 on the 1st of this month
        $end_of_month = strtotime('first day of next month midnight') - 1; // 23:59:59 on the last day of this month

        // Query for rows within the current month
        $writing_this_month = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) 
            FROM {$table_proqyz_v3_progress_submissions} 
            WHERE `status` = 1 
            AND `quiz_category` = 'ielts-writing' 
            AND `session_status` = 1
            AND `date` BETWEEN %d AND %d
        ", $start_of_month, $end_of_month));

        $speaking_this_month = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) 
            FROM {$table_proqyz_v3_progress_submissions} 
            WHERE `status` = 1 
            AND `quiz_category` = 'ielts-speaking' 
            AND `session_status` = 1
            AND `date` BETWEEN %d AND %d
        ", $start_of_month, $end_of_month));

        $reading_this_month = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) 
            FROM {$table_proqyz_v3_progress_submissions} 
            WHERE `status` = 1 
            AND `quiz_category` = 'ielts-reading' 
            AND `session_status` = 1
            AND `date` BETWEEN %d AND %d
        ", $start_of_month, $end_of_month));

        $listening_this_month = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) 
            FROM {$table_proqyz_v3_progress_submissions} 
            WHERE `status` = 1 
            AND `quiz_category` = 'ielts-listening' 
            AND `session_status` = 1
            AND `date` BETWEEN %d AND %d
        ", $start_of_month, $end_of_month));

        return new WP_REST_Response([
            'success'  => (object) [
                "message"   => 'Count of activities retrieved successfully',
                "month"     => (object) [
                    "writing"   => $writing_this_month,
                    "speaking"  => $speaking_this_month,
                    "reading"   => $reading_this_month,
                    "listening" => $listening_this_month,
                    "total"     => ($writing_this_month + $speaking_this_month + $reading_this_month + $listening_this_month)
                ],
                "overall"   => (object) [
                    "writing"   => $writing_count,
                    "reading"   => $reading_count,
                    "listening" => $listening_count,
                    "speaking"   => $speaking_count,
                    "total"     => ($writing_count + $reading_count + $listening_count + $speaking_count)
                ],
                "today"    => (object) [
                    "writing"   => $writing_todays,
                    "speaking"  => $speaking_todays,
                    "reading"   => $reading_todays,
                    "listening" => $listening_todays,
                    "total"     => ($writing_todays + $speaking_todays + $reading_todays + $listening_todays)
                ]
            ]
        ], 200);


    }

    /**
     * Handle the ProQyz stats request
     * 
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function handle_proqyz_stats_request($request) {
        // Ensure the script continues processing even if the user disconnects
        ignore_user_abort(true);

        global $st_version_key, $st_maintenance_key;
		$get_pre_version 		= get_option($st_version_key, '1.0.0');
		$get_pre_fix_version	= get_option($st_maintenance_key,'1.0.0');

        $proqyz_version     = $get_pre_version;
        $proqyz_fix_version  = $get_pre_fix_version;
        $wordpress_version  = get_bloginfo('version');
        $php_version        = phpversion(); 


        
        return new WP_REST_Response([
            'success'  => (object) [
                "message"   => 'Count of activities retrieved successfully',
                "proqyz"     => (object) [
                    "version"   => $proqyz_version,
                    "fix_version" => $proqyz_fix_version
                ],
                "wordpress"   => (object) [
                    "version"   => $wordpress_version,
                ],
                "php"        => (object) [
                    "version"   => $php_version,
                ]
            ]
        ], 200);

    }

    /**
     * Add CORS headers to allow all origins.
     */
    public function add_cors_support() {
        add_action('rest_api_init', function () {
            add_filter('rest_pre_serve_request', function ($value) {
                header('Access-Control-Allow-Origin: *');
                header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
                header('Access-Control-Allow-Credentials: true');
                header('Access-Control-Allow-Headers: Authorization, Content-Type');
                return $value;
            });
        });
    }

}

// Instantiate the plugin class
return ST_ProQyz_Activity_Rest::instance();
