<?php

namespace BookWellAB;

defined('ABSPATH') || exit;

if (!class_exists('BookWellAB_Default_Pages')) {

    class BookWellAB_Default_Pages
    {
        public const STORE_KEY = 'default_pages';

        /**
         * @return array<string, array{title: string, slug: string, content: string}>
         */
        public static function get_page_definitions()
        {
            bookwellab_load_textdomain();

            return [
                'booking' => [
                    'title' => __('Book An Appointment', 'bookwellnow-appointment-booking'),
                    'slug' => 'book-an-appointment',
                    'content' => "<!-- wp:shortcode -->\n[bookwell_booking]\n<!-- /wp:shortcode -->",
                ],
                'customer_panel' => [
                    'title' => __('My Booking', 'bookwellnow-appointment-booking'),
                    'slug' => 'my-booking',
                    'content' => "<!-- wp:shortcode -->\n[bookwellnow_customer_panel]\n<!-- /wp:shortcode -->",
                ],
            ];
        }

        /**
         * Create default frontend pages on fresh install (idempotent).
         *
         * @return void
         */
        public static function maybe_create_default_pages()
        {
            if (!function_exists('wp_insert_post')) {
                return;
            }

            $definitions = self::get_page_definitions();
            $stored = BookWellAB_Database::get_db_store_option(self::STORE_KEY, []);
            if (!is_array($stored)) {
                $stored = [];
            }

            $author_id = get_current_user_id();
            if ($author_id <= 0) {
                $author_id = 1;
            }

            foreach ($definitions as $page_key => $definition) {
                $stored_id = isset($stored[$page_key]) ? absint($stored[$page_key]) : 0;
                if ($stored_id > 0 && get_post_status($stored_id)) {
                    self::maybe_repair_page_shortcode_content(
                        $stored_id,
                        (string) ($definition['content'] ?? '')
                    );
                    continue;
                }

                $slug = sanitize_title((string) ($definition['slug'] ?? ''));
                if ($slug !== '') {
                    $existing = get_page_by_path($slug);
                    if ($existing instanceof \WP_Post) {
                        $stored[$page_key] = (int) $existing->ID;
                        self::maybe_repair_page_shortcode_content(
                            (int) $existing->ID,
                            (string) ($definition['content'] ?? '')
                        );
                        continue;
                    }
                }

                $page_id = wp_insert_post(
                    [
                        'post_title' => (string) ($definition['title'] ?? ''),
                        'post_name' => $slug,
                        'post_content' => (string) ($definition['content'] ?? ''),
                        'post_status' => 'publish',
                        'post_type' => 'page',
                        'post_author' => $author_id,
                        'comment_status' => 'closed',
                        'ping_status' => 'closed',
                    ],
                    true
                );

                if (!is_wp_error($page_id) && $page_id > 0) {
                    $stored[$page_key] = (int) $page_id;
                    self::maybe_repair_page_shortcode_content(
                        (int) $page_id,
                        (string) ($definition['content'] ?? '')
                    );
                }
            }

            BookWellAB_Database::update_db_store_option(self::STORE_KEY, $stored);

            self::maybe_seed_page_settings($stored);
        }

        /**
         * Populate general page-selection settings on first install when unset.
         *
         * @param array<string, int> $stored Stored page ID map.
         * @return void
         */
        private static function maybe_seed_page_settings(array $stored)
        {
            $bwdb = new BookWellAB_Database();
            $general = $bwdb->get_settings_by_type('general', []);
            if (!is_array($general)) {
                $general = [];
            }

            $seed_map = [
                'booking' => 'booking_form_page_id',
                'customer_panel' => 'customer_panel_page_id',
            ];

            $changed = false;
            foreach ($seed_map as $page_key => $setting_key) {
                if (!empty($general[$setting_key])) {
                    continue;
                }

                $page_id = isset($stored[$page_key]) ? absint($stored[$page_key]) : 0;
                if ($page_id <= 0) {
                    continue;
                }

                $general[$setting_key] = $page_id;
                $changed = true;
            }

            if ($changed) {
                $bwdb->update_settings_by_type('general', $general);
            }
        }

        /**
         * Repair malformed default-page shortcode content without overwriting custom content.
         *
         * @param int    $page_id            WordPress page ID.
         * @param string $expected_shortcode Expected shortcode string, e.g. [bookwellnow_customer_panel].
         * @return void
         */
        private static function maybe_repair_page_shortcode_content($page_id, $expected_content)
        {
            $page_id = absint($page_id);
            $expected_content = trim((string) $expected_content);
            if ($page_id <= 0 || $expected_content === '') {
                return;
            }

            $post = get_post($page_id);
            if (!$post instanceof \WP_Post || $post->post_type !== 'page') {
                return;
            }

            $content = trim((string) $post->post_content);
            if ($content === $expected_content) {
                return;
            }

            $expected_plain_shortcode = '';
            if (preg_match('/\[[^\]]+\]/', $expected_content, $matches)) {
                $expected_plain_shortcode = trim((string) $matches[0]);
            }
            $shortcode_name = trim($expected_plain_shortcode, '[] ');
            if ($shortcode_name === '') {
                return;
            }

            // Keep user-authored custom content intact unless it is empty or a malformed shortcode-only value.
            $repair_candidates = [
                '',
                $expected_plain_shortcode,
                '[ ' . $shortcode_name . ' ]',
                $shortcode_name,
                '[' . $shortcode_name,
                $shortcode_name . ']'
            ];

            if (!in_array($content, $repair_candidates, true)) {
                return;
            }

            wp_update_post(
                [
                    'ID' => $page_id,
                    'post_content' => $expected_content,
                ]
            );
        }

        /**
         * @param string $page_key booking|customer_panel
         * @return int
         */
        public static function get_stored_page_id($page_key)
        {
            $stored = BookWellAB_Database::get_db_store_option(self::STORE_KEY, []);
            if (!is_array($stored) || !isset($stored[$page_key])) {
                return 0;
            }

            $page_id = absint($stored[$page_key]);
            if ($page_id > 0 && get_post_type($page_id) === 'page') {
                $status = get_post_status($page_id);
                if ($status && $status !== 'trash') {
                    return $page_id;
                }
            }

            return 0;
        }

        /**
         * @param string $page_key booking|customer_panel
         * @param int    $page_id
         * @return void
         */
        public static function sync_stored_page_id($page_key, $page_id)
        {
            $page_id = absint($page_id);
            $definitions = self::get_page_definitions();
            if (!isset($definitions[$page_key])) {
                return;
            }

            $stored = BookWellAB_Database::get_db_store_option(self::STORE_KEY, []);
            if (!is_array($stored)) {
                $stored = [];
            }

            if ($page_id > 0) {
                $stored[$page_key] = $page_id;
            } elseif (isset($stored[$page_key])) {
                unset($stored[$page_key]);
            }

            BookWellAB_Database::update_db_store_option(self::STORE_KEY, $stored);
        }

        /**
         * Resolve a frontend page ID from settings, stored defaults, or slug.
         *
         * @param string $page_key booking|customer_panel
         * @return int
         */
        public static function get_resolved_page_id($page_key)
        {
            $definitions = self::get_page_definitions();
            if (!isset($definitions[$page_key])) {
                return 0;
            }

            $setting_key = $page_key === 'booking' ? 'booking_form_page_id' : 'customer_panel_page_id';
            $bwdb = new BookWellAB_Database();
            $general = $bwdb->get_settings_by_type('general', []);
            if (
                is_array($general)
                && isset($general[$setting_key])
                && is_numeric($general[$setting_key])
            ) {
                $setting_page_id = absint($general[$setting_key]);
                if ($setting_page_id > 0 && get_post_type($setting_page_id) === 'page') {
                    $status = get_post_status($setting_page_id);
                    if ($status && $status !== 'trash') {
                        return $setting_page_id;
                    }
                }
            }

            $stored_id = self::get_stored_page_id($page_key);
            if ($stored_id > 0) {
                return $stored_id;
            }

            $slug = sanitize_title((string) ($definitions[$page_key]['slug'] ?? ''));
            if ($slug === '') {
                return 0;
            }

            $page = get_page_by_path($slug);
            return $page instanceof \WP_Post ? (int) $page->ID : 0;
        }

        /**
         * @param string $page_key booking|customer_panel
         * @return string
         */
        public static function get_resolved_page_url($page_key)
        {
            $page_id = self::get_resolved_page_id($page_key);
            if ($page_id <= 0) {
                return '';
            }

            return (string) get_permalink($page_id);
        }
    }
}
