<?php 
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
/* phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.SchemaChange */

global $wpdb;

$charset_collate = $wpdb->get_charset_collate();

$kirb_diamonds_metatable = $wpdb->prefix . 'kirb_diamonds_meta';
$kirb_rc_table = $wpdb->prefix . 'kirb_compare_recent_prods';
$kirb_byortable = $wpdb->prefix . 'kirb_byor';
$kirb_metadata = $wpdb->prefix . 'kirb_metadata';
$kirb_wishlist = $wpdb->prefix . 'kirb_wishlist';
$kirb_cache = $wpdb->prefix . 'kirb_cache';

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

// Create metadata table
$kirb_diamonds_meta_table = "CREATE TABLE IF NOT EXISTS $kirb_diamonds_metatable (
    id int NOT NULL AUTO_INCREMENT,
    post_id int NOT NULL,
    diamond_uid TEXT NOT NULL,
    PRIMARY KEY (id)
) $charset_collate;";

dbDelta($kirb_diamonds_meta_table);

// Create BYOR table
$kirb_byor_table = "CREATE TABLE IF NOT EXISTS $kirb_byortable (
        id int NOT NULL AUTO_INCREMENT,
        user_id TEXT NOT NULL,
        ring_post_id int NOT NULL,
        ring_variation_id int NOT NULL,
        ring_attributes TEXT NOT NULL,
        diamond_uid TEXT NOT NULL,
        diamond_type int NOT NULL,
        ord int NOT NULL,
        PRIMARY KEY (id)
    ) $charset_collate;";

// ord = in which order the diamond is added to the ring
// 0 = diamond first
// 1 = ring first

dbDelta($kirb_byor_table);

// Check if ring_attributes column exists in byor table
// Check if ring_attributes column exists in byor table
$col_ring_attr = $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM {$kirb_byortable} LIKE %s", 'ring_attributes' ) );
if ( $col_ring_attr !== 'ring_attributes' ) {
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Table name is internal/constant; no user input.
    $wpdb->query( "ALTER TABLE {$kirb_byortable} ADD ring_attributes TEXT NOT NULL AFTER ring_variation_id" );
}

// Check if uid column exists in byor table
// Check if uid column exists in byor table
$col_uid = $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM {$kirb_byortable} LIKE %s", 'uid' ) );
if ( $col_uid !== 'uid' ) {
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Table name is internal/constant; no user input.
    $wpdb->query( "ALTER TABLE {$kirb_byortable} ADD uid TEXT NOT NULL AFTER id" );
}

// Check if setting_type column exists in byor table
// Check if setting_type column exists in byor table
$col_setting_type = $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM {$kirb_byortable} LIKE %s", 'setting_type' ) );
if ( $col_setting_type !== 'setting_type' ) {
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Table name is internal/constant; no user input.
    $wpdb->query( "ALTER TABLE {$kirb_byortable} ADD setting_type INT NOT NULL AFTER diamond_type" );
}

$kirb_recent_compare_table = "CREATE TABLE IF NOT EXISTS $kirb_rc_table(
    id INT PRIMARY KEY AUTO_INCREMENT,
    type INT,
    diamond_uid TEXT,
    user_id INT
) $charset_collate;";

dbDelta($kirb_recent_compare_table);

$kirb_metadata_table = "CREATE TABLE IF NOT EXISTS $kirb_metadata(
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `meta_key` VARCHAR(191) NOT NULL,
    `meta_value` LONGTEXT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `idx_meta_key` (`meta_key`)
) $charset_collate;";

dbDelta($kirb_metadata_table);

$kirb_wishlist_table = "CREATE TABLE IF NOT EXISTS $kirb_wishlist (
  id INT NOT NULL AUTO_INCREMENT ,
  user_id TEXT NOT NULL ,
  ref_id INT NULL DEFAULT NULL , 
  diamond_uid TEXT NOT NULL , 
  diamond_meta JSON NOT NULL , 
  ring_id INT NULL DEFAULT NULL , 
  ring_variation_id INT NULL DEFAULT NULL , 
  type INT NOT NULL , 
  PRIMARY KEY (id)
) $charset_collate;";

dbDelta($kirb_wishlist_table);

$kirb_cache_table = "CREATE TABLE IF NOT EXISTS $kirb_cache (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    `cache_key` VARCHAR(191) NOT NULL UNIQUE,
    `cache_value` LONGTEXT,
    `expires_at` BIGINT UNSIGNED NOT NULL,
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    INDEX (`expires_at`)
  ) $charset_collate;";

dbDelta($kirb_cache_table);

$is_plugin_active = kirbGetMeta('_is_plugin_active') == 'true';

