<?php

namespace Rtc\PlantShopWC\Admin\Controllers;

use Rtc\PlantShopWC\Admin\Models\GeneralSettingsModel;
use Rtc\PlantShopWC\Admin\Views\GeneralSettingsView;
class GeneralSettingsController {
    protected $model;

    protected $view;

    public function __construct() {
        $this->model = new GeneralSettingsModel();
        $this->view = new GeneralSettingsView();
    }

    public function registerHooks() {
        add_action( 'admin_menu', array($this, 'plantshopWcMenuPage') );
        add_action( 'admin_init', array($this, 'plantshopWcRegisterSettings') );
        add_action( 'admin_enqueue_scripts', array($this, 'plantshopWcAdminEnqueue') );
    }

    /**
     * Admin enqueue function.
     * @param $hook
     * @return void
     */
    public function plantshopWcAdminEnqueue( $hook ) : void {
        if ( !wp_script_is( 'plantshop-wc-admin-theme', 'registered' ) ) {
            wp_register_script(
                'plantshop-wc-admin-theme',
                '',
                array(),
                PLANTSHOP_WC_PLUGIN_VERSION,
                false
            );
        }
        wp_enqueue_script(
            'plantshop-wc-admin-theme',
            '',
            array('jquery'),
            PLANTSHOP_WC_PLUGIN_VERSION,
            true
        );
        wp_add_inline_script( 'plantshop-wc-admin-theme', 'document.body.dataset.theme = "light"; document.querySelector("html").dataset.theme = "light";' );
        if ( !str_contains( $hook, 'plantshop-wc' ) ) {
            return;
        }
        wp_enqueue_style(
            'plantshop-wc-admin-tw',
            PLANTSHOP_WC_PUBLIC_URL . 'admin/css/tw.css',
            array(),
            PLANTSHOP_WC_PLUGIN_VERSION
        );
        if ( str_contains( $hook, '-account' ) ) {
            wp_enqueue_style(
                'plantshop-wc-settings-admin-fs-override-css',
                PLANTSHOP_WC_PUBLIC_URL . 'admin/css/fs-override.css',
                array(),
                PLANTSHOP_WC_PLUGIN_VERSION
            );
        }
        wp_enqueue_script(
            'plantshop-wc-sweetalert2',
            PLANTSHOP_WC_PUBLIC_URL . 'vendor/js/sweetalert2.all.min.js',
            array(),
            PLANTSHOP_WC_PLUGIN_VERSION,
            true
        );
        if ( !in_array( $hook, array('toplevel_page_plantshop-wc'), true ) ) {
            return;
        }
        // Media uploader for image fields
        if ( function_exists( 'wp_enqueue_media' ) ) {
            wp_enqueue_media();
        }
        wp_enqueue_script(
            'plantshop-wc-settings.js',
            PLANTSHOP_WC_PUBLIC_URL . 'admin/js/settings.js',
            array('jquery'),
            PLANTSHOP_WC_PLUGIN_VERSION,
            true
        );
        wp_enqueue_script(
            'plantshop-wc-alpinejs',
            PLANTSHOP_WC_PUBLIC_URL . 'vendor/js/alpinejs.min.js',
            array(),
            PLANTSHOP_WC_PLUGIN_VERSION,
            true
        );
    }

    public function plantshopWcMenuPage() {
        $svg = file_get_contents( PLANTSHOP_WC_LOGO_PATH );
        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reading local plugin asset.
        $icon_data_uri = 'data:image/svg+xml;base64,' . base64_encode( $svg );
        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Required for menu icon data URI.
        add_menu_page(
            __( 'PlantShop for WooCommerce', 'plantshop-wc' ),
            __( 'PlantShop for WooCommerce', 'plantshop-wc' ),
            'manage_options',
            'plantshop-wc',
            array($this->view, 'render'),
            $icon_data_uri,
            10
        );
    }

