<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
//phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
//phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching -- This query modifies data; caching is not applicable

/**
 * Create Kbucket tables and default settings for a blog.
 * Used on plugin activation and when a new multisite blog is created.
 *
 * @param int|null $blog_id Blog ID for multisite, or null for current blog.
 */
function kb_create_tables_for_blog( $blog_id = null ) {
	$switched = false;
	// Only switch in multisite when a specific blog_id is given; single site always uses current blog.
	if ( $blog_id !== null && is_multisite() ) {
		switch_to_blog( $blog_id );
		$switched = true;
	}

	/** @var $wpdb object */
	global $wpdb;

	// Skip if tables already exist — avoid duplicate creation or redundant work.
	$table = $wpdb->prefix . 'kb_files';
	$exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
	if ( $exists === $table ) {
		if ( $switched ) {
			restore_current_blog();
		}
		return;
	}

	$charsetCollate = $wpdb->get_charset_collate();

	$sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}kbucket (
				id_kbucket varchar(100) NOT NULL,
				id_cat varchar(100) DEFAULT NULL,
				title text,
				description text NOT NULL,
				link text,
				author varchar(50) DEFAULT NULL,
				publisher varchar(255) DEFAULT NULL,
				author_alias varchar(255) DEFAULT NULL,
				publisher_alias varchar(255) DEFAULT NULL,
				facebook varchar(200) NOT NULL,
				twitter varchar(200) NOT NULL,
				pub_date varchar(100) DEFAULT NULL,
				add_date date DEFAULT NULL,
				status enum( '0','1' ) DEFAULT '1',
				image_url varchar(255) DEFAULT '',
				short_url varchar(255) DEFAULT '',
				post_id int(11) DEFAULT NULL,
				url_kbucket varchar(255),
			PRIMARY KEY  (id_kbucket),
			UNIQUE KEY id_kbucket_id_cat_index (id_kbucket,id_cat)
			) ENGINE=MyISAM $charsetCollate";
	$wpdb->query( $sql );

	$sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}kb_files (
				id_file int(9) NOT NULL AUTO_INCREMENT,
				name varchar(100) DEFAULT NULL,
				comment text DEFAULT NULL,
				encoding text NOT NULL,
				publisher varchar(255) DEFAULT NULL,
				author varchar(50) DEFAULT NULL,
				keywords text DEFAULT NULL,
				file_added varchar(100) DEFAULT NULL,
				file_path varchar(255) DEFAULT NULL,
			PRIMARY KEY (id_file)
			) ENGINE=MyISAM $charsetCollate";
	$wpdb->query( $sql );

	$sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}kb_category (
				id_cat varchar(100) NOT NULL,
				name varchar(50) DEFAULT NULL,
    			alias_name varchar(255) DEFAULT NULL,
				description text,
				image text,
				parent_cat varchar(100) DEFAULT '0',
				level bigint(3) DEFAULT NULL,
				add_date date DEFAULT NULL,
				keywords varchar(255) DEFAULT NULL,
				status enum( '0','1' ) DEFAULT '1',
			PRIMARY KEY  (id_cat),
			UNIQUE KEY id_cat (id_cat,name,parent_cat)
			) ENGINE=MyISAM $charsetCollate";
	$wpdb->query( $sql );

	$sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}kb_suggest (
				id_sug int(2) NOT NULL AUTO_INCREMENT,
				id_cat varchar(100) DEFAULT NULL,
				tittle varchar(50) DEFAULT NULL,
				description text NOT NULL,
				tags varchar(200) NOT NULL,
				add_date date DEFAULT NULL,
				author varchar(50) DEFAULT NULL,
				link text,
				twitter text,
				facebook text,
				status enum( '0','1' ) DEFAULT '1',
			PRIMARY KEY  (id_sug)
			) ENGINE=MyISAM $charsetCollate";
	$wpdb->query( $sql );

	$sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}kb_tags (
				id_ktags int(3) NOT NULL AUTO_INCREMENT,
				id_kbucket varchar(100) DEFAULT NULL,
				id_tag int(3) DEFAULT NULL,
				status enum( '0','1' ) DEFAULT '1',
			PRIMARY KEY  (id_ktags),
			UNIQUE KEY id_kbucket_id_tag_index (id_kbucket,id_tag)
			) ENGINE=MyISAM  $charsetCollate;";
	$wpdb->query( $sql );

	$sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}kb_tag_details (
				id_tag int(3) NOT NULL AUTO_INCREMENT,
				name varchar(50) DEFAULT NULL,
				status enum( '0','1' ) DEFAULT '1',
			PRIMARY KEY  (id_tag),
			UNIQUE KEY name_index (name)
			) ENGINE=MyISAM  $charsetCollate";
	$wpdb->query( $sql );

	$post = get_post( get_option( 'kb_setup_page_id', 'kbucket' ) );
	$kpage = ( isset( $post->post_name ) ) ? $post->post_name : 'kbucket';

	$kbucketPageExists = get_posts(
		array(
			'name'        => $kpage,
			'post_type'   => 'page',
			'numberposts' => 1,
		)
	);

	if ( ! $kbucketPageExists ) {
		$kbucketPage = array(
			'post_name'   => 'kbucket',
			'post_title'  => 'Kbucket',
			'post_status' => 'publish',
			'post_type'   => 'page',
		);

		$post_id = wp_insert_post( $kbucketPage );
		if ( $post_id && ! is_wp_error( $post_id ) ) {
			update_option( 'kb_setup_page_id', $post_id );
		}
	}
	add_option( 'kbucket_data', 'Default', '', 'yes' );

	if ( $switched ) {
		restore_current_blog();
	}
}