if(!$is_plugin_active){
    // Default settings for the plugin
    kirbAddMeta('_setting_primary_color','#7646D7');
    kirbAddMeta('_setting_accent_color','#EBE2FB');
    kirbAddMeta('_setting_text_primary_color', '#ffffff');
    kirbAddMeta('_setting_text_accent_color', '#000000');
    kirbAddMeta('_setting_primary_color_filter','invert(41%) sepia(21%) saturate(6164%) hue-rotate(237deg) brightness(89%) contrast(93%)');

    kirbAddMeta('_setting_text_primary_color_filter', 'invert(100%) sepia(0%) saturate(0%) hue-rotate(80deg) brightness(105%) contrast(102%)');
    kirbAddMeta('_setting_text_accent_color_filter', 'invert(0%) sepia(0%) saturate(13%) hue-rotate(236deg) brightness(99%) contrast(105%)');

    kirbAddMeta('_setting_products_per_page',16);
    kirbAddMeta('_setting_cache_enabled', 'true');
    kirbAddMeta('_setting_catg_control',wp_json_encode(array(
        "NATURAL" => true,
        "GEMSTONE" => true,
        "LAB CREATED" => true,
        "COLORED DIAMONDS" => true
    )));
    kirbAddMeta("_setting_ring_setting_catg","");
}

// Default ring wedding category - new setting
if(!kirbGetMeta('_setting_ring_wedding_catg')){
    kirbAddMeta('_setting_ring_wedding_catg','[]');
}

$addons_data = array();
if($is_plugin_active) {
    $addons_data = json_decode(kirbGetMeta('_setting_addon_data'), true);
}

// Addons Default Data
$addons_arr = array(
    'consult_expert' => array(
        'enabled' => $addons_data['consult_expert']['enabled'] ?? true,
        'string' => $addons_data['consult_expert']['string'] ?? '',
    ),
    'free_shipping' => array(
        'enabled' => $addons_data['free_shipping']['enabled'] ?? true,
        'string' => $addons_data['free_shipping']['string'] ?? '',
    ),
    'easy_returns' => array(
        'enabled' => $addons_data['easy_returns']['enabled'] ?? true,
        'string' => $addons_data['easy_returns']['string'] ?? '',
    ),
    'free_resizing' => array(
        'enabled' => $addons_data['free_resizing']['enabled'] ?? true,
        'string' => $addons_data['free_resizing']['string'] ?? '',
    ),
    'fast_shipping' => array(
        'enabled' => $addons_data['fast_shipping']['enabled'] ?? true,
        'string' => $addons_data['fast_shipping']['string'] ?? '5',
    ),
    'ring_size' => array(
        'enabled' => $addons_data['ring_size']['enabled'] ?? true,
        'string' => $addons_data['ring_size']['string'] ?? '',
    ),
    'add_to_cart' => array(
        'enabled' => $addons_data['add_to_cart']['enabled'] ?? true,
        'string' => $addons_data['add_to_cart']['string'] ?? '',
    ),
    'choose_this_setting' => array(
        'enabled' => $addons_data['choose_this_setting']['enabled'] ?? true,
        'string' => $addons_data['choose_this_setting']['string'] ?? '',
    ),
    'wed_ring_size' => array(
        'enabled' => $addons_data['wed_ring_size']['enabled'] ?? true,
        'string' => $addons_data['wed_ring_size']['string'] ?? '',
    ),
    'engraving_catg' => array(
        'enabled' => $addons_data['engraving_catg']['enabled'] ?? false,
        'string' => $addons_data['engraving_catg']['string'] ?? '',
    ),
    'pendant_catg' => array(
        'enabled' => $addons_data['pendant_catg']['enabled'] ?? false,
        'string' => $addons_data['pendant_catg']['string'] ?? '',
    ),
    'virtual_ring_view' => array(
        'enabled' => $addons_data['virtual_ring_view']['enabled'] ?? true,
        'string' => $addons_data['virtual_ring_view']['string'] ?? '',
    ),
    'default_sort' => array(
        'title' => $addons_data['default_sort']['title'] ?? 'Popular',
        'select' => $addons_data['default_sort']['select'] ?? 'popular',
    ),
);

$addons_new_data = array();
foreach($addons_arr as $addon => $value){
    $addons_new_data[$addon] = array(
        'enabled' => $value['enabled'] ?? false,
        'string' => $value['string'] ?? '',
    );
}
kirbAddMeta('_setting_addon_data',wp_json_encode($addons_new_data));

if(!$is_plugin_active || !kirbGetMeta('_admin_tab_config')) {
    $admin_tab_config = array(
        'pricing-tab' => array(
            'active' => true,
            'completed' => $is_plugin_active
        ),
        'initial-tab' => array(
            'active' => false,
            'completed' => false
        ),
        'help-tab' => array(
            'active' => false,
            'completed' => false
        ),
        'lang-tab' => array(
            'active' => false,
            'completed' => false
        ),
        'feed-control' => array(
            'active' => false,
            'completed' => false
        ),
    );
    kirbAddMeta('_admin_tab_config',wp_json_encode($admin_tab_config));
    kirbAddMeta('_is_plugin_initial_setup','false');
}

