<?php

/**
 * Plugin activation handler
 *
 * @package KarateClubManager
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * Handles plugin activation
 */
class MACM_Activator {
    /**
     * Activate the plugin
     *
     * This method is called when the plugin is activated.
     * It sets up the database, creates roles, and performs initial configuration.
     */
    public static function activate() {
        // Check WordPress and PHP versions.
        if ( version_compare( get_bloginfo( 'version' ), '6.0', '<' ) ) {
            deactivate_plugins( MACM_PLUGIN_BASENAME );
            wp_die( esc_html__( 'Martial Arts Club Manager requires WordPress 6.0 or higher.', 'martial-arts-club-manager' ) );
        }
        if ( version_compare( PHP_VERSION, '7.4', '<' ) ) {
            deactivate_plugins( MACM_PLUGIN_BASENAME );
            wp_die( esc_html__( 'Martial Arts Club Manager requires PHP 7.4 or higher.', 'martial-arts-club-manager' ) );
        }
        // Check if WooCommerce is active.
        if ( !class_exists( 'WooCommerce' ) ) {
            deactivate_plugins( MACM_PLUGIN_BASENAME );
            wp_die( esc_html__( 'Martial Arts Club Manager requires WooCommerce to be installed and activated.', 'martial-arts-club-manager' ) );
        }
        // Create database tables.
        require_once MACM_PLUGIN_DIR . 'includes/database/class-macm-database.php';
        MACM_Database::create_tables();
        // Initialize default belt colors.
        require_once MACM_PLUGIN_DIR . 'includes/classes/class-macm-belt-color.php';
        MACM_Belt_Color::initialize_defaults();
        // Update belt colors order (for existing installations).
        MACM_Belt_Color::update_belt_order();
        // Create custom roles.
        require_once MACM_PLUGIN_DIR . 'includes/class-macm-roles.php';
        MACM_Roles::create_roles();
        // Create default WooCommerce products.
        self::create_default_products();
        // Create plugin pages.
        self::create_plugin_pages();
        // Set default options.
        add_option( 'macm_version', MACM_VERSION );
        add_option( 'macm_protected_pages', array() );
        add_option( 'macm_class_register_users', array() );
        // Flush rewrite rules.
        flush_rewrite_rules();
    }

    /**
     * Create default WooCommerce products
     *
     * Creates 4 default products on plugin activation:
     * - Starter Kit (£100)
     * - Basic Membership (£45)
     * - Pro Membership (£55)
     * - Licence (£50)
     *
     * @since 1.0.0
     */
    private static function create_default_products() {
        $products = array(
            array(
                'name'        => 'Starter Kit',
                'price'       => '100.00',
                'description' => 'Complete starter kit for new karate students including uniform and essential equipment.',
                'sku'         => 'KCM-STARTER-KIT',
            ),
            array(
                'name'        => 'Basic Membership',
                'price'       => '45.00',
                'description' => 'Monthly basic membership with access to regular training sessions.',
                'sku'         => 'KCM-BASIC-MEMBERSHIP',
            ),
            array(
                'name'        => 'Pro Membership',
                'price'       => '55.00',
                'description' => 'Monthly pro membership with access to all training sessions and premium content.',
                'sku'         => 'KCM-PRO-MEMBERSHIP',
            ),
            array(
                'name'        => 'Licence',
                'price'       => '50.00',
                'description' => 'Annual karate licence registration fee.',
                'sku'         => 'KCM-LICENCE',
            )
        );
        $created_product_ids = array();
        foreach ( $products as $product_data ) {
            // Check if product with this SKU already exists.
            $existing_product_id = wc_get_product_id_by_sku( $product_data['sku'] );
            if ( $existing_product_id ) {
                // Product already exists, store its ID.
                $created_product_ids[$product_data['sku']] = $existing_product_id;
                continue;
            }
            // Create new product.
            $product = new WC_Product_Simple();
            $product->set_name( $product_data['name'] );
            $product->set_regular_price( $product_data['price'] );
            $product->set_description( $product_data['description'] );
            $product->set_sku( $product_data['sku'] );
            $product->set_catalog_visibility( 'visible' );
            $product->set_status( 'publish' );
            // Save product.
            $product_id = $product->save();
            if ( $product_id ) {
                $created_product_ids[$product_data['sku']] = $product_id;
            }
        }
        // Store product IDs for future reference.
        update_option( 'macm_default_products', $created_product_ids );
        update_option( 'macm_default_products_created', true );
    }

    /**
     * Create plugin pages
     *
     * Creates required pages on plugin activation:
     * - Training Videos
     * - Members Area
     * - Class Register
     * - Book a Trial Class
     * - Events & Competitions
     *
     * @since 1.0.0
     */
    private static function create_plugin_pages() {
        // Check if pages have already been created.
        $pages_created = get_option( 'macm_pages_created', false );
        if ( $pages_created ) {
            return;
        }
        // FREE pages - available to all users.
        $free_pages = array(array(
            'title'   => 'Members Area',
            'slug'    => 'members-area',
            'content' => '[macm_member_area]',
            'option'  => 'macm_members_area_page_id',
        ), array(
            'title'   => 'Book a Trial Class',
            'slug'    => 'book-trial-class',
            'content' => '[macm_trial_booking_form]',
            'option'  => 'macm_trial_booking_page_id',
        ));
        // Create free pages.
        foreach ( $free_pages as $page_data ) {
            self::create_page( $page_data );
        }
        // Mark pages as created.
        update_option( 'macm_pages_created', true );
    }

    /**
     * Create a single page
     *
     * @param array $page_data Page data array with title, slug, content, option.
     * @since 1.0.131
     */
    private static function create_page( $page_data ) {
        // Check if page already exists by slug.
        // Ensure slug is not null before passing to get_page_by_path (PHP 8.1+ compatibility).
        $slug = ( isset( $page_data['slug'] ) && null !== $page_data['slug'] ? $page_data['slug'] : '' );
        $existing_page = ( !empty( $slug ) ? get_page_by_path( $slug ) : null );
        if ( $existing_page && !is_null( $existing_page ) ) {
            // Page exists, store its ID.
            update_option( $page_data['option'], $existing_page->ID );
        } else {
            // Create new page - ensure all values are not null (PHP 8.1+ compatibility).
            $page_id = wp_insert_post( array(
                'post_title'     => ( isset( $page_data['title'] ) && null !== $page_data['title'] ? $page_data['title'] : '' ),
                'post_name'      => ( isset( $page_data['slug'] ) && null !== $page_data['slug'] ? $page_data['slug'] : '' ),
                'post_content'   => ( isset( $page_data['content'] ) && null !== $page_data['content'] ? $page_data['content'] : '' ),
                'post_status'    => 'publish',
                'post_type'      => 'page',
                'post_author'    => 1,
                'comment_status' => 'closed',
                'ping_status'    => 'closed',
            ) );
            if ( $page_id && !is_wp_error( $page_id ) ) {
                update_option( $page_data['option'], $page_id );
            }
        }
    }

}