/**
 * Run install scripts by plugin activation.
 * Create Kbucket tables and insert default settings for the current site.
 * Fired by register_activation_hook.
 */
function register_activation_kbucket() {
	kb_create_tables_for_blog( null );
}

/**
 * Create Kbucket tables when a new site is added to the network (multisite).
 * Fired by wpmu_new_blog (legacy).
 *
 * @param int    $blog_id Blog ID of the new site.
 * @param int    $user_id User ID.
 * @param string $domain  Site domain.
 * @param string $path    Site path.
 * @param int    $site_id Network site ID.
 * @param array  $meta    Meta data for the new site.
 */
function kb_on_new_blog_create_tables( $blog_id, $user_id, $domain, $path, $site_id, $meta ) {
	if ( ! is_multisite() ) {
		return;
	}
	$active_sitewide = get_site_option( 'active_sitewide_plugins', array() );
	if ( ! empty( $active_sitewide[ plugin_basename( WPKB_FILE ) ] ) ) {
		kb_create_tables_for_blog( $blog_id );
	}
}

/**
 * Create Kbucket tables when a new site is initialized (WP 5.1+).
 * Fired by wp_initialize_site.
 *
 * @param WP_Site $site The new site object.
 */
function kb_on_initialize_site_create_tables( $site ) {
	if ( ! is_multisite() || ! ( $site instanceof WP_Site ) ) {
		return;
	}
	$active_sitewide = get_site_option( 'active_sitewide_plugins', array() );
	if ( ! empty( $active_sitewide[ plugin_basename( WPKB_FILE ) ] ) ) {
		kb_create_tables_for_blog( (int) $site->blog_id );
	}
}

/**
 * Ensure Kbucket tables exist for the current blog (fixes existing sites that were created
 * before the plugin hooked into wpmu_new_blog, or when plugin was activated network-wide).
 * Runs when an admin visits that site's wp-admin — tables are created on first visit.
 * Safe for single site (current blog = the only site) and multisite (current blog = subsite).
 */
function kb_maybe_create_tables_for_current_blog() {
	if ( ! is_admin() ) {
		return;
	}
	global $wpdb;
	$table = $wpdb->prefix . 'kb_files';
	$exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
	if ( $exists === $table ) {
		return;
	}
	kb_create_tables_for_blog( null );
}

/**
 * One-time repair: create Kbucket tables for all existing network sites that are missing them.
 * Runs once when a network admin loads any Network Admin page (after plugin update).
 * So already-created sites get tables without requiring a visit to each site's wp-admin.
 * Does nothing on single site (exits on ! is_multisite()).
 */
function kb_multisite_repair_missing_tables() {
	if ( ! is_multisite() || ! is_network_admin() || ! is_admin() ) {
		return;
	}
	$done = get_site_option( 'kb_multisite_tables_repair_done', false );
	if ( $done ) {
		return;
	}
	global $wpdb;
	$blog_ids = get_sites( array( 'fields' => 'ids', 'number' => 5000 ) );
	foreach ( $blog_ids as $blog_id ) {
		$prefix = $wpdb->get_blog_prefix( $blog_id );
		$table  = $prefix . 'kb_files';
		$exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
		if ( $exists !== $table ) {
			kb_create_tables_for_blog( (int) $blog_id );
		}
	}
	update_site_option( 'kb_multisite_tables_repair_done', true );
}

// Set Kbucket install hook.
register_activation_hook( WPKB_FILE, 'register_activation_kbucket' );

// Create tables when a new site is created in multisite.
add_action( 'wpmu_new_blog', 'kb_on_new_blog_create_tables', 10, 6 );
add_action( 'wp_initialize_site', 'kb_on_initialize_site_create_tables', 10, 1 );

// Per-site: if current blog is missing kb_files table, create all tables (when visiting that site's wp-admin).
add_action( 'admin_init', 'kb_maybe_create_tables_for_current_blog', 1 );

// One-time multisite repair: create tables for all existing sites missing them (when network admin loads any page).
add_action( 'admin_init', 'kb_multisite_repair_missing_tables', 5 );


/**
 * Remove plugin data if plugin has been deleted
 * Fired by register_deactivation_hook
 */
// function register_deactivation_kbucket() {
// 	if ( ! current_user_can( 'activate_plugins' ) ) return;
// 	global $wpdb;

// 	$dropTables = array(
// 		$wpdb->prefix . 'kbucket',
// 		$wpdb->prefix . 'kb_category',
// 		$wpdb->prefix . 'kb_suggest',
// 		$wpdb->prefix . 'kb_tags',
// 		$wpdb->prefix . 'kb_tag_details',
// 		$wpdb->prefix . 'kb_page_settings',
// 	);

// 	$dropTablesStr = '' . implode( ',', $dropTables );
// 	$wpdb->query( "DROP TABLE $dropTablesStr" );
// }
