<?php
namespace Vidplex;

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Activate
 *
 * Handles plugin activation procedures.
 *
 * Responsible for creating database tables, setting default options,
 * and performing any setup tasks required when the plugin is activated.
 */
class Activate {
	/**
	 * Handles plugin activation.
	 *
	 * This method is triggered when the plugin is activated.
	 * It can be used to set up database tables, register custom post types,
	 * flush rewrite rules, or initialize default settings.
	 *
	 * @return void
	 */
	public static function activate() {
		self::create_tables();
	}

	/**
	 * Creates the necessary database tables for the plugin.
	 *
	 * Sets up tables for storing channels, videos, and related data
	 * if they do not already exist. Called during plugin
	 * activation.
	 *
	 * @return void
	 */
	private static function create_tables() {
		global $wpdb;

		$charset_collate = $wpdb->get_charset_collate();

		// Channels table.
		$table_name = $wpdb->prefix . 'vidplex_yt_channels';
		$sql        = "CREATE TABLE $table_name (
			id BIGINT(20) NOT NULL AUTO_INCREMENT,
			channel_id VARCHAR(255) NOT NULL UNIQUE,
			channel_name VARCHAR(255) NOT NULL,
			channel_handle VARCHAR(255) NOT NULL,
			channel_thumbnail VARCHAR(255) NOT NULL DEFAULT '',
			channel_uploads_playlist VARCHAR(255),
			statistics JSON NOT NULL,
			branding_settings JSON NOT NULL,
			published_at DATETIME NULL,
			created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
			updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			thumbnail_blob LONGBLOB,
			mime_type VARCHAR(50),
			banner_blob LONGBLOB,
			banner_mime_type VARCHAR(50),
			next_page_token VARCHAR(255),
			last_sync_at DATETIME NULL,
			PRIMARY KEY (id)
   	 	) $charset_collate;";

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		dbDelta( $sql );

		// Videos table.
		$table_name = $wpdb->prefix . 'vidplex_yt_videos';
		$sql        = "CREATE TABLE $table_name (
			id BIGINT(20) NOT NULL AUTO_INCREMENT,
			channel_id BIGINT(20) NOT NULL DEFAULT 0,
			video_id VARCHAR(255) NOT NULL UNIQUE,
			video_title TEXT NOT NULL,
			video_description TEXT,
			published_at DATETIME,
			created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
			updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			is_shorts INT DEFAULT 0, 
			statistics JSON NOT NULL,
			status VARCHAR(20) NOT NULL DEFAULT 'active',
			PRIMARY KEY (id),
			INDEX idx_channel_id (channel_id)
    	) $charset_collate;";

		dbDelta( $sql );
	}
}
