<?php
/**
 * Class Controller file.
 *
 * @package WebToffee
 */

namespace WebToffee\CookieConsent\Lite\Admin\Modules\Settings\Includes;

use WebToffee\CookieConsent\Lite\Admin\Modules\Settings\Includes\Settings;
use WebToffee\CookieConsent\Lite\Admin\Modules\Scanner\Api;
use WP_Error;
use WebToffee\CookieConsent\Lite\Admin\Modules\Banners\Includes\Banner;
use WebToffee\CookieConsent\Lite\Includes\Filesystem;
use Exception;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Handles Cookies Operation
 *
 * @class       Controller
 * @version     3.0.0
 * @package     WebToffee
 */
class Controller {

	/**
	 * Instance of the current class
	 *
	 * @var object
	 */
	private static $instance;

	/**
	 * Return the current instance of the class
	 *
	 * @return object
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Localize common plugin settings.
	 *
	 * @param array $data Data.
	 * @return array
	 */
	public function load_common_settings( $data ) {
		$settings                = new Settings();
		$data['settings']        = $settings->get();
		$data['settings']['url'] = get_site_url();
		$data['vendors']         = ! empty( get_option( 'wcc_vendor_data', array() ) ) ? get_option( 'wcc_vendor_data' ) : array(
			'thirdpartyvendors' => \WebToffee\CookieConsent\Lite\Frontend\Modules\Iab\IAB::get_instance()->get_allowed_vendor_list(),
			'googlevendors'     => \WebToffee\CookieConsent\Lite\Frontend\Modules\Iab\IAB::get_instance()->get_allowed_google_vendor_list(),
		);
		return $data;
	}

	/**
	 *  Fetch site info from either locally or from API.
	 *
	 * @param array $args Array of arguments.
	 * @return array
	 */
	public function get_info( $args = array() ) {
		return $this->get_site_info( $args );
	}

	/**
	 *  Get the current plan details and features list from a local DB.
	 *
	 * @param array $args Array of arguments.
	 * @return array
	 */
	public function get_site_info( $args = array() ) {
		return $this->get_default();
	}

	/**
	 * Get default site info.
	 *
	 * @return array
	 */
	public function get_default() {
		$settings  = new Settings();
		$scan      = new \WebToffee\CookieConsent\Lite\Admin\Modules\Scanner\Includes\Controller();
		$scan_data = $scan->get_item_from_db();
		return array(
			'id'                         => '',
			'url'                        => get_site_url(),
			'plan'                       => array(
				'id'          => '',
				'slug'        => 'free',
				'name'        => __( 'Free', 'webtoffee-cookie-consent' ),
				'description' => __( 'Free Plan', 'webtoffee-cookie-consent' ),
				'scan_limit'  => '100',
				'log_limit'   => 5000,
				'features'    => array(
					'multi_law'         => false,
					'custom_css'        => false,
					'custom_branding'   => false,
					'config_geo_rules'  => false,
					'max_free_websites' => 1,
					'remove_powered_by' => false,
					'popup_layout'      => false,
				),
			),
			'banners'                    => array(
				'status' => \WebToffee\CookieConsent\Lite\Admin\Modules\Banners\Includes\Controller::get_instance()->check_status(),
			),
			'consent_logs'               => array(
				'status' => $settings->get_consent_log_status(),
			),
			'scans'                      => array(
				'data' => isset( $scan_data ) ? $scan_data : array(),
			),
			'languages'                  => array(
				'default' => $settings->get_default_language(),
			),
			'site_language'              => array(
				'language' => $settings->get_site_language(),
			),
			'multiligual'                => array(
				'status' => $settings->is_site_multilingual(),
			),
			'translation_modal'          => array(
				'show' => $settings->get_translation_modal_status(),
			),
			'license'                    => array(
				'status' => get_option( 'wtcookieconsent_activation_status', false ),
			),
			'tables_missing'             => count( wcc_missing_tables() ) > 0,
			'privacy_policy'             => array(
				'page' => $settings->get_privacy_policy(),
			),
			'renew_date'                 => array(
				'date' => $settings->get_renew_date(),
			),
			'migration_notice'           => array(
				'status' => $settings->get_migration_notice_status(),
			),
			'renew_consent_notice'       => array(
				'status' => $settings->get_renew_consent_notice_status(),
			),
			'no_cookie_scripts_to_block' => array(
				'selected' => $settings->get_no_cookie_scripts_to_block(),
			),
			'review_reminder'            => array(
				'data' => $settings->get_review_reminder_data(),
			),
		);
	}

