<?php
/**
 * Activation class file.
 *
 * @package WholesaleNode_For_WooCommerce
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching

/**
 * Handles plugin activation and database setup.
 */
class WOOWSNFree_Activation {

	/**
	 * Run activation tasks.
	 */
	public static function activate() {
		self::create_tables();
		self::seed_b2b_group();
		self::setup_roles();
		self::set_defaults();

		update_option( 'woowsn_free_version', WOOWSN_FREE_VERSION );
		update_option( 'woowsn_free_activation_date', current_time( 'mysql' ) );
		flush_rewrite_rules();
	}

	/**
	 * Create required DB tables.
	 */
	private static function create_tables() {
		global $wpdb;
		$charset = $wpdb->get_charset_collate();
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';

		// ── Quotes (identical to Pro) ──────────────────────────────────
		dbDelta( "CREATE TABLE {$wpdb->prefix}woowsn_quotes (
			id mediumint(9) NOT NULL AUTO_INCREMENT,
			form_data longtext NOT NULL,
			status varchar(50) NOT NULL DEFAULT 'pending',
			ip_address varchar(100) DEFAULT NULL,
			user_id bigint(20) DEFAULT NULL,
			created_at datetime DEFAULT CURRENT_TIMESTAMP,
			updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			KEY status (status),
			KEY user_id (user_id),
			KEY created_at (created_at)
		) {$charset};" );

		// ── Rules (identical to Pro) ───────────────────────────────────
		dbDelta( "CREATE TABLE {$wpdb->prefix}woowsn_rules (
			id mediumint(9) NOT NULL AUTO_INCREMENT,
			rule_type varchar(50) NOT NULL,
			title varchar(255) NOT NULL,
			description text,
			user_roles longtext,
			user_ids longtext,
			user_list_ids longtext,
			product_ids longtext,
			product_list_ids longtext,
			category_ids longtext,
			tag_ids longtext,
			config longtext,
			priority int(11) DEFAULT 0,
			status varchar(20) DEFAULT 'active',
			created_by bigint(20) DEFAULT NULL,
			created_at datetime DEFAULT CURRENT_TIMESTAMP,
			updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			KEY rule_type (rule_type),
			KEY status (status),
			KEY priority (priority),
			KEY type_status (rule_type, status)
		) {$charset};" );

		// ── Product lists (identical to Pro) ───────────────────────────
		dbDelta( "CREATE TABLE {$wpdb->prefix}woowsn_product_lists (
			id mediumint(9) NOT NULL AUTO_INCREMENT,
			title varchar(255) NOT NULL,
			description text,
			type varchar(50) DEFAULT 'manual',
			product_ids longtext,
			category_ids longtext,
			tag_ids longtext,
			status varchar(20) DEFAULT 'active',
			created_by bigint(20) DEFAULT NULL,
			created_at datetime DEFAULT CURRENT_TIMESTAMP,
			updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			KEY status (status)
		) {$charset};" );

		// ── User groups (identical schema to Pro) ──────────────────────
		// Free only seeds the b2b parent + b2b_default child.
		// Pro's seed_default_groups() is idempotent (slug-unique inserts)
		// so it will simply skip the b2b rows that already exist here.
		dbDelta( "CREATE TABLE {$wpdb->prefix}woowsn_user_groups (
			id mediumint(9) NOT NULL AUTO_INCREMENT,
			title varchar(255) NOT NULL,
			slug varchar(100) NOT NULL,
			description text,
			group_type varchar(20) DEFAULT 'custom',
			parent_id mediumint(9) DEFAULT 0,
			sort_order int(11) DEFAULT 0,
			auto_assign_roles longtext,
			permissions longtext,
			status varchar(20) DEFAULT 'active',
			created_by bigint(20) DEFAULT NULL,
			created_at datetime DEFAULT CURRENT_TIMESTAMP,
			updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			UNIQUE KEY slug (slug),
			KEY status (status),
			KEY parent_id (parent_id),
			KEY group_type (group_type)
		) {$charset};" );
	}

	/**
	 * Seed the B2B parent group and its default child group.
	 */
	public static function seed_b2b_group() {
		global $wpdb;
		$table = $wpdb->prefix . 'woowsn_user_groups';
		$now   = current_time( 'mysql' );

		$parent_id = $wpdb->get_var(
			$wpdb->prepare( "SELECT id FROM {$table} WHERE slug = %s", 'b2b' )
		);

		if ( ! $parent_id ) {
			$wpdb->insert( $table, array(
				'title'             => 'B2B',
				'slug'              => 'b2b',
				'description'       => 'Business-to-business customers',
				'group_type'        => 'system',
				'parent_id'         => 0,
				'sort_order'        => 0,
				'auto_assign_roles' => '[]',
				'permissions'       => '[]',
				'status'            => 'active',
				'created_by'        => 1,
				'created_at'        => $now,
				'updated_at'        => $now,
			) );
			$parent_id = $wpdb->insert_id;
		}

		$child_exists = $wpdb->get_var(
			$wpdb->prepare( "SELECT id FROM {$table} WHERE slug = %s", 'b2b_default' )
		);

		if ( ! $child_exists ) {
			$wpdb->insert( $table, array(
				'title'             => 'B2B Default',
				'slug'              => 'b2b_default',
				'description'       => 'Default B2B group',
				'group_type'        => 'system',
				'parent_id'         => (int) $parent_id,
				'sort_order'        => 0,
				'auto_assign_roles' => '[]',
				'permissions'       => '[]',
				'status'            => 'active',
				'created_by'        => 1,
				'created_at'        => $now,
				'updated_at'        => $now,
			) );
		}
	}

