<?php

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

class AIEO_Store_CPT {

    const POST_TYPE = 'aieo_store';
    const META_KEY  = '_aieo_grv_location_id';

    private static $registered = false;

    public static function register() {
        if (self::$registered) { return; }
        self::$registered = true;
        add_action('init', array(__CLASS__, 'register_cpt'));
        if (is_admin()) {
            add_action('add_meta_boxes', array(__CLASS__, 'add_metabox'));
            add_action('save_post_' . self::POST_TYPE, array(__CLASS__, 'save_metabox'), 10, 2);
        }
    }

    
    public static function settings() {
        $opt = get_option('aieo_dmm_settings');
        $seo = (is_array($opt) && isset($opt['seo']) && is_array($opt['seo'])) ? $opt['seo'] : array();
        $base = isset($seo['store_cpt_base']) ? sanitize_title((string) $seo['store_cpt_base']) : '';
        if ('' === $base) { $base = 'stores'; } 
        $sing = (isset($seo['store_cpt_singular']) && '' !== $seo['store_cpt_singular']) ? (string) $seo['store_cpt_singular'] : __('Store', 'ai-eshop-optimizer');
        $plur = (isset($seo['store_cpt_plural']) && '' !== $seo['store_cpt_plural']) ? (string) $seo['store_cpt_plural'] : __('Stores', 'ai-eshop-optimizer');
        return array(
            'enabled' => !empty($seo['store_cpt_enabled']),
            'base'    => $base,
            'sing'    => $sing,
            'plur'    => $plur,
        );
    }

    public static function register_cpt() {
        $s = self::settings();
        if (!$s['enabled']) { return; } 

        register_post_type(self::POST_TYPE, array(
            'labels'        => array(
                'name'          => $s['plur'],
                'singular_name' => $s['sing'],
                
                'add_new_item'  => sprintf(__('Add %s', 'ai-eshop-optimizer'), $s['sing']),
                
                'edit_item'     => sprintf(__('Edit %s', 'ai-eshop-optimizer'), $s['sing']),
                'menu_name'     => $s['plur'],
            ),
            'public'        => true,
            'show_in_rest'  => true, 
            'has_archive'   => true,
            'menu_icon'     => 'dashicons-store',
            'supports'      => array('title', 'editor', 'thumbnail', 'excerpt', 'custom-fields', 'page-attributes'),
            'rewrite'       => array('slug' => $s['base'], 'with_front' => false),
        ));

        register_post_meta(self::POST_TYPE, self::META_KEY, array(
            'type'          => 'integer',
            'single'        => true,
            'show_in_rest'  => true,
            'auth_callback' => static function () { return current_user_can('edit_posts'); },
        ));

        
        
        
        if (get_option('aieo_store_cpt_flush')) {
            delete_option('aieo_store_cpt_flush');
            flush_rewrite_rules(false);
        }
    }

    

    public static function add_metabox() {
        add_meta_box(
            'aieo-store-location',
            __('Store location (Local SEO)', 'ai-eshop-optimizer'),
            array(__CLASS__, 'render_metabox'),
            self::POST_TYPE,
            'side',
            'high'
        );
    }

    public static function render_metabox($post) {
        if (!class_exists('AIEO_Google_Reviews_Locations')) {
            echo '<p>' . esc_html__('Locations & Reviews is unavailable.', 'ai-eshop-optimizer') . '</p>';
            return;
        }
        $current = (int) get_post_meta($post->ID, self::META_KEY, true);
        $locs    = AIEO_Google_Reviews_Locations::list_all(false);
        wp_nonce_field('aieo_store_loc', 'aieo_store_loc_nonce');
        echo '<p>' . esc_html__('Which location does this page represent? Its address, hours and Maps links power this page\'s LocalBusiness schema.', 'ai-eshop-optimizer') . '</p>';
        echo '<select name="aieo_grv_location_id" style="width:100%;">';
        echo '<option value="0">' . esc_html__('— none —', 'ai-eshop-optimizer') . '</option>';
        foreach ($locs as $l) {
            $label = (string) ($l['label'] ?? $l['slug'] ?? ('#' . $l['id']));
            echo '<option value="' . (int) $l['id'] . '" ' . selected($current, (int) $l['id'], false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select>';
    }

    public static function save_metabox($post_id, $post) {
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; }
        if (!isset($_POST['aieo_store_loc_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['aieo_store_loc_nonce'])), 'aieo_store_loc')) { return; }
        if (!current_user_can('edit_post', $post_id)) { return; }
        $loc_id = isset($_POST['aieo_grv_location_id']) ? (int) $_POST['aieo_grv_location_id'] : 0;
        if ($loc_id > 0) {
            update_post_meta($post_id, self::META_KEY, $loc_id);
        } else {
            delete_post_meta($post_id, self::META_KEY);
        }
    }
}