	/**
	 * Maybe update the plugin settings if required.
	 *
	 * @param array $response Response from the web app.
	 * @return void
	 */
	public function maybe_update_settings( $response ) {
		$settings                           = new Settings();
		$data                               = $settings->get();
		$data['consent_logs']               = isset( $response['consent_logs'] ) ? $response['consent_logs'] : array();
		$data['languages']                  = isset( $response['languages'] ) ? $response['languages'] : array();
		$data['translation_modal']          = isset( $response['translation_modal'] ) ? $response['translation_modal'] : array();
		$data['renew_date']                 = isset( $response['renew_date'] ) ? $response['renew_date'] : array();
		$data['google_consent_mode']        = isset( $response['google_consent_mode'] ) ? $response['google_consent_mode'] : array();
		$data['migration_notice']           = isset( $response['migration_notice'] ) ? $response['migration_notice'] : array();
		$data['url_passthrough']            = isset( $response['url_passthrough'] ) ? $response['url_passthrough'] : array();
		$data['gcm_debug_mode']             = isset( $response['gcm_debug_mode'] ) ? $response['gcm_debug_mode'] : array();
		$data['gtag_behavior']              = isset( $response['gtag_behavior'] ) ? $response['gtag_behavior'] : array();
		$data['redact_ads_data']            = isset( $response['redact_ads_data'] ) ? $response['redact_ads_data'] : array();
		$data['renew_consent_notice']       = isset( $response['renew_consent_notice'] ) ? $response['renew_consent_notice'] : array();
		$data['hide_banner_on_pages']       = isset( $response['hide_banner_on_pages'] ) ? $response['hide_banner_on_pages'] : array();
		$data['no_cookie_scripts_to_block'] = isset( $response['no_cookie_scripts_to_block'] ) ? $response['no_cookie_scripts_to_block'] : array();
		$data['review_reminder']            = isset( $response['review_reminder'] ) ? $response['review_reminder'] : array();
		$data['microsoft_clarity']          = isset( $response['microsoft_clarity'] ) ? $response['microsoft_clarity'] : array();
		$data['microsoft_uet']              = isset( $response['microsoft_uet'] ) ? $response['microsoft_uet'] : array();
		$data['gtm_template']               = isset( $response['gtm_template'] ) ? $response['gtm_template'] : array();
		update_option( 'wcc_settings', $data );
	}

	/**
	 * Delete the cache.
	 *
	 * @return void
	 */
	public function delete_cache() {
		wp_cache_flush();
	}