    public function plantshopWcRegisterSettings() {
        $option_key = GeneralSettingsModel::get_option_key();
        // Uses core settings registration for now; custom option rendering can be introduced later if needed.
        register_setting( 
            'plantshop-wc_group',
            // settings group
            $option_key,
            // option name in DB
            array(
                'type'              => 'array',
                'sanitize_callback' => array($this, 'sanitizeSettingsTab'),
            )
         );
        add_settings_section(
            'plantshop-wc_main_section',
            // id
            '',
            // no heading
            '__return_false',
            // no explanatory callback needed
            'plantshop-wc'
        );
        foreach ( $this->model->get_settings() as $id => $meta ) {
            add_settings_field(
                $id,
                esc_html( $meta['label'] ),
                array($this->view, $meta['callback']),
                'plantshop-wc',
                'plantshop-wc_main_section',
                array(
                    'option_key'  => $option_key,
                    'id'          => $id,
                    'description' => $meta['description'] ?? '',
                    'class'       => $meta['class'],
                    'data'        => $meta['data'],
                )
            );
        }
    }

    public function sanitizeSettingsTab( $input ) : array {
        $input = ( is_array( $input ) ? $input : array() );
        $clean = array(
            'registration_number'             => ( isset( $input['registration_number'] ) ? sanitize_text_field( $input['registration_number'] ) : '' ),
            'disabled_cats'                   => $this->sanitizePositiveIdList( $input['disabled_cats'] ?? array() ),
            'equivalent_replacement_info_url' => ( isset( $input['equivalent_replacement_info_url'] ) ? esc_url_raw( $input['equivalent_replacement_info_url'] ) : '' ),
            'shipping_week_ranges'            => $this->sanitizeShippingWeekRanges( $input['shipping_week_ranges'] ?? '' ),
        );
        $this->copyBooleanFlagIfSet( $clean, $input, 'enable_equivalent_replacement' );
        $this->copyBooleanFlagIfSet( $clean, $input, 'botanical_name_replacement' );
        $this->copyBooleanFlagIfSet( $clean, $input, 'enable_frontend_bed_sorting' );
        $this->copyBooleanFlagIfSet( $clean, $input, 'show_frontend_bed_number' );
        $this->copyBooleanFlagIfSet( $clean, $input, 'enable_shipping_periods' );
        if ( isset( $clean['enable_shipping_periods'] ) && $clean['enable_shipping_periods'] === '1' && empty( $clean['shipping_week_ranges'] ) && function_exists( 'add_settings_error' ) ) {
            add_settings_error(
                GeneralSettingsModel::get_option_key(),
                'shipping_week_ranges_empty',
                __( 'Shipping periods are enabled, but no valid weeks are defined. Customers will not be able to select a shipping week.', 'plantshop-wc' ),
                'warning'
            );
        }
        return $clean;
    }

    private function copyBooleanFlagIfSet( array &$clean, array $input, string $key ) : void {
        if ( isset( $input[$key] ) ) {
            $clean[$key] = ( (string) $input[$key] === '1' ? '1' : '0' );
        }
    }

    private function sanitizePositiveIdList( $value ) : array {
        if ( !is_array( $value ) ) {
            return array();
        }
        $ids = array_map( 'intval', $value );
        return array_values( array_unique( array_filter( $ids, static function ( $id ) {
            return $id > 0;
        } ) ) );
    }

    private function sanitizeShippingWeekRanges( $value ) : string {
        $text = ( is_string( $value ) ? $value : '' );
        $text = str_replace( array("\r\n", "\r"), "\n", $text );
        $text = trim( $text );
        if ( $text === '' ) {
            return '';
        }
        $lines = preg_split( '/\\n+/', $text );
        $ranges = array();
        foreach ( $lines as $line ) {
            $parsed = $this->parseShippingWeekRangeLine( trim( (string) $line ) );
            if ( $parsed !== null ) {
                $ranges[] = $parsed;
            }
        }
        $ranges = array_values( array_unique( $ranges ) );
        return implode( "\n", $ranges );
    }

    private function parseShippingWeekRangeLine( string $line ) : ?string {
        if ( $line === '' ) {
            return null;
        }
        if ( !preg_match( '/^W?(\\d{1,2})(?:\\s*(?:-|\\.{2})\\s*W?(\\d{1,2}))?$/i', $line, $matches ) ) {
            return null;
        }
        $start = (int) $matches[1];
        $end = ( isset( $matches[2] ) && $matches[2] !== '' ? (int) $matches[2] : $start );
        if ( $start < 1 || $end < 1 || $start > 52 || $end > 52 || $start > $end ) {
            return null;
        }
        if ( $start === $end ) {
            return sprintf( 'W%02d', $start );
        }
        return sprintf( 'W%02d-W%02d', $start, $end );
    }

}
