<?php

namespace Limb_Chatbot\Includes\Migrations;

use Limb_Chatbot\Includes\Data_Objects\Chatbot;
use Limb_Chatbot\Includes\Data_Objects\Lead_Field;
use Limb_Chatbot\Includes\Data_Objects\Setting;
use Limb_Chatbot\Includes\Data_Schemas\Setting as Setting_Schema;

/**
 * Migration for version 1.0.14
 *
 * Updates custom_instructions and default_custom_instructions parameters
 * for the default chatbot with new concise response guidelines.
 *
 * @since 1.0.14
 */
class Migration_1_0_14 extends Abstract_Migration {

	/**
	 * Setting key prefix for notification type opt-in: lbaic.notifications.notification_type.{type_key}.
	 * Value 1 = enabled (send), 0 = disabled.
	 */
	const SETTING_NOTIFICATION_TYPE_PREFIX = 'lbaic.notifications.notification_type.';
	/**
	 * Notification type keys to enable by default (global opt-in settings).
	 *
	 * @var string[]
	 * @since 1.0.15
	 */
	private static array $default_notification_types = [ 'chat_created', 'lead_captured' ];

	/**
	 * Get the target version this migration upgrades to.
	 *
	 * @return string
	 * @since 1.0.14
	 */
	public function get_version(): string {
		return '1.0.14';
	}

	/**
	 * Get migration description.
	 *
	 * @return string
	 * @since 1.0.14
	 */
	public function get_description(): string {
		return 'Update custom_instructions and migrate lead capture widgets to config-based field mapping';
	}

	/**
	 * Execute the migration.
	 *
	 * Updates the custom_instructions and default_custom_instructions parameters
	 * for the default chatbot with new guidelines emphasizing concise responses.
	 *
	 * @return bool True on success, false on failure.
	 * @since 1.0.14
	 */
	public function up(): bool {
		$this->log( 'Starting migration 1.0.14 - Updating custom instructions and migrating lead capture widgets' );

		try {
			$chatbot = Chatbot::make();

			// Update custom instructions (role + guidelines; same as schema default)
			$custom_instructions = Setting_Schema::get_default_custom_instructions();

			$chatbot->update_parameter( 'custom_instructions', $custom_instructions );
			$chatbot->update_parameter( 'default_custom_instructions', $custom_instructions );

			if ( ! $this->create_notification_log_table() ) {
				return false;
			}

			$this->add_default_notification_opt_in_settings();

			$this->log( 'Migration 1.0.14 completed successfully' );

			return true;
		} catch ( \Exception $e ) {
			$this->log( sprintf( 'Error in migration 1.0.14: %s', $e->getMessage() ), 'error' );

			return false;
		}
	}

	/**
	 * Create the lbaic_notification_log table.
	 *
	 * @return bool True on success, false on failure.
	 * @since 1.0.15
	 */
	private function create_notification_log_table(): bool {
		$table_name = $this->wpdb->prefix . 'lbaic_notification_log';

		if ( $this->table_exists( $table_name ) ) {
			$this->log( "Table {$table_name} already exists, skipping creation" );

			return true;
		}

		$collate = $this->wpdb->get_charset_collate();

		$sql = "CREATE TABLE `{$table_name}` (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			chatbot_user_id bigint(20) unsigned NOT NULL,
			type_key varchar(100) NOT NULL,
			channel varchar(50) NOT NULL,
			status varchar(20) NOT NULL DEFAULT 'pending',
			sent_at datetime NULL DEFAULT NULL,
			fail_reason TEXT NULL DEFAULT NULL,
			content_type varchar(100) NULL DEFAULT NULL,
			content LONGTEXT NULL DEFAULT NULL,
			PRIMARY KEY (id),
			KEY chatbot_user_id (chatbot_user_id),
			KEY type_key (type_key),
			KEY channel (channel),
			KEY status (status),
			KEY sent_at (sent_at)
		) {$collate};";

		$this->db_delta( $sql );

		if ( ! $this->table_exists( $table_name ) ) {
			$this->log( "Failed to create table {$table_name}", 'error' );

			return false;
		}

		$this->log( "Successfully created table {$table_name}" );

		return true;
	}

	/**
	 * Add default (global) settings to enable all notification types for opt-in.
	 * When a chatbot user has no meta preference, these settings control whether to send.
	 *
	 * @return void
	 * @since 1.0.15
	 */
	private function add_default_notification_opt_in_settings(): void {
		foreach ( self::$default_notification_types as $type_key ) {
			$key = self::SETTING_NOTIFICATION_TYPE_PREFIX . $type_key;
			$this->maybe_add_setting( $key, 1 );
		}
		$this->log( 'Default notification opt-in settings added' );
	}
}
