<?php
/**
 * Class ZUTALW_License_Manager
 * Handles license activation and periodic validation against the Django backend.
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

class ZUTALW_License_Manager {

    const OPTION_KEY = 'zutalw_license_info';

    public function __construct() {
        add_action( 'zutalw_daily_license_check', array( $this, 'check_license_periodically' ) );

        if ( ! wp_next_scheduled( 'zutalw_daily_license_check' ) ) {
            wp_schedule_event( time(), 'daily', 'zutalw_daily_license_check' );
        }
    }

    /**
     * Activates the license key by sending a request to the Django backend.
     *
     * @param string $key The license key to activate.
     * @return array|WP_Error Returns an array with status and message, or WP_Error on failure.
     */
    public function activate_license( $key ) {
        $domain   = home_url();
        // Construct the full endpoint using the global constant
        $endpoint = ZUTALW_API_BASE_URL . 'license/activate/'; 

        $payload_data = array(
            'license_key' => sanitize_text_field( $key ),
            'domain'      => esc_url( $domain ),
            'action'      => 'activate'
        );

        $json_payload = wp_json_encode( $payload_data, JSON_UNESCAPED_SLASHES );

        // Generate HMAC signature using the global shared secret
        $signature = hash_hmac( 'sha256', $json_payload, ZUTALW_SHARED_SECRET );

        $args = array(
            'body'        => $json_payload,
            'headers'     => array(
                'Content-Type'       => 'application/json',
                'Accept'             => 'application/json',
                'X-Plugin-Signature' => $signature,
            ),
            'timeout'     => 15,
            'sslverify'   => false, 
        );

        $response = wp_remote_post( $endpoint, $args );

        if ( is_wp_error( $response ) ) {
            return $response;
        }

        $response_code = wp_remote_retrieve_response_code( $response );
        $body          = wp_remote_retrieve_body( $response );
        $data          = json_decode( $body, true );

        if ( $response_code === 200 && isset( $data['status'] ) && $data['status'] === 'success' ) {
            $license_data = array(
                'license_status' => 'active',
                'license_key'    => sanitize_text_field( $key ),
                'expiry_date'    => sanitize_text_field( $data['data']['expires_at'] ?? '' ),
                'last_checked'   => current_time( 'mysql' )
            );

            update_option( self::OPTION_KEY, $license_data );

            return array(
                'success' => true,
                'message' => __( 'License activated successfully.', 'zuta-lucky-wheel' )
            );
        }

        $error_message = isset( $data['error'] ) ? $data['error'] : __( 'Activation failed.', 'zuta-lucky-wheel' );
        return new WP_Error( 'activation_failed', $error_message );
    }

    /**
     * Periodically checks the license validity using WP Cron (every 24 hours).
     */
    public function check_license_periodically() {
        $license_data = get_option( self::OPTION_KEY );

        if ( ! $license_data || empty( $license_data['license_key'] ) ) {
            return;
        }

        $domain   = home_url();
        $key      = $license_data['license_key'];
        
        // Construct the validate endpoint
        $endpoint = ZUTALW_API_BASE_URL . 'license/validate/'; 

        $args = array(
            'body'        => wp_json_encode( array(
                'license_key' => $key,
                'domain'      => esc_url( $domain )
            ), JSON_UNESCAPED_SLASHES ),
            'headers'     => array(
                'Content-Type' => 'application/json',
                'Accept'       => 'application/json'
            ),
            'timeout'     => 10,
        );

        $response = wp_remote_post( $endpoint, $args );

        if ( is_wp_error( $response ) ) {
            return;
        }

        $response_code = wp_remote_retrieve_response_code( $response );
        $data          = json_decode( wp_remote_retrieve_body( $response ), true );

        if ( $response_code !== 200 || ( isset( $data['status'] ) && $data['status'] !== 'success' ) ) {
            $license_data['license_status'] = 'inactive';
            update_option( self::OPTION_KEY, $license_data );
        } else {
            $license_data['last_checked'] = current_time( 'mysql' );
            update_option( self::OPTION_KEY, $license_data );
        }
    }

    public static function clear_cron() {
        $timestamp = wp_next_scheduled( 'zutalw_daily_license_check' );
        if ( $timestamp ) {
            wp_unschedule_event( $timestamp, 'zutalw_daily_license_check' );
        }
    }
}

new ZUTALW_License_Manager();