if(!$is_plugin_active || !kirbGetMeta('_regional_data')) {
    $kirb_init_locals_data = [
        "en_US" => [
            "enabled" => true,
            "ring_size" => "r2",
            "label" => "English"
        ],
        "en_GB" => [
            "enabled" => false,
            "ring_size" => "r2",
            "label" => "English"
        ],
        "fr_FR" => [
            "enabled" => false,
            "ring_size" => "r1",
            "label" => "French"
        ],
        "it_IT" => [
            "enabled" => false,
            "ring_size" => "r1",
            "label" => "Italian"
        ],
        "de_DE" => [
            "enabled" => false,
            "ring_size" => "r1",
            "label" => "German"
        ],
        "es_ES" => [
            "enabled" => false,
            "ring_size" => "r1",
            "label" => "Spanish"
        ],
        'other' => [
            "enabled" => false,
            "ring_size" => "r1",
            "label" => "Other"
        ]
    ];
    kirbAddMeta("_regional_data", json_encode($kirb_init_locals_data));
}

// Temp Migration Code - Remove after 1.0.0
// $kirb_active_tab_config = json_decode(kirbGetMeta('_admin_tab_config'), true);
// if(!isset($kirb_active_tab_config['feed-control'])) {
//     $kirb_active_tab_config['feed-control'] = array(
//         'active' => false,
//         'completed' => $kirb_active_tab_config['lang-tab']['completed'] ?? false
//     );
//     kirbAddMeta('_admin_tab_config',wp_json_encode($kirb_active_tab_config));
// }

// Temp Cache Remove As Of System Update
$cache_dir = KIRB_BASE_DIR . 'cache/';
if ( is_dir( $cache_dir ) ) {
    $cache_files = glob( trailingslashit( $cache_dir ) . '*' );
    if ( is_array( $cache_files ) ) {
        foreach ( $cache_files as $file ) {
            if ( is_file( $file ) ) {
                wp_delete_file( $file ); // WordPress-safe delete
            }
        }
    }

    // Delete the cache directory using WP_Filesystem
    require_once ABSPATH . 'wp-admin/includes/file.php';
    WP_Filesystem();
    global $wp_filesystem;
    if ( $wp_filesystem && $wp_filesystem->is_dir( $cache_dir ) ) {
        // Second param 'true' ensures recursive removal if needed.
        $wp_filesystem->rmdir( $cache_dir, true );
    }
}

if($is_plugin_active) {
    include_once("plugin_activation_hook.php");
}else{

    $user_info = array();
    $user_info['name'] = get_bloginfo('name');
    $user_info['company_name'] = get_bloginfo('name');
    $user_info['email'] = get_bloginfo('admin_email');
    $user_info['phone'] = '';
    $user_info['country'] = get_bloginfo('language');

    $user_info['country'] = explode('-', $user_info['country'])[1];
    $country_data = json_decode(kirb_file_get_contents(KIRB_PLUGIN_DIR . '/assets/country-codes.json'), true);
    foreach($country_data as $country){
        if($country['code'] == $user_info['country']){
            $user_info['country'] = $country['name'];
            break;
        }
    }

    $user_info['website_url'] = site_url();
    
    kirbAddMeta('_user_info', wp_json_encode($user_info));

    kirb_set_completed_tab('pricing-tab', true);

    include_once("plugin_activation_hook.php");
}

$kirb_upload_dir = wp_get_upload_dir();

// Migrate language settings
if(!file_exists(($kirb_upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'kirb-user-defined-localization.json'))){
    copy(KIRB_BASE_DIR . DIRECTORY_SEPARATOR . 'languages'.DIRECTORY_SEPARATOR.'user-defined-localization.json', $kirb_upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'kirb-user-defined-localization.json');
}else{
    $new_lang_data = json_decode(kirb_file_get_contents(KIRB_PLUGIN_DIR . '/languages/user-defined-localization.json'), true);
    $old_lang_data = json_decode(kirb_file_get_contents($kirb_upload_dir['baseurl'] . '/kirb-user-defined-localization.json'), true);
    $lang_data = kirb_syncData($old_lang_data, $new_lang_data);
    $lang_json_output = wp_json_encode($lang_data, JSON_PRETTY_PRINT);
    kirb_file_put_contents($kirb_upload_dir['basedir'] . DIRECTORY_SEPARATOR .'kirb-user-defined-localization.json', $lang_json_output);
}

// Migrate other language file
if(!file_exists(($kirb_upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'kirb-other-lang.json'))) {
    copy(KIRB_BASE_DIR . DIRECTORY_SEPARATOR . 'languages'. DIRECTORY_SEPARATOR .'other.json', $kirb_upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'kirb-other-lang.json');
}

// Migrate config file
if(!file_exists(($kirb_upload_dir['basedir'] . DIRECTORY_SEPARATOR .  'kirb-site-config.json'))){
    copy(KIRB_BASE_DIR . DIRECTORY_SEPARATOR . 'config.json', $kirb_upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'kirb-site-config.json');
}

// Migrate sideload directoy
if(!file_exists(($kirb_upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'kirb-sideload-files' . DIRECTORY_SEPARATOR . 'index.php'))){
    kirb_copy_dir(KIRB_BASE_DIR . '/sideload-files', $kirb_upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'kirb-sideload-files');
}
/* phpcs:enable */
