<?php

namespace Meliconnect\Meliconnect\Core\Controllers;

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

use Meliconnect\Meliconnect\Core\Helpers\FormHelper;
use Meliconnect\Meliconnect\Core\Helpers\Helper;
use Meliconnect\Meliconnect\Core\Interfaces\ControllerInterface;
use Meliconnect\Meliconnect\Core\Models\UserConnection;

class SettingController implements ControllerInterface
{

    public function __construct()
    {
        wp_enqueue_media();
    }

    public function getData()
    {
        // Logic to get and return data
        $data = array();
        return $data;
    }



    /* START HANDLE AJAX METHODS */
    public static function handleSettingsGetGeneralHtml()
    {

        if (! isset($_GET['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'ajax_settings_nonce')) {
            wp_send_json_error(array('message' => 'Nonce verification failed.'));
            wp_die();
        }

        $general_data = Helper::getMeliconnectOptions('general');
        $sellers_with_free_plan = UserConnection::getSellersByPlanComparison('free');


        header('Content-Type:  text/html');

        include MELICONNECT_PLUGIN_ROOT . 'includes/Core/Views/Partials/Settings/general.php';

        die();
    }

    public static function handleSettingsGetExportHtml()
    {
        if (! isset($_GET['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'ajax_settings_nonce')) {
            wp_send_json_error(array('message' => 'Nonce verification failed.'));
            wp_die();
        }

        $export_data = Helper::getMeliconnectOptions('export');

        header('Content-Type:  text/html');

        include MELICONNECT_PLUGIN_ROOT . 'includes/Core/Views/Partials/Settings/export.php';

        die();
    }

    public static function handleSettingsGetImportHtml()
    {
        if (! isset($_GET['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'ajax_settings_nonce')) {
            wp_send_json_error(array('message' => 'Nonce verification failed.'));
            wp_die();
        }

        $import_data = Helper::getMeliconnectOptions('import');

        header('Content-Type:  text/html');

        include MELICONNECT_PLUGIN_ROOT . 'includes/Core/Views/Partials/Settings/import.php';

        die();
    }

    public static function handleSettingsGetSyncHtml()
    {
        if (! isset($_GET['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'ajax_settings_nonce')) {
            wp_send_json_error(array('message' => 'Nonce verification failed.'));
            wp_die();
        }

        $sync_data = Helper::getMeliconnectOptions('sync');
        $sellers_with_free_plan = UserConnection::getSellersByPlanComparison('free');

        header('Content-Type:  text/html');

        include MELICONNECT_PLUGIN_ROOT . 'includes/Core/Views/Partials/Settings/sync.php';

        die();
    }

    public static function handleSettingsGetMlEventsHtml()
    {

        if (! isset($_GET['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'ajax_settings_nonce')) {
            wp_send_json_error(array('message' => 'Nonce verification failed.'));
            wp_die();
        }

        $sync_data = Helper::getMeliconnectOptions('sync');
        $sellers_with_free_plan = UserConnection::getSellersByPlanComparison('free');

        header('Content-Type: text/html');

        include MELICONNECT_PLUGIN_ROOT . 'includes/Core/Views/Partials/Settings/ml-events.php';

        die();
    }


    public static function handleSaveGeneralSettings()
    {
        if (
            ! isset($_POST['nonce']) ||
            ! wp_verify_nonce(
                sanitize_text_field(wp_unslash($_POST['nonce'])),
                'ajax_settings_nonce'
            )
        ) {
            wp_send_json_error([
                'message' => 'Nonce verification failed.'
            ]);

            wp_die();
        }

        // Permisos
        if (! current_user_can('meliconnect_manage_plugin')) {

            wp_send_json_error(
                esc_html__(
                    'You do not have permission to perform this action',
                    'meliconnect'
                )
            );

            return;
        }

        /**
         * =========================
         * DATA
         * =========================
         */

        $data = [];

        $data['meliconnect_general_image_attachment_ids'] =
            (
                isset($_POST['meliconnect_general_image_attachment_ids']) &&
                is_array($_POST['meliconnect_general_image_attachment_ids'])
            )
            ? array_map(
                'intval',
                wp_unslash($_POST['meliconnect_general_image_attachment_ids'])
            )
            : [];

        $data['meliconnect_general_description_template'] =
            isset($_POST['meliconnect_general_description_template'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_general_description_template'])
            )
            : '';

        $data['meliconnect_general_sync_type'] =
            isset($_POST['meliconnect_general_sync_type'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_general_sync_type'])
            )
            : '';

        $data['meliconnect_general_sync_items_batch'] =
            isset($_POST['meliconnect_general_sync_items_batch'])
            ? intval(
                wp_unslash($_POST['meliconnect_general_sync_items_batch'])
            )
            : 0;

        $data['meliconnect_general_sync_frecuency_minutes'] =
            isset($_POST['meliconnect_general_sync_frecuency_minutes'])
            ? intval(
                wp_unslash($_POST['meliconnect_general_sync_frecuency_minutes'])
            )
            : 0;

        $data['meliconnect_general_sync_method'] =
            isset($_POST['meliconnect_general_sync_method'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_general_sync_method'])
            )
            : '';

        /**
         * =========================
         * SAVE OPTIONS
         * =========================
         */

        foreach ($data as $key => $value) {
            update_option($key, $value);
        }

        /**
         * =========================
         * SAVE SNAPSHOT
         * =========================
         */

        self::saveSnapshot('general', $data);

        /**
         * =========================
         * RESPONSE
         * =========================
         */

        wp_send_json_success([
            'message' => esc_html__(
                'Settings saved successfully',
                'meliconnect'
            ),
            'data' => $data
        ]);
    }

    public static function handleSaveExportSettings()
    {
        // Nonce
        if (
            ! isset($_POST['nonce']) ||
            ! wp_verify_nonce(
                sanitize_text_field(wp_unslash($_POST['nonce'])),
                'ajax_settings_nonce'
            )
        ) {
            wp_send_json_error([
                'message' => 'Nonce verification failed.'
            ]);

            wp_die();
        }

        // Permisos
        if (! current_user_can('meliconnect_manage_plugin')) {

            wp_send_json_error(
                esc_html__(
                    'You do not have permission to perform this action',
                    'meliconnect'
                )
            );

            return;
        }

        /**
         * =========================
         * DATA
         * =========================
         */

        $bool = function ($key) {
            return (
                isset($_POST[$key]) &&
                'true' === $_POST[$key]
            ) ? 'true' : 'false';
        };

        $data = [];

        $data['meliconnect_export_title'] =
            isset($_POST['meliconnect_export_title'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_export_title'])
            )
            : '';

        $data['meliconnect_export_stock'] =
            isset($_POST['meliconnect_export_stock'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_export_stock'])
            )
            : '';

        $data['meliconnect_export_price'] =
            isset($_POST['meliconnect_export_price'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_export_price'])
            )
            : '';

        $data['meliconnect_export_images'] =
            isset($_POST['meliconnect_export_images'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_export_images'])
            )
            : '';

        $data['meliconnect_export_sku'] =
            isset($_POST['meliconnect_export_sku'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_export_sku'])
            )
            : '';

        $data['meliconnect_export_product_attributes'] =
            isset($_POST['meliconnect_export_product_attributes'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_export_product_attributes'])
            )
            : '';

        $data['meliconnect_export_ml_status'] =
            isset($_POST['meliconnect_export_ml_status'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_export_ml_status'])
            )
            : '';

        $data['meliconnect_export_variations'] =
            isset($_POST['meliconnect_export_variations'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_export_variations'])
            )
            : '';

        $data['meliconnect_export_description'] =
            isset($_POST['meliconnect_export_description'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_export_description'])
            )
            : '';

        $data['meliconnect_export_description_to'] =
            isset($_POST['meliconnect_export_description_to'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_export_description_to'])
            )
            : '';

        $data['meliconnect_export_type'] =
            isset($_POST['meliconnect_export_type'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_export_type'])
            )
            : '';

        $data['meliconnect_export_finalize_ml'] =
            isset($_POST['meliconnect_export_finalize_ml'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_export_finalize_ml'])
            )
            : '';

        $data['meliconnect_export_invalid_variations_mode'] =
            isset($_POST['meliconnect_export_invalid_variations_mode'])
            ? sanitize_text_field(
                wp_unslash($_POST['meliconnect_export_invalid_variations_mode'])
            )
            : 'split';

        /**
         * =========================
         * CHECKBOXES
         * =========================
         */

        $checkbox_fields = [
            'meliconnect_export_is_disabled',
            'meliconnect_export_state_paused',
            'meliconnect_export_state_closed',
            'meliconnect_export_use_generic_attributes',
        ];

        foreach ($checkbox_fields as $checkbox) {
            $data[$checkbox] = $bool($checkbox);
        }

        /**
         * =========================
         * SAVE OPTIONS
         * =========================
         */

        foreach ($data as $key => $value) {
            update_option($key, $value);
        }

        /**
         * =========================
         * SNAPSHOT
         * =========================
         */

        self::saveSnapshot('export', $data);

        /**
         * =========================
         * RESPONSE
         * =========================
         */

        wp_send_json_success([
            'message' => esc_html__(
                'Export settings saved successfully',
                'meliconnect'
            ),
            'data' => $data
        ]);
    }

    public static function handleSaveImportSettings()
    {
        // Nonce
        if (
            ! isset($_POST['nonce']) ||
            ! wp_verify_nonce(
                sanitize_text_field(wp_unslash($_POST['nonce'])),
                'ajax_settings_nonce'
            )
        ) {
            wp_send_json_error([
                'message' => 'Nonce verification failed.'
            ]);

            wp_die();
        }

        // Permisos
        if (! current_user_can('meliconnect_manage_plugin')) {

            wp_send_json_error(
                esc_html__(
                    'You do not have permission to perform this action',
                    'meliconnect'
                )
            );

            return;
        }

        /**
         * =========================
         * HELPERS
         * =========================
         */

        $bool = function ($key) {
            return (
                isset($_POST[$key]) &&
                $_POST[$key] === 'true'
            ) ? 'true' : 'false';
        };

        /**
         * =========================
         * DATA
         * =========================
         */

        $data = [];

        $fields = [

            'meliconnect_import_title',
            'meliconnect_import_stock',
            'meliconnect_import_price',
            'meliconnect_import_promotional_price',
            'meliconnect_import_images',
            'meliconnect_import_sku',
            'meliconnect_import_categories',
            'meliconnect_max_category_level',
            'meliconnect_import_product_attributes',
            'meliconnect_import_ml_status',
            'meliconnect_import_variations',
            'meliconnect_import_variations_as',
            'meliconnect_import_description',
            'meliconnect_import_description_to',
            'meliconnect_import_type',

            // price variation
            'meliconnect_import_price_variation_operand',
            'meliconnect_import_price_variation_type',

            // stock variation
            'meliconnect_import_stock_variation_operand',
            'meliconnect_import_stock_variation_type',

            'meliconnect_import_dedupe_variations',
            'meliconnect_import_dedupe_strategy',
            'meliconnect_import_variable_update_strategy'
        ];

        foreach ($fields as $field) {

            $data[$field] = isset($_POST[$field])
                ? sanitize_text_field(
                    wp_unslash($_POST[$field])
                )
                : '';
        }

        /**
         * =========================
         * NUMBERS
         * =========================
         */

        $data['meliconnect_import_price_variation_amount'] =
            isset($_POST['meliconnect_import_price_variation_amount'])
            ? intval(
                wp_unslash($_POST['meliconnect_import_price_variation_amount'])
            )
            : 0;

        $data['meliconnect_import_stock_variation_amount'] =
            isset($_POST['meliconnect_import_stock_variation_amount'])
            ? intval(
                wp_unslash($_POST['meliconnect_import_stock_variation_amount'])
            )
            : 0;

        /**
         * =========================
         * CHECKBOXES
         * =========================
         */

        $checkbox_fields = [
            'meliconnect_import_is_disabled',
            'meliconnect_import_state_paused',
            'meliconnect_import_state_closed',
            'meliconnect_import_by_sku',
            'meliconnect_import_attrs',
        ];

        foreach ($checkbox_fields as $checkbox) {
            $data[$checkbox] = $bool($checkbox);
        }

        /**
         * =========================
         * SAVE OPTIONS
         * =========================
         */

        foreach ($data as $key => $value) {
            update_option($key, $value);
        }

        /**
         * =========================
         * SNAPSHOT
         * =========================
         */

        self::saveSnapshot('import', $data);

        /**
         * =========================
         * RESPONSE
         * =========================
         */

        wp_send_json_success([
            'message' => esc_html__(
                'Import settings saved successfully',
                'meliconnect'
            ),
            'data' => $data
        ]);
    }


    public static function handleSaveSyncSettings()
    {

        // Nonce
        if (
            ! isset($_POST['nonce']) ||
            ! wp_verify_nonce(
                sanitize_text_field(wp_unslash($_POST['nonce'])),
                'ajax_settings_nonce'
            )
        ) {
            wp_send_json_error(['message' => 'Nonce verification failed.']);
            wp_die();
        }

        // Permisos
        if (! current_user_can('meliconnect_manage_plugin')) {
            wp_send_json_error(
                esc_html__('You do not have permission to perform this action', 'meliconnect')
            );
            wp_die();
        }

        /**
         * Helper para checkboxes
         */
        $bool = function ($key) {
            return (isset($_POST[$key]) && $_POST[$key] === 'true') ? 'true' : 'false';
        };

        /**
         * =========================
         * CORE SETTINGS
         * =========================
         */
        $data = [];

        // Master
        $data['meliconnect_sync_enabled'] = $bool('meliconnect_sync_enabled');


        // Cron
        $data['meliconnect_sync_enable_cron'] = $bool('meliconnect_sync_enable_cron');

        $data['meliconnect_sync_batch_size'] =
            isset($_POST['meliconnect_sync_batch_size'])
            ? max(1, intval($_POST['meliconnect_sync_batch_size']))
            : 50;

        $data['meliconnect_sync_frequency'] =
            isset($_POST['meliconnect_sync_frequency'])
            ? max(1, intval($_POST['meliconnect_sync_frequency']))
            : 10;

        $data['meliconnect_sync_reconcile_hours'] =
            isset($_POST['meliconnect_sync_reconcile_hours'])
            ? max(1, intval($_POST['meliconnect_sync_reconcile_hours']))
            : 6;

        // Direction
        $allowed_directions = ['woo_to_meli', 'meli_to_woo', 'bidirectional'];

        $data['meliconnect_sync_direction'] =
            isset($_POST['meliconnect_sync_direction']) &&
            in_array($_POST['meliconnect_sync_direction'], $allowed_directions, true)
            ? sanitize_text_field($_POST['meliconnect_sync_direction'])
            : 'woo_to_meli';

        // What to sync
        $data['meliconnect_sync_stock']  = $bool('meliconnect_sync_stock');
        $data['meliconnect_sync_price']  = $bool('meliconnect_sync_price');
        $data['meliconnect_sync_status'] = $bool('meliconnect_sync_status');

        // Conflict resolution
        $allowed_conflicts = ['woo', 'meli'];

        $data['meliconnect_sync_conflict_resolution'] =
            isset($_POST['meliconnect_sync_conflict_resolution']) &&
            in_array($_POST['meliconnect_sync_conflict_resolution'], $allowed_conflicts, true)
            ? sanitize_text_field($_POST['meliconnect_sync_conflict_resolution'])
            : 'woo';


        /**
         * =========================
         * INTELIGENCIA BÁSICA (MUY IMPORTANTE)
         * =========================
         */

        // Si sync está desactivado → apagar todo
        if ($data['meliconnect_sync_enabled'] === 'false') {
            $data['meliconnect_sync_enable_cron'] = 'false';
        }

        // Si dirección es solo Woo → Meli, no tiene sentido escuchar cambios de Meli
        if ($data['meliconnect_sync_direction'] === 'woo_to_meli') {
            // OK: triggers Woo sirven
            // nada que tocar por ahora
        }


        // Si NO es bidirectional → conflict resolution no aplica tanto
        if ($data['meliconnect_sync_direction'] !== 'bidirectional') {
            // Podrías ignorarlo o dejar default
            // lo dejamos guardado igual por simplicidad
        }



        /**
         * =========================
         * SAVE
         * =========================
         */
        foreach ($data as $key => $value) {
            update_option($key, $value);
        }

        $fullSyncSetiings = Helper::getMeliconnectOptions('sync');

        self::saveSnapshot('sync', $fullSyncSetiings);

        wp_send_json_success([
            'message' => esc_html__('Synchronization settings saved successfully.', 'meliconnect'),
            'data'    => $data,
        ]);
    }

    public static function saveSnapshot($module, $data)
    {
        global $wpdb;

        $table = $wpdb->prefix . 'meliconnect_settings_snapshots';

        ksort($data);

        $hash = hash('sha256', wp_json_encode($data));

        $exists = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT id FROM {$table}
                 WHERE module = %s
                 AND hash = %s
                 LIMIT 1",
                $module,
                $hash
            )
        );

        if (!$exists) {

            $wpdb->insert(
                $table,
                [
                    'module'      => $module,
                    'hash'        => $hash,
                    'description' => '',
                    'settings'    => wp_json_encode($data),
                    'is_active'   => 1,
                    'user_id'     => get_current_user_id(),
                    'plugin_version' => MELICONNECT_VERSION,
                    'created_at'  => current_time('mysql'),
                ],
                [
                    '%s', // module
                    '%s', // hash
                    '%s', // description
                    '%s', // settings ← FIX (esto era el problema típico)
                    '%d', // is_active
                    '%d', // user_id
                    '%s', // plugin_version
                    '%s', // created_at
                ]
            );

            $snapshot_id = $wpdb->insert_id;
        } else {
            $snapshot_id = $exists;
        }

        // Desactivar otros del mismo módulo
        $wpdb->query(
            $wpdb->prepare(
                "
                UPDATE {$table}
                SET is_active = 0
                WHERE module = %s
                AND hash != %s
                ",
                $module,
                $hash
            )
        );

        // activar el actual
        $wpdb->update(
            $table,
            ['is_active' => 1],
            ['id' => $snapshot_id],
            ['%d'],
            ['%d']
        );

        update_option("meliconnect_active_snapshot_id_{$module}", $snapshot_id);

        return $hash;
    }

    public static function handleSaveMlEventsSettings()
    {

        // Nonce
        if (
            ! isset($_POST['nonce']) ||
            ! wp_verify_nonce(
                sanitize_text_field(wp_unslash($_POST['nonce'])),
                'ajax_settings_nonce'
            )
        ) {
            wp_send_json_error(array('message' => 'Nonce verification failed.'));
            wp_die();
        }

        // Permisos
        if (! current_user_can('meliconnect_manage_plugin')) {
            wp_send_json_error(
                esc_html__('You do not have permission to perform this action', 'meliconnect')
            );
            wp_die();
        }

        $data = self::getSyncSettingsFromPost();

        foreach ($data as $key => $value) {
            update_option($key, $value);
        }

        $fullSyncSetiings = Helper::getMeliconnectOptions('sync');

        self::saveSnapshot('sync', $fullSyncSetiings);

        wp_send_json_success([
            'message' => 'Settings saved successfully.',
            'data' => $data
        ]);
    }

    private static function getSyncSettingsFromPost()
    {
        return array(
            'meliconnect_sync_enable_auto_sync' => (isset($_POST['meliconnect_sync_enable_auto_sync']) && $_POST['meliconnect_sync_enable_auto_sync'] === 'true') ? 'true' : 'false',

            'meliconnect_sync_on_orders' => (isset($_POST['meliconnect_sync_on_orders']) && $_POST['meliconnect_sync_on_orders'] === 'true') ? 'true' : 'false',

            'meliconnect_sync_on_product_changes' => (isset($_POST['meliconnect_sync_on_product_changes']) && $_POST['meliconnect_sync_on_product_changes'] === 'true') ? 'true' : 'false',

            'meliconnect_sync_create_product' => (isset($_POST['meliconnect_sync_create_product']) && $_POST['meliconnect_sync_create_product'] === 'true') ? 'true' : 'false',

            'meliconnect_sync_on_stock_locations' => (isset($_POST['meliconnect_sync_on_stock_locations']) && $_POST['meliconnect_sync_on_stock_locations'] === 'true') ? 'true' : 'false',

            'meliconnect_sync_on_price_changes' => (isset($_POST['meliconnect_sync_on_price_changes']) && $_POST['meliconnect_sync_on_price_changes'] === 'true') ? 'true' : 'false',
        );
    }







    /* START CUSTOM METHODS */
    public static function print_setting_checkbox($key, $label, $value = '', $check_compare_value = true, $helpText = '')
    {
        FormHelper::print_checkbox($key, $label, $value, $check_compare_value, $helpText);
    }

    public static function print_setting_select(
        $key,
        $label,
        $selected_value_key = '',
        $options = null,
        $inline_label = false
    ) {
        // Definir las opciones por defecto traducibles
        if ($options === null) {
            $options = array(
                'always'    => esc_html__('Always', 'meliconnect'),
                'on_update' => esc_html__('On Update', 'meliconnect'),
                'on_create' => esc_html__('On Create', 'meliconnect'),
            );
        }

        // Clase dinámica para controlar si el label va inline
        $wrapper_class = $inline_label
            ? 'meliconnect-columns meliconnect-is-vcentered'
            : 'meliconnect-columns';

        echo '<div class="' . esc_attr($wrapper_class) . '">';

        // Si NO es inline, mostrar label en columna separada
        if (! $inline_label) {
            echo '
            <div class="meliconnect-column meliconnect-is-4">
                <label for="' . esc_attr($key) . '" class="meliconnect-label">'
                . esc_html($label) .
                '</label>
            </div>
            <div class="meliconnect-column meliconnect-is-8">
        ';
        } else {
            // Inline: label y select en misma línea
            echo '
            <div class="meliconnect-column">
                <label for="' . esc_attr($key) . '" class="meliconnect-label" style="margin-right:10px;">'
                . esc_html($label) .
                '</label>
        ';
        }

        echo '
                <div class="meliconnect-select meliconnect-is-fullwidth">
                    <select name="' . esc_attr($key) . '" id="' . esc_attr($key) . '">';

        foreach ($options as $option_key => $option_value) {
            echo '<option value="' . esc_attr($option_key) . '" '
                . selected($selected_value_key, $option_key, false)
                . '>'
                . esc_html($option_value)
                . '</option>';
        }

        echo '
                    </select>
                </div>
            </div>
        </div>';
    }
}
