<?php
/**
 * Plan Limit Notice Class.
 *
 * @package SAAI\Classes
 */

namespace SAAI\Classes;

use SAAI\Helpers\Connect;
use SAAI\Helpers\Helper;
use SAAI\Factories\Vite_App;
use SAAI\Traits\Singleton_Trait;

defined( 'ABSPATH' ) || exit;

/**
 * Plan_Limit_Notice Class.
 *
 * Handles admin notices and dashboard notifications when plan usage limits
 * are exceeded.
 *
 * @since 1.1.0
 */
class Plan_Limit_Notice {

    use Singleton_Trait;

    /**
     * Holds the class instance object.
     *
     * @var Plan_Limit_Notice $instance object
     * @since 1.1.0
     */
    protected static $instance;

    /**
     * Option name for storing the notice dismissal timestamp.
     *
     * @since 1.1.0
     */
    const DISMISS_OPTION = 'saai_plan_limit_notice_dismissed';

    /**
     * Option name for tracking if the dashboard notification has been created.
     *
     * @since 1.1.0
     */
    const NOTIFICATION_CREATED_OPTION = 'saai_plan_limit_notification_created';

    /**
     * Run the class functionality.
     *
     * @since 1.1.0
     * @return void
     */
    public function run() {
        add_action( 'admin_notices', array( $this, 'display_wp_notice' ) );
        add_action( 'saai_admin_notices', array( $this, 'display_storeagent_notice' ) );
        add_action( 'wp_ajax_saai_dismiss_plan_limit_notice', array( $this, 'ajax_dismiss_notice' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
        add_action( 'admin_init', array( $this, 'maybe_create_dashboard_notification' ) );
    }

    /**
     * Check if plan limit is exceeded.
     *
     * Delegates to Plan_Manager and also checks that the store is connected
     * and plan data exists.
     *
     * @since 1.1.0
     * @return bool True if limit is exceeded.
     */
    protected function is_limit_exceeded() {
        if ( ! Connect::is_connected() ) {
            return false;
        }

        $plan_data = Plan_Manager::instance()->get_plan_data();
        if ( empty( $plan_data['plan_name'] ) ) {
            return false;
        }

        return Plan_Manager::instance()->is_plan_limit_exceeded();
    }

    /**
     * Check if the WP notice should be shown on Dashboard/Plugins pages.
     *
     * @since 1.1.0
     * @return bool True if notice should be shown.
     */
    protected function should_show_wp_notice() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return false;
        }

        // Only show on WP Dashboard (index.php) and Plugins page (plugins.php).
        global $pagenow;
        if ( ! in_array( $pagenow, array( 'index.php', 'plugins.php' ), true ) ) {
            return false;
        }

        if ( ! $this->is_limit_exceeded() ) {
            return false;
        }

        // Check if dismissed within the last 7 days.
        $dismissed_time = get_option( self::DISMISS_OPTION, 0 );
        if ( $dismissed_time && ( time() - $dismissed_time ) < WEEK_IN_SECONDS ) {
            return false;
        }

        return true;
    }

    /**
     * Display a dismissable notice on WP Dashboard and Plugins pages.
     *
     * @since 1.1.0
     * @return void
     */
    public function display_wp_notice() {
        if ( ! $this->should_show_wp_notice() ) {
            return;
        }

        $plans_url = Helper::get_utm_url( 'my-account', 'saai', 'clientsite', 'plan-limit-notice', 'https://app.storeagent.ai/' );

        include SAAI_TEMPLATES_DIR . 'admin/notices/plan-limit-wp-notice.php';
    }

    /**
     * Display a non-dismissable notice on StoreAgent admin pages.
     *
     * @since 1.1.0
     * @return void
     */
    public function display_storeagent_notice() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        if ( ! $this->is_limit_exceeded() ) {
            return;
        }

        $plans_url = Helper::get_utm_url( 'my-account', 'saai', 'clientsite', 'plan-limit-notice', 'https://app.storeagent.ai/' );

        include SAAI_TEMPLATES_DIR . 'admin/notices/plan-limit-storeagent-notice.php';
    }

    /**
     * Handle AJAX notice dismissal.
     *
     * @since 1.1.0
     * @return void
     */
    public function ajax_dismiss_notice() {
        check_ajax_referer( 'saai_dismiss_plan_limit_notice', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( -1 );
        }

        update_option( self::DISMISS_OPTION, time() );
        wp_die( 1 );
    }

    /**
     * Create a dashboard notification when plan limit is exceeded.
     *
     * Only creates the notification once per exceeded-limit period.
     *
     * @since 1.1.0
     * @return void
     */
    public function maybe_create_dashboard_notification() {
        if ( ! $this->is_limit_exceeded() ) {
            return;
        }

        // Only create the notification once.
        if ( get_option( self::NOTIFICATION_CREATED_OPTION, false ) ) {
            return;
        }

        $plans_url = Helper::get_utm_url( 'my-account', 'saai', 'clientsite', 'plan-limit-notice', 'https://app.storeagent.ai/' );

        Notification::instance()->create(
            'warning',
            __( 'StoreAgent Plan Upgrade', 'storeagent-ai-for-woocommerce' ),
            __( "You've exceeded the usage limit of your StoreAgent plan and your account has been paused. Please login to your account to upgrade to a higher plan.", 'storeagent-ai-for-woocommerce' ),
            'system',
            null,
            array(),
            array(
                array(
                    'label'  => __( 'View Plans', 'storeagent-ai-for-woocommerce' ),
                    'action' => 'custom',
                    'url'    => $plans_url,
                    'target' => '_blank',
                ),
            ),
            true
        );

        update_option( self::NOTIFICATION_CREATED_OPTION, true, false );
    }

    /**
     * Enqueue scripts for the WP notice dismiss handler.
     *
     * @since 1.1.0
     * @return void
     */
    public function enqueue_scripts() {
        if ( ! $this->should_show_wp_notice() ) {
            return;
        }

        $script = new Vite_App(
            'saai-plan-limit-notice',
            'src/vanilla/notice/plan-limit-notice.ts',
            array( 'jquery' ),
            array(
                'ajaxUrl' => admin_url( 'admin-ajax.php' ),
                'nonce'   => wp_create_nonce( 'saai_dismiss_plan_limit_notice' ),
            ),
            'saaiPlanLimitNotice'
        );
        $script->enqueue();
    }
}
