<?php

if (!defined('ABSPATH')) {
    exit;
}

class AIEO_DMM_Store extends AIEO_DMM_Module_Base {

    const NONCE = 'aieo_store_admin';

    public function get_id()       { return 'store_pages'; }
    public function get_label()    { return __('Store Pages', 'ai-eshop-optimizer'); }
    public function get_priority() { return 90; }                
    public function get_group()    { return 'custom_post_types'; }

    public function register_hooks() {
        add_action('wp_ajax_aieo_store_config_save', array($this, 'ajax_config_save'));
    }

    public function enqueue_admin_assets() {
        $js  = 'assets/js/aieo-store-admin.js';
        $css = 'assets/css/aieo-store-admin.css';
        $jsv  = file_exists(AIEO_DIR . $js)  ? (string) filemtime(AIEO_DIR . $js)  : (defined('AIEO_VERSION') ? AIEO_VERSION : '1.0');
        $cssv = file_exists(AIEO_DIR . $css) ? (string) filemtime(AIEO_DIR . $css) : (defined('AIEO_VERSION') ? AIEO_VERSION : '1.0');

        wp_enqueue_script('aieo-store-admin', AIEO_URI . $js, array('jquery'), $jsv, true);
        wp_enqueue_style('aieo-store-admin', AIEO_URI . $css, array(), $cssv);

        wp_localize_script('aieo-store-admin', 'aieoStore', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce(self::NONCE),
            'i18n'    => array(
                'saving' => __('Saving…', 'ai-eshop-optimizer'),
                'saved'  => __('Saved.', 'ai-eshop-optimizer'),
                'error'  => __('Something went wrong.', 'ai-eshop-optimizer'),
            ),
        ));
    }

    public function render_subtab() {
        $seo = class_exists('AIEO_DMM_Settings') ? (array) AIEO_DMM_Settings::get('seo', array()) : array();
        if (empty($seo)) {
            $opt = get_option('aieo_dmm_settings');
            $seo = (is_array($opt) && isset($opt['seo']) && is_array($opt['seo'])) ? $opt['seo'] : array();
        }

        $stores = get_posts(array(
            'post_type'   => array('store_location', 'aieo_store'),
            'post_status' => array('publish', 'draft', 'pending'),
            'numberposts' => -1,
            'orderby'     => array('menu_order' => 'ASC', 'title' => 'ASC'),
        ));

        $this->render_template('store-pages.php', array(
            'seo'     => $seo,
            'stores'  => $stores,
            'loc_map' => $this->location_label_map(),
        ));
    }

    
    private function location_label_map() {
        global $wpdb;
        $tbl = $wpdb->prefix . 'aieo_google_locations';
        $map = array();
        $exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $tbl));
        if ($exists === $tbl) {
            $rows = $wpdb->get_results("SELECT id, label FROM `{$tbl}`", ARRAY_A); 
            if (is_array($rows)) {
                foreach ($rows as $r) { $map[(int) $r['id']] = (string) $r['label']; }
            }
        }
        return $map;
    }

    

    private function guard() {
        if (!check_ajax_referer(self::NONCE, 'nonce', false)) {
            wp_send_json_error(array('message' => __('Security check failed.', 'ai-eshop-optimizer')));
        }
        $cap = defined('AIEO_CAPABILITY') ? AIEO_CAPABILITY : 'manage_woocommerce';
        if (!current_user_can($cap)) {
            wp_send_json_error(array('message' => __('You are not allowed to do this.', 'ai-eshop-optimizer')));
        }
    }

    
    public function ajax_config_save() {
        $this->guard();
        $clean = array(
            'store_cpt_enabled'  => !empty($_POST['store_cpt_enabled']),
            'store_cpt_base'     => isset($_POST['store_cpt_base']) ? sanitize_title(wp_unslash($_POST['store_cpt_base'])) : '',
            'store_cpt_singular' => isset($_POST['store_cpt_singular']) ? sanitize_text_field(wp_unslash($_POST['store_cpt_singular'])) : '',
            'store_cpt_plural'   => isset($_POST['store_cpt_plural']) ? sanitize_text_field(wp_unslash($_POST['store_cpt_plural'])) : '',
        );

        $old = class_exists('AIEO_DMM_Settings') ? (array) AIEO_DMM_Settings::get('seo', array()) : array();
        $base_changed    = ((string) ($old['store_cpt_base'] ?? '') !== (string) $clean['store_cpt_base']);
        $enabled_changed = (!empty($old['store_cpt_enabled']) !== !empty($clean['store_cpt_enabled']));

        if (class_exists('AIEO_DMM_Settings')) {
            AIEO_DMM_Settings::update(array('seo' => $clean)); 
        } else {
            $opt = get_option('aieo_dmm_settings');
            $opt = is_array($opt) ? $opt : array();
            $opt['seo'] = array_merge((isset($opt['seo']) && is_array($opt['seo'])) ? $opt['seo'] : array(), $clean);
            update_option('aieo_dmm_settings', $opt);
        }

        if ($base_changed || $enabled_changed) {
            update_option('aieo_store_cpt_flush', 1); 
        }
        wp_send_json_success(array('message' => __('Saved.', 'ai-eshop-optimizer')));
    }
}
