<?php
/**
 * Zone restrictions management page — unified accordion design
 *
 * @package AfriRegions
 */

defined( 'ABSPATH' ) or die( 'Forbidden' );

class SCPWOO_Page_Restrictions {

    /** @return void */
    public function render(): void {
        $states_by_country = SCPWOO_Geo_Helper::get_states_by_country();
        $places_by_country = SCPWOO_Geo_Helper::get_merged_places_by_country();
        $wc_countries      = function_exists( 'WC' ) && WC()->countries ? WC()->countries->get_countries() : array();
        $multi_country     = count( $states_by_country ) > 1;

        $restrictions        = SCPWOO_States_Places::get_json_option( SCPWOO_States_Places::OPTION_RESTRICTED_ZONES );
        $restricted_regions  = isset( $restrictions['regions'] ) ? $restrictions['regions'] : array();
        $restricted_cities   = isset( $restrictions['cities'] ) ? $restrictions['cities'] : array();
        $restriction_message = isset( $restrictions['message'] ) ? $restrictions['message'] : __( 'Sorry, we do not deliver to this area yet.', 'afriregions-city-neighborhood-for-woocommerce' );
        $restrictions_enabled = isset( $restrictions['enabled'] ) ? $restrictions['enabled'] : 'no';
        $blocked_count = count( $restricted_regions ) + count( $restricted_cities );
        ?>
        <div id="scpwoo-restrict-wrap">

            <?php if ( $restrictions_enabled === 'yes' ) : ?>
            <div class="scpwoo-notice scpwoo-notice--warn">
                <span class="dashicons dashicons-warning"></span>
                <?php
                /* translators: %d = number of blocked zones */
                echo esc_html( sprintf( __( 'Restrictions are active — %d blocked zone(s) are hidden at checkout.', 'afriregions-city-neighborhood-for-woocommerce' ), $blocked_count ) );
                ?>
            </div>
            <?php endif; ?>

            <div class="scpwoo-row32">

                <!-- Left: zone list -->
                <div>
                    <div class="scpwoo-dash-card">
                        <div class="scpwoo-dash-card-header scpwoo-card-header-space-between">
                            <span><?php esc_html_e( 'Blocked zones', 'afriregions-city-neighborhood-for-woocommerce' ); ?></span>
                            <input type="text" id="scpwoo-rz-search" placeholder="<?php esc_attr_e( 'Search...', 'afriregions-city-neighborhood-for-woocommerce' ); ?>" aria-label="<?php esc_attr_e( 'Search zones', 'afriregions-city-neighborhood-for-woocommerce' ); ?>" />
                        </div>

                        <?php if ( $multi_country ) : ?>
                        <div class="scpwoo-country-filter" data-storage-key="scpwoo_restrictions_country" data-target=".scpwoo-rz-country-group" data-match="heading">
                            <select id="scpwoo-rz-country-select" class="scpwoo-country-select">
                                <option value=""><?php esc_html_e( 'All countries', 'afriregions-city-neighborhood-for-woocommerce' ); ?></option>
                                <?php foreach ( $states_by_country as $cc => $regs ) :
                                    $cn = isset( $wc_countries[ $cc ] ) ? $wc_countries[ $cc ] : $cc;
                                ?>
                                    <option value="<?php echo esc_attr( $cc ); ?>"><?php echo esc_html( $cn ); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php endif; ?>

                        <div class="scpwoo-rz-list">
                            <?php foreach ( $states_by_country as $country_code => $country_regions ) :
                                $country_name   = isset( $wc_countries[ $country_code ] ) ? $wc_countries[ $country_code ] : $country_code;
                                $country_places = isset( $places_by_country[ $country_code ] ) ? $places_by_country[ $country_code ] : array();
                            ?>
                                <?php if ( $multi_country ) : ?>
                                <div class="scpwoo-rz-country-group">
                                    <div class="scpwoo-rz-country-heading"><?php echo esc_html( $country_name ); ?></div>
                                <?php endif; ?>
                            <?php foreach ( $country_regions as $code => $name ) :
                                $region_key           = $country_code . ':' . $code;
                                $is_region_restricted = in_array( $region_key, $restricted_regions, true );
                                $region_cities        = isset( $country_places[ $code ] ) ? $country_places[ $code ] : array();
                                sort( $region_cities );
                                $city_count = count( $region_cities );

                                $restricted_city_count = 0;
                                foreach ( $region_cities as $city ) {
                                    if ( in_array( $region_key . '|' . $city, $restricted_cities, true ) ) {
                                        $restricted_city_count++;
                                    }
                                }
                            ?>
                            <div class="scpwoo-rz-region <?php echo $is_region_restricted ? 'scpwoo-rz-blocked' : ''; ?>" data-region="<?php echo esc_attr( $region_key ); ?>">
                                <div class="scpwoo-rz-region-header" role="button" tabindex="0" aria-expanded="false" aria-controls="scpwoo-rz-cities-<?php echo esc_attr( $country_code . '-' . $code ); ?>">
                                    <span class="scpwoo-rz-arrow dashicons dashicons-arrow-right-alt2" aria-hidden="true"></span>
                                    <label class="scpwoo-rz-region-check">
                                        <input type="checkbox" name="restricted_regions[]" value="<?php echo esc_attr( $region_key ); ?>" <?php checked( $is_region_restricted ); ?> />
                                        <strong><?php echo esc_html( $name ); ?></strong>
                                        <span class="scpwoo-rz-code">(<?php echo esc_html( $code ); ?>)</span>
                                    </label>
                                    <?php if ( $is_region_restricted ) : ?>
                                        <span class="scpwoo-badge scpwoo-badge-error"><?php esc_html_e( 'Blocked', 'afriregions-city-neighborhood-for-woocommerce' ); ?></span>
                                    <?php elseif ( $restricted_city_count > 0 ) : ?>
                                        <span class="scpwoo-badge scpwoo-badge-warning"><?php echo esc_html( $restricted_city_count . ' / ' . $city_count ); ?></span>
                                    <?php else : ?>
                                        <span class="scpwoo-badge scpwoo-badge-default"><?php echo esc_html( '0 / ' . $city_count ); ?></span>
                                    <?php endif; ?>
                                </div>
                                <?php if ( $city_count > 0 ) : ?>
                                <div class="scpwoo-rz-cities scpwoo-hidden" id="scpwoo-rz-cities-<?php echo esc_attr( $country_code . '-' . $code ); ?>">
                                    <?php if ( $is_region_restricted ) : ?>
                                        <p class="scpwoo-rz-blocked-msg"><?php esc_html_e( 'Entire region blocked', 'afriregions-city-neighborhood-for-woocommerce' ); ?></p>
                                    <?php endif; ?>
                                    <div class="scpwoo-rz-cities-grid">
                                        <?php foreach ( $region_cities as $city ) :
                                            $city_key = $region_key . '|' . $city;
                                            $is_city_restricted = in_array( $city_key, $restricted_cities, true );
                                        ?>
                                        <label class="scpwoo-rz-city" data-city="<?php echo esc_attr( mb_strtolower( $city ) ); ?>">
                                            <input type="checkbox" name="restricted_cities[]" value="<?php echo esc_attr( $city_key ); ?>" <?php checked( $is_city_restricted || $is_region_restricted ); ?> <?php disabled( $is_region_restricted ); ?> />
                                            <?php echo esc_html( $city ); ?>
                                        </label>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                                <?php if ( $multi_country ) : ?>
                                </div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </div>

                        <div class="scpwoo-rz-save-bar">
                            <button type="button" class="button button-primary" id="scpwoo-save-restrictions">
                                <?php esc_html_e( 'Save restrictions', 'afriregions-city-neighborhood-for-woocommerce' ); ?>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Right: options + stats -->
                <div class="scpwoo-col">

                    <div class="scpwoo-settings-card">
                        <div class="scpwoo-settings-card-header"><?php esc_html_e( 'Options', 'afriregions-city-neighborhood-for-woocommerce' ); ?></div>
                        <div class="scpwoo-settings-row">
                            <div class="scpwoo-settings-row-toggle">
                                <label class="scpwoo-toggle">
                                    <input type="checkbox" id="scpwoo-restrictions-enabled" value="yes" <?php checked( $restrictions_enabled, 'yes' ); ?> />
                                    <span class="scpwoo-toggle-slider"></span>
                                </label>
                            </div>
                            <label for="scpwoo-restrictions-enabled" class="scpwoo-settings-row-label"><?php esc_html_e( 'Enable restrictions', 'afriregions-city-neighborhood-for-woocommerce' ); ?></label>
                            <div class="scpwoo-settings-row-desc"><?php esc_html_e( 'Block orders from checked zones.', 'afriregions-city-neighborhood-for-woocommerce' ); ?></div>
                        </div>
                        <div class="scpwoo-settings-row">
                            <label class="scpwoo-settings-row-label"><?php esc_html_e( 'Checkout message', 'afriregions-city-neighborhood-for-woocommerce' ); ?></label>
                            <div class="scpwoo-settings-row-desc scpwoo-settings-row-wide">
                                <p class="description" style="margin-bottom:6px;color:#1d2327;"><?php esc_html_e( 'Shown to the customer at checkout when their delivery zone is blocked.', 'afriregions-city-neighborhood-for-woocommerce' ); ?></p>
                                <textarea id="scpwoo-restriction-message" rows="2" class="scpwoo-textarea" placeholder="<?php esc_attr_e( 'Sorry, we do not deliver to this area yet.', 'afriregions-city-neighborhood-for-woocommerce' ); ?>"><?php echo esc_textarea( $restriction_message ); ?></textarea>
                            </div>
                        </div>
                    </div>

                    <div class="scpwoo-dash-card">
                        <div class="scpwoo-rz-stat-body">
                            <div class="scpwoo-rz-stat-value"><?php echo esc_html( $blocked_count ); ?></div>
                            <div class="scpwoo-rz-stat-meta">
                                <?php
                                /* translators: %1$d = blocked regions, %2$d = blocked cities */
                                echo esc_html( sprintf( __( '%1$d regions · %2$d cities', 'afriregions-city-neighborhood-for-woocommerce' ), count( $restricted_regions ), count( $restricted_cities ) ) );
                                ?>
                            </div>
                        </div>
                    </div>

                </div><!-- /.scpwoo-col -->

            </div><!-- /.scpwoo-row32 -->

        </div>

        <?php
    }

