<?php

/**
 * License Manager
 * 
 * Helper class for Freemius license checks and feature limits
 *
 * @package AIContentGenerator
 */
namespace AICG;

// Prevent direct access
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * License Manager class
 */
class License_Manager {
    /**
     * Free plan limits
     */
    const FREE_LIMITS = array(
        'ai_keywords'        => 10,
        'schedules'          => 1,
        'publish_per_week'   => 4,
        'max_ready_articles' => 2,
        'images_per_article' => 1,
        'max_internal_links' => 0,
        'content_lengths'    => array('short'),
    );

    public static function is_pro() {
        if ( !function_exists( 'roidaico_fs' ) ) {
            return false;
        }
        return false;
    }

    /**
     * Check if user is on trial
     *
     * @return bool
     */
    public static function is_trial() {
        if ( !function_exists( 'roidaico_fs' ) ) {
            return false;
        }
        return roidaico_fs()->is_trial();
    }

    /**
     * Check if user is paying (not trial)
     *
     * @return bool
     */
    public static function is_paying() {
        if ( !function_exists( 'roidaico_fs' ) ) {
            return false;
        }
        return roidaico_fs()->is_paying();
    }

    /**
     * Get limit for a specific feature
     *
     * @param string $feature Feature name
     * @return mixed Limit value or null if Pro
     */
    public static function get_limit( $feature ) {
        if ( self::is_pro() ) {
            return null;
            // No limit for Pro
        }
        return ( isset( self::FREE_LIMITS[$feature] ) ? self::FREE_LIMITS[$feature] : null );
    }

    /**
     * Check if feature is available
     *
     * @param string $feature Feature name
     * @return bool
     */
    public static function can_use_feature( $feature ) {
        if ( self::is_pro() ) {
            return true;
        }
        // Features completely disabled for free users
        $pro_only_features = array(
            'internal_links',
            'custom_instructions',
            'seo_integration',
            'auto_generate_keywords',
            'system_log',
            'medium_length',
            'long_length'
        );
        return !in_array( $feature, $pro_only_features );
    }

    /**
     * Get count of AI-generated keywords
     *
     * @return int
     */
    public static function get_ai_keywords_count() {
        self::maybe_reset_monthly_limits();
        return (int) get_option( 'roidaico_ai_keywords_generated', 0 );
    }

    /**
     * Increment AI-generated keywords count
     *
     * @param int $count Number to add
     * @return void
     */
    public static function increment_ai_keywords_count( $count = 1 ) {
        $current = self::get_ai_keywords_count();
        update_option( 'roidaico_ai_keywords_generated', $current + $count );
    }

    /**
     * Check if user can generate more AI keywords
     *
     * @return bool
     */
    public static function can_generate_ai_keywords() {
        if ( self::is_pro() ) {
            return true;
        }
        $limit = self::get_limit( 'ai_keywords' );
        $used = self::get_ai_keywords_count();
        return $used < $limit;
    }

    /**
     * Get remaining AI keywords quota
     *
     * @return int|string
     */
    public static function get_remaining_ai_keywords() {
        if ( self::is_pro() ) {
            return __( 'Unlimited', 'roidnet-ai-content-generator' );
        }
        $limit = self::get_limit( 'ai_keywords' );
        $used = self::get_ai_keywords_count();
        return sprintf( __( '%d (Free monthly limit)', 'roidnet-ai-content-generator' ), max( 0, $limit - $used ) );
    }

    /**
     * Get weekly publish count
     *
     * @return int
     */
    public static function get_weekly_publish_count() {
        $count = get_transient( 'roidaico_weekly_publish_count' );
        return ( $count ? (int) $count : 0 );
    }

    /**
     * Increment weekly publish count
     *
     * @return void
     */
    public static function increment_weekly_publish_count() {
        $count = self::get_weekly_publish_count();
        // Expires at end of week (Sunday 23:59:59)
        $seconds_until_sunday = strtotime( 'next sunday 23:59:59' ) - time();
        set_transient( 'roidaico_weekly_publish_count', $count + 1, $seconds_until_sunday );
    }