	/**
	 * Create the Wholesaler WP role if it does not exist.
	 */
	private static function setup_roles() {
		if ( get_role( 'wholesaler' ) ) {
			return;
		}
		$caps     = array( 'read' => true, 'edit_posts' => false, 'delete_posts' => false );
		$customer = get_role( 'customer' );
		if ( $customer ) {
			$caps = array_merge( $customer->capabilities, $caps );
		}
		add_role( 'wholesaler', __( 'Wholesaler', 'wholesalenode-for-woocommerce' ), $caps );
	}

	/**
	 * Set default option values on first activation.
	 */
	private static function set_defaults() {
		if ( ! get_option( 'woowsn_free_features' ) ) {
			update_option( 'woowsn_free_features', array(
				'registration'       => true,
				'hide_price'         => true,
				'product_visibility' => true,
				'discount_rules'     => true,
				'product_lists'      => true,
				'quotes'             => true,
			) );
		}

		self::seed_default_registration_form();

		if ( ! get_option( 'woowsn_hide_price_settings' ) ) {
			update_option( 'woowsn_hide_price_settings', array(
				'hide_for_guests'  => false,
				'replacement_text' => __( 'Login to see prices', 'wholesalenode-for-woocommerce' ),
				'show_button'      => false,
				'button_text'      => __( 'Request Quote', 'wholesalenode-for-woocommerce' ),
				'button_url'       => '',
				'hide_add_to_cart' => false,
			) );
		}

		if ( ! get_option( 'woowsn_general_settings' ) ) {
			update_option( 'woowsn_general_settings', array(
				'enableQuoteForm'          => true,
				'enableEmailNotifications' => true,
			) );
		}

		if ( ! get_option( 'woowsn_quotes_settings' ) ) {
			update_option( 'woowsn_quotes_settings', array(
				'displayMode'           => 'popup',
				'displaymode'           => 'popup',
				'displayPosition'       => 'after_add_to_cart_button',
				'displayposition'       => 'after_add_to_cart_button',
				'popupButtonText'       => 'Request a Quote',
				'popupbuttontext'       => 'Request a Quote',
				'popupButtonClass'      => '',
				'enableOnSingleProduct' => true,
				'enableonsingleproduct' => true,
			) );
		}
	}

	/**
	 * Seed the default registration form fields into both option keys.
	 *
	 * Called on activation and on version bump so existing installs also
	 * get the default form if neither option has any fields yet.
	 */
	public static function seed_default_registration_form() {
		$free_saved = get_option( 'woowsn_free_registration_form', array() );
		$pro_saved  = get_option( 'woowsn_registration_form', array() );

		if ( ! empty( $free_saved['fields'] ) || ! empty( $pro_saved['fields'] ) ) {
			return;
		}

		$default_form = array(
			'fields' => array(
				array(
					'id'          => 'billing_first_name',
					'name'        => 'billing_first_name',
					'type'        => 'text',
					'label'       => __( 'First Name', 'wholesalenode-for-woocommerce' ),
					'placeholder' => '',
					'required'    => true,
					'default'     => true,
					'locked'      => false,
					'isWCDefault' => true,
					'order'       => 0,
				),
				array(
					'id'          => 'billing_last_name',
					'name'        => 'billing_last_name',
					'type'        => 'text',
					'label'       => __( 'Last Name', 'wholesalenode-for-woocommerce' ),
					'placeholder' => '',
					'required'    => true,
					'default'     => true,
					'locked'      => false,
					'isWCDefault' => true,
					'order'       => 1,
				),
				array(
					'id'          => 'billing_company',
					'name'        => 'billing_company',
					'type'        => 'text',
					'label'       => __( 'Company Name', 'wholesalenode-for-woocommerce' ),
					'placeholder' => '',
					'required'    => true,
					'default'     => true,
					'locked'      => false,
					'isWCDefault' => true,
					'order'       => 2,
				),
				array(
					'id'          => 'billing_phone',
					'name'        => 'billing_phone',
					'type'        => 'tel',
					'label'       => __( 'Phone', 'wholesalenode-for-woocommerce' ),
					'placeholder' => '',
					'required'    => false,
					'default'     => true,
					'locked'      => false,
					'isWCDefault' => true,
					'order'       => 3,
				),
				array(
					'id'          => 'woowsn_company_type',
					'name'        => 'woowsn_company_type',
					'type'        => 'text',
					'label'       => __( 'Business Type', 'wholesalenode-for-woocommerce' ),
					'placeholder' => __( 'e.g. Retailer, Distributor, Manufacturer', 'wholesalenode-for-woocommerce' ),
					'required'    => false,
					'default'     => false,
					'locked'      => false,
					'isWCDefault' => false,
					'order'       => 4,
				),
			),
		);

		update_option( 'woowsn_free_registration_form', $default_form );
		update_option( 'woowsn_registration_form', $default_form );
	}
}