    /**
     * AJAX: Save restrictions
     */
    /** @return void */
    public function ajax_save_restrictions(): void {
        check_ajax_referer( SCPWOO_States_Places::NONCE_ADMIN_WRITE, 'nonce' );

        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( array( 'message' => 'Permission denied' ) );
        }

        // Validate and whitelist region keys (format: CC:RC)
        $restricted_regions = array();
        if ( ! empty( $_POST['restricted_regions'] ) && is_array( $_POST['restricted_regions'] ) ) {
            $raw_regions = array_map( 'sanitize_text_field', wp_unslash( $_POST['restricted_regions'] ) );
            foreach ( $raw_regions as $region_key ) {
                $parsed = SCPWOO_Geo_Helper::parse_key( $region_key );
                if ( SCPWOO_Geo_Helper::is_valid_country( $parsed['country'] )
                     && SCPWOO_Geo_Helper::is_valid_region( $parsed['country'], $parsed['region'] ) ) {
                    $restricted_regions[] = $region_key;
                }
            }
        }

        // Validate and whitelist city keys (format: CC:RC|CityName)
        $restricted_cities = array();
        if ( ! empty( $_POST['restricted_cities'] ) && is_array( $_POST['restricted_cities'] ) ) {
            $raw_cities = array_map( 'sanitize_text_field', wp_unslash( $_POST['restricted_cities'] ) );
            foreach ( $raw_cities as $city_key ) {
                $pipe_pos = strpos( $city_key, '|' );
                if ( $pipe_pos === false ) {
                    continue;
                }
                $region_key = substr( $city_key, 0, $pipe_pos );
                $city_name  = substr( $city_key, $pipe_pos + 1 );
                $parsed     = SCPWOO_Geo_Helper::parse_key( $region_key );

                if ( ! SCPWOO_Geo_Helper::is_valid_country( $parsed['country'] ) ) {
                    continue;
                }
                if ( ! SCPWOO_Geo_Helper::is_valid_region( $parsed['country'], $parsed['region'] ) ) {
                    continue;
                }
                if ( ! SCPWOO_Geo_Helper::is_valid_city_in_region( $parsed['country'], $parsed['region'], $city_name ) ) {
                    continue;
                }
                $restricted_cities[] = $city_key;
            }
        }