    /**
     * Check if user can publish more this week
     *
     * @return bool
     */
    public static function can_publish_this_week() {
        if ( self::is_pro() ) {
            return true;
        }
        $limit = self::get_limit( 'publish_per_week' );
        $used = self::get_weekly_publish_count();
        return $used < $limit;
    }

    /**
     * Get remaining weekly publishes
     *
     * @return int|string
     */
    public static function get_remaining_weekly_publishes() {
        if ( self::is_pro() ) {
            return __( 'Unlimited', 'roidnet-ai-content-generator' );
        }
        $limit = self::get_limit( 'publish_per_week' );
        $used = self::get_weekly_publish_count();
        return max( 0, $limit - $used );
    }

    /**
     * Get upgrade URL
     *
     * @return string
     */
    public static function get_upgrade_url() {
        if ( !function_exists( 'roidaico_fs' ) ) {
            return '#';
        }
        // If the user has not activated the trial/pro version yet, return the trial URL by default
        if ( !roidaico_fs()->can_use_premium_code() && !roidaico_fs()->is_trial() ) {
            return roidaico_fs()->get_trial_url();
        }
        return roidaico_fs()->get_upgrade_url();
    }

    /**
     * Get Pro badge HTML
     *
     * @param bool $with_link Include upgrade link
     * @return string
     */
    public static function get_pro_badge( $with_link = true ) {
        $badge = '<span class="roidaico-pro-badge">PRO</span>';
        if ( $with_link && !self::is_pro() ) {
            $url = self::get_upgrade_url();
            $badge = sprintf(
                '<a href="%s" class="roidaico-pro-link" title="%s">%s</a>',
                esc_url( $url ),
                esc_attr__( 'Upgrade to Pro', 'roidnet-ai-content-generator' ),
                $badge
            );
        }
        return $badge;
    }

    /**
     * Get schedule count
     *
     * @return int
     */
    public static function get_schedule_count() {
        global $wpdb;
        $table = $wpdb->prefix . 'roidaico_schedules';
        return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" );
    }

    /**
     * Check if user can add more schedules
     *
     * @return bool
     */
    public static function can_add_schedule() {
        if ( self::is_pro() ) {
            return true;
        }
        $limit = self::get_limit( 'schedules' );
        $current = self::get_schedule_count();
        return $current < $limit;
    }

    /**
     * Get allowed content lengths
     *
     * @return array
     */
    public static function get_allowed_lengths() {
        if ( self::is_pro() ) {
            return array('short', 'medium', 'long');
        }
        return self::FREE_LIMITS['content_lengths'];
    }

    /**
     * Check if length is allowed
     *
     * @param string $length Length to check
     * @return bool
     */
    public static function is_length_allowed( $length ) {
        return in_array( $length, self::get_allowed_lengths() );
    }

    /**
     * Get max images per article
     *
     * @return int
     */
    public static function get_max_images() {
        if ( self::is_pro() ) {
            return 10;
        }
        return self::FREE_LIMITS['images_per_article'];
    }

    /**
     * Get max ready articles
     *
     * @return int
     */
    public static function get_max_ready_articles() {
        if ( self::is_pro() ) {
            return 50;
        }
        return self::FREE_LIMITS['max_ready_articles'];
    }

    /**
     * Check and reset monthly limits if needed
     *
     * @return void
     */
    private static function maybe_reset_monthly_limits() {
        $last_reset = get_option( 'roidaico_last_monthly_reset', '' );
        $current_month = date( 'Y-m' );
        if ( $last_reset !== $current_month ) {
            update_option( 'roidaico_ai_keywords_generated', 0 );
            update_option( 'roidaico_last_monthly_reset', $current_month );
        }
    }

}