	/**
	 * Reset the plugin settings to default
	 *
	 */
	public function reset() {
		// Load default settings
		$settings = new \WebToffee\CookieConsent\Lite\Admin\Modules\Settings\Includes\Settings();
		$default  = $settings->get_defaults();
		$settings->update( $default );
		return true;
	}
	/**
	 * Update the status of admin renew consent notices.
	 * @param array  $request Request params.
	 * @since 3.1.1
	 * @return WP_Error|WP_REST_Response
	 */
	public function update_renew_consent_notice( $request ) {
		$data = isset( $request['status'] ) ? $request['status'] : false;
		update_option( 'wcc_show_renew_consent_notice', $data );
		return true;
	}
	/**
	 * Update the review seeking banner data
	 * @param array  $request Request params.
	 * @since 3.2.0
	 * @return WP_Error|WP_REST_Response
	 */
	public function update_review_data( $request ) {
		$data = isset( $request['status'] ) ? $request['status'] : false;
		update_option( 'wcc_review_reminder', $data );
		return true;
	}
	/**
	 * Export settings and banners to a JSON file.
	 *
	 * @since 3.3.0
	 * @return array
	 */
	public function export_settings() {
		// Get settings data
		$object        = new Settings();
		$settings_data = $object->get();

		// Get banner data
		$banners = \WebToffee\CookieConsent\Lite\Admin\Modules\Banners\Includes\Controller::get_instance()->get_items();

		// Get vendor and purpose features data
		$vendor_data      = get_option( 'wcc_vendor_data', array() );
		$purpose_features = get_option( 'wcc_purpose_features', array() );

		// Get cookie categories data (without cookies)
		$cookie_categories_raw = \WebToffee\CookieConsent\Lite\Admin\Modules\Cookies\Includes\Category_Controller::get_instance()->get_item_from_db();
		
		// Remove cookies from each category to reduce export size
		$cookie_categories = array();
		if ( ! empty( $cookie_categories_raw ) ) {
			foreach ( $cookie_categories_raw as $category ) {
				$category_copy = clone $category;
				unset( $category_copy->cookies ); // Remove cookies array
				$cookie_categories[] = $category_copy;
			}
		}

		// Check if no data exists
		if ( empty( $settings_data ) && empty( $banners ) ) {
			wp_die( 'No data found to export.' );
		}

		$uploads_dir    = Filesystem::get_instance()->get_uploads_dir( 'webtoffee' );
		$date_timestamp = wp_date( 'Y-m-d' ) . '_' . strtotime( wp_date( 'Y-m-d H:i:s' ) );

		// JSON file name
		$json_filename = "wcc_settings_$date_timestamp.json";
		$json_path     = $uploads_dir['path'] . $json_filename;

		// Ensure the directory exists
		if ( ! is_dir( $uploads_dir['path'] ) ) {
			wp_mkdir_p( $uploads_dir['path'] );
		}

		// Prepare the data to export
		$export_data = array();

		if ( ! empty( $settings_data ) ) {
			$export_data['settings'] = $settings_data;
		}

		if ( ! empty( $banners ) ) {
			$export_data['banner_data'] = $banners;
		}

		if ( ! empty( $vendor_data ) ) {
			$export_data['vendor_data'] = $vendor_data;
		}

		if ( ! empty( $purpose_features ) ) {
			$export_data['purpose_features'] = $purpose_features;
		}

		if ( ! empty( $cookie_categories ) ) {
			$export_data['cookie_categories'] = $cookie_categories;
		}

		// Convert data to JSON format
		$json_data = json_encode( $export_data, JSON_PRETTY_PRINT );

		// Save JSON data to file using WP_Filesystem
		global $wp_filesystem;
		if ( empty( $wp_filesystem ) ) {
			require_once ABSPATH . '/wp-admin/includes/file.php';
			WP_Filesystem();
		}
		
		$wp_filesystem->put_contents( $json_path, $json_data, FS_CHMOD_FILE );

		return array(
			'json_url'  => $uploads_dir['url'] . $json_filename,
			'file_name' => $json_filename,
		);
	}
	/**
	 * Import settings and banners from a JSON file.
	 *
	 * @since 3.3.0
	 * @return void
	 */
	public function import_settings() {
		// Check if file was uploaded
		if ( ! isset( $_FILES['file'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
			return array(
				'success' => false,
				'message' => __( 'No file was uploaded.', 'webtoffee-cookie-consent' ),
			);
		}

		$file = $_FILES['file']; // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

		// Basic validation
		if ( $file['error'] !== UPLOAD_ERR_OK ) {
			return array(
				'success' => false,
				'message' => sprintf(
					/* translators: %s: file upload error code */
					__( 'File upload failed with error: %s', 'webtoffee-cookie-consent' ),
					$file['error']
				),
			);
		}

		// Check file exists and is readable
		if ( ! file_exists( $file['tmp_name'] ) || ! is_readable( $file['tmp_name'] ) ) {
			return array(
				'success' => false,
				'message' => __( 'Uploaded file is not accessible.', 'webtoffee-cookie-consent' ),
			);
		}

		// Verify file type - check both extension and mime type
		$file_type  = wp_check_filetype( $file['name'] );
		$valid_json = ( $file_type['ext'] === 'json' || $file['type'] === 'application/json' );

		if ( ! $valid_json ) {
			return array(
				'success' => false,
				'message' => __( 'Invalid file type. Please upload a JSON file.', 'webtoffee-cookie-consent' ),
			);
		}

		// Read and validate JSON content
		$import_data = wcc_read_json_file( $file['tmp_name'] );
		if ( json_last_error() !== JSON_ERROR_NONE ) {
			return array(
				'success' => false,
				'message' => sprintf(
					/* translators: %s: JSON error message */
					__( 'Invalid JSON format: %s', 'webtoffee-cookie-consent' ),
					json_last_error_msg()
				),
			);
		}

		try {
			// Validate required data structure
			if ( ! isset( $import_data['settings'] ) || ! is_array( $import_data['settings'] ) ) {
				return array(
					'success' => false,
					'message' => __( 'Invalid settings data structure in the imported file.', 'webtoffee-cookie-consent' ),
				);
			}

			// Update settings while preserving site information
			$object           = new Settings();
			$current_settings = $object->get();

			// Preserve existing site information
			$import_data['settings']['site'] = $current_settings['site'];

			$object->update( $import_data['settings'] );

			// Update banners if present
			if ( isset( $import_data['banner_data'] ) && is_array( $import_data['banner_data'] ) ) {
				foreach ( $import_data['banner_data'] as $banner_data ) {
					if ( ! isset( $banner_data['name'], $banner_data['settings'], $banner_data['contents'] ) ) {
						continue; // Skip invalid banner data
					}

					$id     = isset( $banner_data['banner_id'] ) ? absint( $banner_data['banner_id'] ) : 0;
					$banner = new Banner( $id );
					$banner->set_name( $banner_data['name'] );
					$banner->set_default( $banner_data['default'] ?? false );
					$banner->set_status( $banner_data['status'] ?? true );
					$banner->set_settings( $banner_data['settings'] );
					$banner->set_contents( $banner_data['contents'] );

					\WebToffee\CookieConsent\Lite\Admin\Modules\Banners\Includes\Controller::get_instance()
						->update_item( $banner );
				}
			}

			// Update vendor data if present
			if ( isset( $import_data['vendor_data'] ) ) {
				update_option( 'wcc_vendor_data', $import_data['vendor_data'] );
			}

			// Update purpose features if present
			if ( isset( $import_data['purpose_features'] ) ) {
				update_option( 'wcc_purpose_features', $import_data['purpose_features'] );
			}

			// Update cookie categories if present
			if ( isset( $import_data['cookie_categories'] ) && is_array( $import_data['cookie_categories'] ) ) {
				global $wpdb;
				
				foreach ( $import_data['cookie_categories'] as $category_data ) {
					// Convert to array if it's an object
					if ( is_object( $category_data ) ) {
						$category_data = json_decode( wp_json_encode( $category_data ), true );
					}
					
					if ( ! isset( $category_data['slug'] ) || empty( $category_data['slug'] ) ) {
						continue; // Skip invalid category data
					}

					// Find existing category by slug - get full row
					$existing_category = $wpdb->get_row( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
						$wpdb->prepare( 
							"SELECT * FROM {$wpdb->prefix}wcc_cookie_categories WHERE slug = %s", 
							$category_data['slug'] 
						) 
					); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

					// Create category object - pass existing data if found
					if ( $existing_category ) {
						$category = new \WebToffee\CookieConsent\Lite\Admin\Modules\Cookies\Includes\Cookie_Categories( $existing_category );
					} else {
						$category = new \WebToffee\CookieConsent\Lite\Admin\Modules\Cookies\Includes\Cookie_Categories();
					}
					
					// Set category properties - convert nested arrays/objects properly
					if ( isset( $category_data['name'] ) ) {
						$name = $category_data['name'];
						if ( is_object( $name ) ) {
							$name = json_decode( wp_json_encode( $name ), true );
						}
						$category->set_name( $name );
					}
					
					$category->set_slug( $category_data['slug'] );
					
					if ( isset( $category_data['description'] ) ) {
						$description = $category_data['description'];
						if ( is_object( $description ) ) {
							$description = json_decode( wp_json_encode( $description ), true );
						}
						$category->set_description( $description );
					}
					
					if ( isset( $category_data['prior_consent'] ) ) {
						$category->set_prior_consent( (bool) $category_data['prior_consent'] );
					}
					
					if ( isset( $category_data['visibility'] ) ) {
						$category->set_visibility( (bool) $category_data['visibility'] );
					}
					
					if ( isset( $category_data['priority'] ) ) {
						$category->set_priority( (int) $category_data['priority'] );
					}
					
					if ( isset( $category_data['sell_personal_data'] ) ) {
						$category->set_sell_personal_data( (bool) $category_data['sell_personal_data'] );
					}
					
					if ( isset( $category_data['meta'] ) ) {
						$meta = $category_data['meta'];
						if ( is_object( $meta ) ) {
							$meta = json_decode( wp_json_encode( $meta ), true );
						}
						$category->set_meta( $meta );
					}
					
					$category->save();
				}
			}

			return array(
				'success' => true,
				'message' => __( 'Settings imported successfully.', 'webtoffee-cookie-consent' ),
			);

		} catch ( Exception $e ) {
			return array(
				'success' => false,
				'message' => sprintf(
					/* translators: %s: error message */
					__( 'Error processing import: %s', 'webtoffee-cookie-consent' ),
					$e->getMessage()
				),
			);
		}
	}
}