        // Remove cities that belong to a fully restricted region (avoid redundancy)
        foreach ( $restricted_cities as $k => $city_key ) {
            $pipe_pos = strpos( $city_key, '|' );
            if ( $pipe_pos !== false ) {
                $region_key = substr( $city_key, 0, $pipe_pos );
                if ( in_array( $region_key, $restricted_regions, true ) ) {
                    unset( $restricted_cities[ $k ] );
                }
            }
        }
        $restricted_cities = array_values( $restricted_cities );

        // Sanitize and limit message length
        $message = isset( $_POST['message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['message'] ) ) : '';
        if ( mb_strlen( $message ) > SCPWOO_States_Places::MAX_LEN_MESSAGE ) {
            $message = mb_substr( $message, 0, SCPWOO_States_Places::MAX_LEN_MESSAGE );
        }

        $restrictions = array(
            'enabled'  => isset( $_POST['enabled'] ) && $_POST['enabled'] === 'yes' ? 'yes' : 'no',
            'message'  => $message,
            'regions'  => $restricted_regions,
            'cities'   => $restricted_cities,
        );

        SCPWOO_States_Places::update_json_option( SCPWOO_States_Places::OPTION_RESTRICTED_ZONES, $restrictions );

        SCPWOO_Audit::log_restrictions_saved( count( $restricted_regions ), count( $restricted_cities ) );
        wp_send_json_success( array( 'message' => __( 'Restrictions saved.', 'afriregions-city-neighborhood-for-woocommerce' ) ) );
    }
}
