<?php
if (! defined('ABSPATH')) {
    exit;
} class PufferGo_Site_Profile
{
    public const OPTION_KEY = 'puffergo_site_profile';

    public static function default_structure()
    {
        return array('audience' => array('role' => '', 'priorities' => '', 'regions' => '', ), 'identity' => array('brand_name' => '', 'slogan' => '', 'founded' => '', 'story' => '', ), 'contact' => array('email' => '', 'phone' => '', 'address' => '', 'channels' => array(), ), 'business' => array('industry' => '', 'products' => array(), ), 'advantage' => array('certifications' => array(), 'pillars' => array(), 'pain_points' => '', 'tone' => 'Professional', ), 'trustData' => array('employees' => '', 'factoryAreaSqm' => '', 'annualCapacity' => '', 'productionLines' => '', 'passRate' => '', 'servedCountries' => '', 'servedClients' => '', 'avgResponseHours' => '', 'representativeClients' => array(), ), 'testimonials' => array(), 'assets' => array('logo_attachment_id' => 0, 'logo_url' => '', ), 'seo' => array('keywords' => array(), ), 'special_instructions' => '', 'language' => 'en', );
    }

    private static function normalize_language($locale)
    {
        if (empty($locale)) {
            return 'en';
        } $lower = strtolower($locale);

        if (0 === strpos($lower, 'en')) {
            return 'en';
        } $map = array('zh_cn' => 'zh_CN', 'zh_hk' => 'zh_HK', 'zh_tw' => 'zh_TW', );

        if (isset($map[$lower])) {
            return $map[$lower];
        } $primary = explode('_', $lower)[0];
        $allowed = array('fr', 'de', 'ja', 'ru', 'ar', 'es', 'pt', 'id', 'th', 'vi', 'ko', 'tr', 'hi', 'sw');

        if (in_array($primary, $allowed, true)) {
            return $primary;
        }

return 'en';
    }

    public function __construct()
    {
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('rest_api_init', array($this, 'register_rest_routes'));
    }

    public static function render_page()
    { ?>
		<div class="wrap">
			<div id="puffergo-site-profile-root"></div>
		</div>
		<?php
    }

    public function enqueue_scripts($hook)
    {
        if (strpos($hook, 'puffergo-site-profile') === false) {
            return;
        } $plugin_dir = plugin_dir_path(dirname(__FILE__));
        $plugin_url = plugin_dir_url(dirname(__FILE__));
        $asset_file = $plugin_dir . 'build/blocks/site-profile-app/index.asset.php';
        $script_path = 'build/blocks/site-profile-app/index.js';
        $style_path = 'build/blocks/site-profile-app/style-index.css';

        if (file_exists($asset_file)) {
            $asset = include $asset_file;
            $deps = $asset['dependencies'];
            $version = $asset['version'];
        } else {
            $deps = array('wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n');
            $version = (string) time();
        } wp_enqueue_script('puffergo-site-profile', $plugin_url . $script_path, $deps, $version, true);
        $global_tailwind = $plugin_dir . 'build/blocks/ai-admin-app/index.css';

        if (file_exists($global_tailwind)) {
            wp_enqueue_style('puffergo-admin-tailwind', $plugin_url . 'build/blocks/ai-admin-app/index.css', array(), (string) filemtime($global_tailwind));
        } $index_css = $plugin_dir . 'build/blocks/site-profile-app/index.css';

        if (file_exists($index_css)) {
            wp_enqueue_style('puffergo-site-profile-app', $plugin_url . 'build/blocks/site-profile-app/index.css', array(), (string) filemtime($index_css));
        }

if (file_exists($plugin_dir . $style_path)) {
            wp_enqueue_style('puffergo-site-profile-styles', $plugin_url . $style_path, array('puffergo-site-profile-app'), $version);
        } wp_localize_script('puffergo-site-profile', 'puffergoSiteProfile', array('restUrl' => rest_url(), 'nonce' => wp_create_nonce('wp_rest'), 'aiSiteBuilderUrl' => admin_url('admin.php?page=puffergo-ai-site-builder'), ));
        PufferGo_Workflow_Jobs_REST::add_poll_config_inline_script('puffergo-site-profile');
        wp_enqueue_style('wp-components');
        wp_enqueue_media();
    }

    public function register_rest_routes()
    {
        register_rest_route('puffergo/v1', '/site-profile', array(array('methods' => 'GET', 'callback' => array($this, 'rest_get'), 'permission_callback' => function () { return current_user_can('manage_options'); }, ), array('methods' => 'POST', 'callback' => array($this, 'rest_save'), 'permission_callback' => function () { return current_user_can('manage_options'); }, 'args' => array('siteProfile' => array('type' => 'object', 'required' => false, 'description' => __('Full site profile object (preferred POST key; avoids ModSecurity false positives on JSON key "profile").', 'puffergo'), ), 'profile' => array('type' => 'object', 'required' => false, 'description' => __('Legacy POST key for site profile object; use siteProfile instead.', 'puffergo'), ), ), ), ));
        register_rest_route('puffergo/v1', '/setup', array('methods' => 'POST', 'callback' => array($this, 'rest_setup'), 'permission_callback' => function () { return current_user_can('manage_options'); }, 'args' => array('url' => array('type' => 'string', 'required' => true, 'sanitize_callback' => 'esc_url_raw', 'validate_callback' => function ($value) {
            $url = wp_http_validate_url($value);

            if (false === $url) {
                return new WP_Error('invalid_url', __('url must be a valid http or https URL.', 'puffergo'));
            }

return true;
        }, ), 'import_sample_data' => array('type' => 'boolean', 'required' => false, 'default' => true, ), ), ));
    }

    public function rest_setup(WP_REST_Request $request)
    {
        $url = $request->get_param('url');
        $import_sample_data = (bool) $request->get_param('import_sample_data');
        $result = array('theme' => array('activated' => false, 'was_present' => false), 'urls' => array('updated' => false, 'siteurl' => '', 'home' => ''), 'sample_data' => array('imported' => false), );
        $was_present = PufferGo_Theme_Setup::is_generatepress_present();
        $result['theme']['was_present'] = $was_present;

        if (! $was_present) {
            global $puffergo_theme_setup;
            $install = $puffergo_theme_setup->install_generatepress();

            if ('installed' !== $install['status_after']) {
                $result['theme']['error'] = $install['message'];
            }
        }

if (PufferGo_Theme_Setup::is_generatepress_present()) {
            switch_theme(PufferGo_Theme_Setup::THEME_SLUG);
            $result['theme']['activated'] = (get_option('stylesheet') === PufferGo_Theme_Setup::THEME_SLUG);

            if (! $result['theme']['activated']) {
                $result['theme']['error'] = 'switch_theme did not take effect.';
            }
        } update_option('siteurl', $url);
        update_option('home', $url);
        $result['urls']['siteurl'] = get_option('siteurl');
        $result['urls']['home'] = get_option('home');
        $result['urls']['updated'] = ($result['urls']['siteurl'] === $url && $result['urls']['home'] === $url);

        if (! $result['urls']['updated']) {
            $result['urls']['error'] = 'Option did not persist after update_option.';
        }

if ($import_sample_data) {
            $already_imported = PufferGo_Sample_Data_Seeder::has_imported();
            $existing_record = $already_imported ? (array) get_option(PufferGo_Sample_Data_Seeder::OPTION_KEY, array()) : array();
            $post_ids = isset($existing_record['post_ids']) ? (array) $existing_record['post_ids'] : array();

            if (! $already_imported) {
                $seeder_result = PufferGo_Sample_Data_Seeder::import_all();
                $post_ids = $seeder_result['post_ids'];
                $result['sample_data']['counts'] = $seeder_result['counts'];
            } $homepage_id = (int) get_option('page_on_front', 0);
            $show_on_front = get_option('show_on_front', 'posts');

            if (! $homepage_id || $show_on_front !== 'page') {
                $homepage_id = PufferGo_Sample_Data_Seeder::create_showroom_homepage();

                if ($homepage_id) {
                    $post_ids[] = $homepage_id;
                    update_option('show_on_front', 'page');
                    update_option('page_on_front', $homepage_id);
                }
            } $post_ids = array_merge($post_ids, PufferGo_Sample_Data_Seeder::create_showroom_structural_pages());
            $header_menu_id = function_exists('puffergo_resolve_menu_id') ? puffergo_resolve_menu_id('puffergo_primary', 'PufferGo Header') : 0;

            if (! $header_menu_id || empty(wp_get_nav_menu_items($header_menu_id))) {
                PufferGo_Sample_Data_Seeder::sync_showroom_menu($homepage_id);
            } $footer_menu_id = function_exists('puffergo_resolve_menu_id') ? puffergo_resolve_menu_id('puffergo_footer', 'PufferGo Footer') : 0;

            if (! $footer_menu_id || empty(wp_get_nav_menu_items($footer_menu_id))) {
                PufferGo_Sample_Data_Seeder::sync_showroom_footer_menu();
            } update_option(PufferGo_Sample_Data_Seeder::OPTION_KEY, array('imported_at' => $existing_record['imported_at'] ?? current_time('mysql'), 'post_ids' => array_unique(array_filter($post_ids)), 'showroom' => true, ));
            $result['sample_data']['imported'] = true;
        }

if (! get_option(PufferGo_Design_System::OPTION_KEY)) {
            do_action('puffergo_init_design_system');
        }

return new WP_REST_Response($result, 200);
    }

    public function rest_get($request)
    {
        $stored = get_option(self::OPTION_KEY, array());

        if (! is_array($stored)) {
            $stored = array();
        } $merged = array_replace_recursive(self::default_structure(), $stored);

        if (empty($merged['language'])) {
            $merged['language'] = 'en';
        }

if (isset($merged['assets']) && is_array($merged['assets'])) {
            $merged['assets'] = self::resolve_logo_assets($merged['assets']);
        }

return new WP_REST_Response(array('profile' => $merged), 200);
    }

    public function rest_save($request)
    {
        $params = $request->get_json_params();
        $raw = $this->extract_profile_payload($params);
        $sanitized = $this->sanitize_profile($raw);
        $updated = array_merge($sanitized, array('updated_at' => current_time('c')));
        update_option(self::OPTION_KEY, $updated, false);

        return new WP_REST_Response(array('success' => true, 'profile' => $updated), 200);
    }

    private function extract_profile_payload($params)
    {
        if (! is_array($params)) {
            return array();
        }

if (isset($params['siteProfile']) && is_array($params['siteProfile'])) {
            return $params['siteProfile'];
        }

if (isset($params['profile']) && is_array($params['profile'])) {
            return $params['profile'];
        }

return array();
    }

    private function sanitize_profile($raw)
    {
        $out = array();
        $out['audience'] = array('role' => isset($raw['audience']['role']) ? sanitize_text_field(wp_unslash($raw['audience']['role'])) : '', 'priorities' => isset($raw['audience']['priorities']) ? sanitize_text_field(wp_unslash($raw['audience']['priorities'])) : '', 'regions' => isset($raw['audience']['regions']) ? sanitize_text_field(wp_unslash($raw['audience']['regions'])) : '', );
        $out['identity'] = array('brand_name' => isset($raw['identity']['brand_name']) ? sanitize_text_field(wp_unslash($raw['identity']['brand_name'])) : '', 'slogan' => isset($raw['identity']['slogan']) ? sanitize_text_field(wp_unslash($raw['identity']['slogan'])) : '', 'founded' => isset($raw['identity']['founded']) ? sanitize_text_field(wp_unslash($raw['identity']['founded'])) : '', 'story' => isset($raw['identity']['story']) ? sanitize_textarea_field(wp_unslash($raw['identity']['story'])) : '', );
        $out['contact'] = array('email' => isset($raw['contact']['email']) ? sanitize_email($raw['contact']['email']) : '', 'phone' => isset($raw['contact']['phone']) ? preg_replace('/[^0-9+]/', '', sanitize_text_field(wp_unslash($raw['contact']['phone']))) : '', 'address' => isset($raw['contact']['address']) ? sanitize_textarea_field(wp_unslash($raw['contact']['address'])) : '', 'channels' => array(), );

        if (! empty($raw['contact']['channels']) && is_array($raw['contact']['channels'])) {
            foreach ($raw['contact']['channels'] as $ch) {
                $type = isset($ch['type']) ? sanitize_text_field(wp_unslash($ch['type'])) : '';
                $value = isset($ch['value']) ? sanitize_text_field(wp_unslash($ch['value'])) : '';
                $extra = isset($ch['extra']) ? esc_url_raw(wp_unslash($ch['extra'])) : '';
                $out['contact']['channels'][] = array('type' => $type, 'value' => $value, 'extra' => $extra);
            }
        } $out['business'] = array('industry' => isset($raw['business']['industry']) ? sanitize_text_field(wp_unslash($raw['business']['industry'])) : '', 'products' => array(), );

        if (! empty($raw['business']['products']) && is_array($raw['business']['products'])) {
            foreach (array_slice($raw['business']['products'], 0, 3) as $p) {
                $out['business']['products'][] = array('name' => isset($p['name']) ? sanitize_text_field(wp_unslash($p['name'])) : (is_string($p) ? sanitize_text_field(wp_unslash($p)) : ''), );
            }
        } $pillars = array();

        if (! empty($raw['advantage']['pillars']) && is_array($raw['advantage']['pillars'])) {
            foreach ($raw['advantage']['pillars'] as $v) {
                $pillars[] = is_string($v) ? sanitize_text_field(wp_unslash($v)) : '';
            }
        } $certifications = array();

        if (! empty($raw['advantage']['certifications']) && is_array($raw['advantage']['certifications'])) {
            foreach ($raw['advantage']['certifications'] as $c) {
                if (is_string($c)) {
                    $name = sanitize_text_field(wp_unslash($c));

                    if ('' !== $name) {
                        $certifications[] = array('name' => $name, 'issuer' => '', 'scope' => '');
                    } continue;
                }

if (! is_array($c)) {
                    continue;
                } $name = isset($c['name']) ? sanitize_text_field(wp_unslash($c['name'])) : '';
                $issuer = isset($c['issuer']) ? sanitize_text_field(wp_unslash($c['issuer'])) : '';
                $scope = isset($c['scope']) ? sanitize_text_field(wp_unslash($c['scope'])) : '';

                if ('' === $name && '' === $issuer && '' === $scope) {
                    continue;
                } $certifications[] = array('name' => $name, 'issuer' => $issuer, 'scope' => $scope);
            }
        } $out['advantage'] = array('certifications' => $certifications, 'pillars' => $pillars, 'pain_points' => isset($raw['advantage']['pain_points']) ? sanitize_textarea_field(wp_unslash($raw['advantage']['pain_points'])) : '', 'tone' => isset($raw['advantage']['tone']) ? sanitize_text_field(wp_unslash($raw['advantage']['tone'])) : 'Professional', );
        $allowed_tone = array('Professional', 'Innovative', 'Caring');

        if (! in_array($out['advantage']['tone'], $allowed_tone, true)) {
            $out['advantage']['tone'] = 'Professional';
        } $td = isset($raw['trustData']) && is_array($raw['trustData']) ? $raw['trustData'] : array();
        $td_string = static function ($key) use ($td) { return isset($td[ $key ]) ? sanitize_text_field(wp_unslash((string) $td[ $key ])) : ''; };
        $rep_clients = array();

        if (! empty($td['representativeClients']) && is_array($td['representativeClients'])) {
            foreach ($td['representativeClients'] as $c) {
                if (! is_array($c)) {
                    continue;
                } $name = isset($c['name']) ? sanitize_text_field(wp_unslash($c['name'])) : '';

                if ('' === $name) {
                    continue;
                } $rep_clients[] = array('name' => $name, 'country' => isset($c['country']) ? sanitize_text_field(wp_unslash($c['country'])) : '', 'logoAsset' => isset($c['logoAsset']) ? esc_url_raw(wp_unslash($c['logoAsset'])) : '', );
            }
        } $out['trustData'] = array('employees' => $td_string('employees'), 'factoryAreaSqm' => $td_string('factoryAreaSqm'), 'annualCapacity' => $td_string('annualCapacity'), 'productionLines' => $td_string('productionLines'), 'passRate' => $td_string('passRate'), 'servedCountries' => $td_string('servedCountries'), 'servedClients' => $td_string('servedClients'), 'avgResponseHours' => $td_string('avgResponseHours'), 'representativeClients' => $rep_clients, );
        $testimonials = array();

        if (! empty($raw['testimonials']) && is_array($raw['testimonials'])) {
            foreach ($raw['testimonials'] as $t) {
                if (! is_array($t)) {
                    continue;
                } $company = isset($t['company']) ? sanitize_text_field(wp_unslash($t['company'])) : '';
                $result = isset($t['result']) ? sanitize_textarea_field(wp_unslash($t['result'])) : '';

                if ('' === $company && '' === $result) {
                    continue;
                } $testimonials[] = array('company' => $company, 'country' => isset($t['country']) ? sanitize_text_field(wp_unslash($t['country'])) : '', 'result' => $result, );
            }
        } $out['testimonials'] = $testimonials;
        $out['assets'] = self::sanitize_assets_for_save(isset($raw['assets']) && is_array($raw['assets']) ? $raw['assets'] : array());
        $keywords_arr = array();

        if (! empty($raw['seo']['keywords']) && is_array($raw['seo']['keywords'])) {
            foreach (array_slice($raw['seo']['keywords'], 0, 30) as $k) {
                $keywords_arr[] = is_string($k) ? sanitize_text_field(wp_unslash($k)) : '';
            } $keywords_arr = array_values(array_filter($keywords_arr));
        } elseif (isset($raw['seo']['keywords']) && is_string($raw['seo']['keywords'])) {
            $keywords_arr = array_values(array_filter(array_map('trim', preg_split('/[\n,]+/', $raw['seo']['keywords']))));
            $keywords_arr = array_slice(array_map('sanitize_text_field', $keywords_arr), 0, 30);
        } $out['seo'] = array('keywords' => $keywords_arr);
        $out['special_instructions'] = isset($raw['special_instructions']) && is_string($raw['special_instructions']) ? sanitize_textarea_field(wp_unslash($raw['special_instructions'])) : '';
        $out['language'] = isset($raw['language']) ? self::normalize_language($raw['language']) : 'en';

        return $out;
    }

    public static function resolve_logo_assets(array $assets)
    {
        $id = isset($assets['logo_attachment_id']) ? absint($assets['logo_attachment_id']) : 0;

        if ($id > 0 && wp_attachment_is_image($id)) {
            $url = wp_get_attachment_image_url($id, 'full');

            return array('logo_attachment_id' => $id, 'logo_url' => $url ? esc_url_raw($url) : '', );
        }

return array('logo_attachment_id' => 0, 'logo_url' => '', );
    }

    public static function sanitize_assets_for_save(array $raw_assets)
    {
        $id = isset($raw_assets['logo_attachment_id']) ? absint($raw_assets['logo_attachment_id']) : 0;

        if ($id <= 0) {
            return array('logo_attachment_id' => 0, 'logo_url' => '', );
        } $post = get_post($id);

        if (! $post || 'attachment' !== $post->post_type || ! wp_attachment_is_image($id) || ! current_user_can('edit_post', $id)) {
            return array('logo_attachment_id' => 0, 'logo_url' => '', );
        } $url = wp_get_attachment_image_url($id, 'full');

        return array('logo_attachment_id' => $id, 'logo_url' => $url ? esc_url_raw($url) : '', );
    }
} function puffergo_get_site_brand_identity()
{
    static $cached = null;

    if (null !== $cached) {
        return $cached;
    } $profile = get_option(PufferGo_Site_Profile::OPTION_KEY, array());
    $raw_assets = (isset($profile['assets']) && is_array($profile['assets'])) ? $profile['assets'] : array();
    $assets = PufferGo_Site_Profile::resolve_logo_assets($raw_assets);
    $site_name = get_bloginfo('name');
    $brand_name = ! empty($profile['identity']['brand_name']) ? $profile['identity']['brand_name'] : $site_name;
    $logo_id = (int) $assets['logo_attachment_id'];
    $logo_alt = $brand_name;

    if ($logo_id > 0) {
        $att_alt = get_post_meta($logo_id, '_wp_attachment_image_alt', true);

        if (! empty($att_alt)) {
            $logo_alt = $att_alt;
        }
    } $raw_contact = (isset($profile['contact']) && is_array($profile['contact'])) ? $profile['contact'] : array();
    $contact = array('email' => isset($raw_contact['email']) ? sanitize_email($raw_contact['email']) : '', 'phone' => isset($raw_contact['phone']) ? sanitize_text_field($raw_contact['phone']) : '', 'address' => isset($raw_contact['address']) ? sanitize_textarea_field($raw_contact['address']) : '', 'channels' => isset($raw_contact['channels']) && is_array($raw_contact['channels']) ? $raw_contact['channels'] : array(), );
    $cached = array('brand_name' => $brand_name, 'logo_url' => $assets['logo_url'], 'logo_alt' => $logo_alt, 'logo_id' => $logo_id, 'contact' => $contact, );

    return $cached;
} function puffergo_the_logo($class = 'h-8 w-auto max-w-[12rem] object-contain object-left', $extra_attrs = array())
{
    $brand = puffergo_get_site_brand_identity();
    $logo_id = $brand['logo_id'];
    $logo_url = $brand['logo_url'];
    $logo_alt = $brand['logo_alt'];
    $default_style = 'height:2.5rem;width:auto;max-width:16rem;object-fit:contain;object-position:left;';

    if ($logo_id > 0) {
        $attrs = array_merge(array('class' => $class, 'alt' => $logo_alt, 'style' => $default_style), $extra_attrs);
        echo wp_get_attachment_image($logo_id, 'full', false, $attrs);

        return true;
    }

if ('' === $logo_url) {
        $logo_url = puffergo_get_default_logo_url();
    }

if ('' !== $logo_url) {
        $merged_attrs = array_merge(array('style' => $default_style), $extra_attrs);
        $attr_parts = array('class="' . esc_attr($class) . '"');

        foreach ($merged_attrs as $k => $v) {
            $attr_parts[] = esc_attr($k) . '="' . esc_attr((string) $v) . '"';
        } echo '<img src="' . esc_url($logo_url) . '" alt="' . esc_attr($logo_alt) . '" ' . implode(' ', $attr_parts) . '>';

        return true;
    }

return false;
} function puffergo_get_default_logo_url()
{
    static $cached = null;

    if (null !== $cached) {
        return $cached;
    } $base_dir = PUFFERGO_PLUGIN_DIR . '/templates/content-templates/header/assets/';

    foreach (array('default-logo.svg', 'default-logo.png', 'default-logo.webp', 'default-logo.jpg') as $file) {
        if (file_exists($base_dir . $file)) {
            $cached = plugins_url('templates/content-templates/header/assets/' . $file, PUFFERGO_PLUGIN_FILE);

            return $cached;
        }
    } $cached = '';

    return $cached;
}
