<?php
if ( ! defined( 'ABSPATH' ) ) exit;
class IntegratePalace_Properties {

    protected $loader;

    protected $plugin_name;

    protected $version;
    protected $integrate_palace_dir;
    protected $integrate_palace_uri;

    public function __construct() {
        $this->plugin_name = 'integrate-palace-properties';
        $this->version = INTEGRATE_PALACE_P_VERSION;
        $this->integrate_palace_dir = INTEGRATE_PALACE_P_PLUGIN_DIR;
        $this->integrate_palace_uri = INTEGRATE_PALACE_P_PLUGIN_URI;

        $this->load_dependencies();
        $this->define_admin_hooks();
        $this->define_public_hooks();
        $this->define_admin_menu();
        $this->register_settings();
        $this->register_webhooks();
        IntegratePalace_Properties_Admin_Ajax::init();
        $this->define_palace_properties();
        $this->integrate_palace_local_fields();
        $this->define_integrate_palace_templates();
        $this->define_integrate_palace_customizer();
        $this->define_ippr_template_defaults();
    }

    private function load_dependencies() {
        require_once $this->integrate_palace_dir . 'includes/class-integratepalacep-loader.php';
        require_once $this->integrate_palace_dir . 'includes/class-integratepalacep-webhooks.php';
        require_once $this->integrate_palace_dir . 'admin/class-integratepalacep-admin.php';
        require_once $this->integrate_palace_dir . 'admin/class-integratepalacep-admin-ajax.php';
        require_once $this->integrate_palace_dir . 'admin/class-integratepalacep-dashboard.php';
        require_once $this->integrate_palace_dir . 'admin/class-integratepalacep-configs.php';
        require_once $this->integrate_palace_dir . 'admin/class-integratepalacep-templates.php';
        require_once $this->integrate_palace_dir . 'includes/class-integratepalacep-settings.php';
        require_once $this->integrate_palace_dir . 'includes/class-integratepalacep-register-properties.php';
        require_once $this->integrate_palace_dir . 'includes/class-integratepalacep-local-fields.php';
        require_once $this->integrate_palace_dir . 'includes/class-integratepalacep-templates.php';
        require_once $this->integrate_palace_dir . 'includes/class-integratepalacep-customizer.php';
        require_once $this->integrate_palace_dir . 'includes/class-integratepalacep-property-helper.php';
        if ( file_exists( $this->integrate_palace_dir . 'includes/class-integratepalacep-template-registry.php' ) ) {
            require_once $this->integrate_palace_dir . 'includes/class-integratepalacep-template-registry.php';
        }
        require_once $this->integrate_palace_dir . 'public/class-integratepalacep-svg-icons.php';
        require_once $this->integrate_palace_dir . 'public/class-integratepalacep-public.php';
        require_once $this->integrate_palace_dir . 'includes/customizer/class-integratepalacep-template-defaults.php';
        require_once $this->integrate_palace_dir . 'includes/customizer/class-integratepalacep-template-dynamic-css.php';

        // Customizer settings (new clean registration)
        require_once $this->integrate_palace_dir . 'includes/class-ipp-customizer-settings.php';

        // Developer API layer
        require_once $this->integrate_palace_dir . 'includes/class-ipp-developer-api.php';
        require_once $this->integrate_palace_dir . 'includes/class-ipp-hooks.php';
        require_once $this->integrate_palace_dir . 'includes/class-ipp-rest-api.php';
        require_once $this->integrate_palace_dir . 'includes/class-ipp-shortcodes.php';

        $this->loader = new IntegratePalace_Properties_Loader();
    }

    private function define_admin_hooks() {
        $plugin_admin = new IntegratePalace_Properties_Admin( $this->get_plugin_name(), $this->get_version() );
        $this->loader->add_filter( 'plugin_row_meta', $plugin_admin, 'integrate_palace_properties_plugin_row_meta',10,2);
        $this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_styles' );
        $this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts' );
        $this->loader->add_action( 'update_integrate_palace_gallery', $plugin_admin, 'update_integrate_palace_gallery',10,2);
    }


    private function define_public_hooks() {
        // Create instances of the classes
        $plugin_public = new IntegratePalace_Properties_Public( $this->get_plugin_name(), $this->get_version() );
        $template_dynamic_css = new IntegratePalace_Properties_Template_Dynamic_CSS();
    
        // Add actions and filters using the loader
        $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_styles' );
        $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'integrate_palace_enqueue_fonts' );
        $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_scripts' );
        
        // Custom template filter
        $this->loader->add_filter( 'template_include', $plugin_public, 'use_palace_property_template' );
        
        // Add custom dynamic CSS to the head
        $this->loader->add_action( 'wp_head', $template_dynamic_css, 'template_customization' );
    }
    

    private function define_palace_properties() { // Custom Post type
        $palace_properties = new IntegratePalace_Properties_Register_Properties();
        $this->loader->add_action( 'init', $palace_properties, 'register_palace_properties' );
    }

    private function integrate_palace_local_fields() {
        // New tabbed admin meta box (self-initializing via static init())
        // IntegratePalaceP_Local_Fields::init() is called at the bottom of the file
    }



    private function define_integrate_palace_templates() {
        $integrate_palace_templates = new IntegratePalace_Properties_Templates();
        $this->loader->add_action( 'admin_init', $integrate_palace_templates, 'register_templates' );
    }

    private function define_ippr_template_defaults() {
        $ippr_template_defaults = new IntegratePalace_Properties_Template_Defaults();
        $this->loader->add_action( 'plugins_loaded', $ippr_template_defaults, 'initialize_defaults' );
    }

    private function define_admin_menu() {
        $this->loader->add_action( 'admin_menu', $this, 'add_admin_menu' );
    }
    
    private function register_settings() {
        $this->loader->add_action( 'admin_init', 'IntegratePalace_Properties_Settings', 'init' );
        
    }

    private function define_integrate_palace_customizer() {
        $integrate_palace_customizer = new IntegratePalace_Properties_Customizer();
        $this->loader->add_action('customize_register', $integrate_palace_customizer, 'include_configurations' , 2 );
        $this->loader->add_action('customize_register', $integrate_palace_customizer, 'prepare_customizer_configs');
        $this->loader->add_action('customize_register', $integrate_palace_customizer, 'customize_register_panel' , 2 );
        $this->loader->add_action( 'customize_controls_enqueue_scripts', $integrate_palace_customizer, 'ippr_customizer_scripts' );
        $this->loader->add_action( 'customize_controls_print_styles', $integrate_palace_customizer, 'ippr_customizer_styles' );
        // $this->loader->add_action('customize_register', $integrate_palace_customizer, 'integrate_palace_register_customizer');
        // $this->loader->add_action( 'customize_controls_enqueue_scripts', $integrate_palace_customizer, 'integrate_palace_customizer_scripts' );
        // $this->loader->add_action( 'customize_controls_print_styles', $integrate_palace_customizer, 'integrate_palace_customizer_styles' );
    }

    private function register_webhooks() {
        IntegratePalace_Properties_Webhooks::init();
    }

    public function add_admin_menu() {
        add_menu_page(
            __( 'WP Palace Properties', 'integrate-palace-properties' ),
            __( 'WP Palace Properties', 'integrate-palace-properties' ),
            'manage_options',
            'integrate-palace-properties',
            array( $this, 'display_dashboard_page' ),
            'dashicons-admin-home'
        );

        add_submenu_page(
            'integrate-palace-properties',
            __( 'All Properties', 'integrate-palace-properties' ),
            __( 'All Properties', 'integrate-palace-properties' ),
            'manage_options',
            'edit.php?post_type=palace-properties'
        );

        add_submenu_page(
            'integrate-palace-properties',
            __( 'Configs', 'integrate-palace-properties' ),
            __( 'Configs', 'integrate-palace-properties' ),
            'manage_options',
            'integrate-palace-properties-configs',
            array( $this, 'display_configs_page' )
        );

        add_submenu_page(
            'integrate-palace-properties',
            __( 'Appearance', 'integrate-palace-properties' ),
            __( 'Appearance', 'integrate-palace-properties' ),
            'manage_options',
            'customize.php?autofocus[panel]=ipp_panel&url=' . urlencode( get_post_type_archive_link( 'palace-properties' ) ),
            null
        );        

        add_submenu_page(
            'integrate-palace-properties',
            __( 'Templates', 'integrate-palace-properties' ),
            __( 'Templates', 'integrate-palace-properties' ),
            'manage_options',
            'palace-property_templates',
            array( $this, 'display_templates' )
        );

        add_submenu_page(
            'integrate-palace-properties',
            __( 'Developer Docs', 'integrate-palace-properties' ),
            __( 'Developer Docs', 'integrate-palace-properties' ),
            'manage_options',
            'ipp-developer-docs',
            array( $this, 'display_developer_docs' )
        );

    }

    public function display_dashboard_page() {
        require_once $this->integrate_palace_dir . 'admin/class-integratepalacep-dashboard.php';
        $dashboard = new IntegratePalace_Properties_Dashboard();
        $dashboard->display();
    }

    public function display_configs_page() {
        require_once $this->integrate_palace_dir . 'admin/class-integratepalacep-configs.php';
        $configs = new IntegratePalace_Properties_Configs();
        $configs->display();
    }

    public function display_templates() {
        require_once $this->integrate_palace_dir . 'admin/class-integratepalacep-templates.php';
        $configs = new IntegratePalace_Properties_Templates_Display();
        $configs->display();
    }

    public function display_developer_docs() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Permission denied.', 'integrate-palace-properties' ) );
        }

        $md_file = $this->integrate_palace_dir . 'DEVELOPERS.md';
        $content = file_exists( $md_file ) ? file_get_contents( $md_file ) : '';

        echo '<div class="wrap" style="max-width:960px;">';
        echo '<h1 style="display:flex;align-items:center;gap:10px;">';
        echo '<span class="dashicons dashicons-editor-code" style="font-size:28px;width:28px;height:28px;"></span>';
        echo esc_html__( 'Developer Documentation', 'integrate-palace-properties' );
        echo '</h1>';
        echo '<p style="color:#646970;margin-bottom:24px;">';
        echo esc_html__( 'Complete reference for theme and plugin developers. Also available at ', 'integrate-palace-properties' );
        echo '<code>' . esc_html( str_replace( ABSPATH, '', $md_file ) ) . '</code>';
        echo '</p>';

        echo '<style>
            .ipp-docs { background:#fff; border:1px solid #c3c4c7; border-radius:4px; padding:32px 40px; font-size:14px; line-height:1.8; color:#1d2327; }
            .ipp-docs h1 { font-size:24px; font-weight:700; margin:32px 0 16px; padding-bottom:8px; border-bottom:2px solid #2271b1; color:#1d2327; }
            .ipp-docs h1:first-child { margin-top:0; }
            .ipp-docs h2 { font-size:20px; font-weight:600; margin:28px 0 12px; color:#1d2327; }
            .ipp-docs h3 { font-size:16px; font-weight:600; margin:24px 0 8px; color:#1d2327; }
            .ipp-docs h4 { font-size:14px; font-weight:600; margin:20px 0 8px; color:#1d2327; }
            .ipp-docs p { margin:0 0 12px; }
            .ipp-docs code { background:#f0f0f1; padding:2px 6px; border-radius:3px; font-size:13px; font-family:"SF Mono","Fira Code",monospace; color:#1d2327; }
            .ipp-docs pre { background:#1d2327; color:#e0e0e0; padding:16px 20px; border-radius:6px; overflow-x:auto; margin:12px 0 16px; line-height:1.5; }
            .ipp-docs pre code { background:none; padding:0; color:inherit; font-size:13px; }
            .ipp-docs ul, .ipp-docs ol { margin:8px 0 16px 24px; }
            .ipp-docs li { margin-bottom:4px; }
            .ipp-docs table { width:100%; border-collapse:collapse; margin:12px 0 16px; }
            .ipp-docs th, .ipp-docs td { padding:8px 12px; border:1px solid #c3c4c7; text-align:left; font-size:13px; }
            .ipp-docs th { background:#f0f0f1; font-weight:600; }
            .ipp-docs hr { border:none; border-top:1px solid #c3c4c7; margin:24px 0; }
            .ipp-docs blockquote { border-left:4px solid #2271b1; margin:12px 0; padding:8px 16px; background:#f0f6fc; color:#1d2327; }
            .ipp-docs a { color:#2271b1; }
        </style>';

        echo '<div class="ipp-docs">';
        echo wp_kses_post( self::render_markdown( $content ) );
        echo '</div>';
        echo '</div>';
    }

    /**
     * Simple Markdown to HTML converter for developer docs.
     */
    private static function render_markdown( $md ) {
        // Code blocks (``` ... ```)
        $md = preg_replace_callback( '/```(\w*)\n(.*?)```/s', function ( $m ) {
            $lang = $m[1] ? ' data-lang="' . esc_attr( $m[1] ) . '"' : '';
            return '<pre' . $lang . '><code>' . esc_html( $m[2] ) . '</code></pre>';
        }, $md );

        // Inline code
        $md = preg_replace( '/`([^`]+)`/', '<code>$1</code>', $md );

        // Headings
        $md = preg_replace( '/^#### (.+)$/m', '<h4>$1</h4>', $md );
        $md = preg_replace( '/^### (.+)$/m', '<h3>$1</h3>', $md );
        $md = preg_replace( '/^## (.+)$/m', '<h2>$1</h2>', $md );
        $md = preg_replace( '/^# (.+)$/m', '<h1>$1</h1>', $md );

        // HR
        $md = preg_replace( '/^---+$/m', '<hr>', $md );

        // Bold / Italic
        $md = preg_replace( '/\*\*(.+?)\*\*/', '<strong>$1</strong>', $md );
        $md = preg_replace( '/\*(.+?)\*/', '<em>$1</em>', $md );

        // Links
        $md = preg_replace( '/\[([^\]]+)\]\(([^)]+)\)/', '<a href="$2">$1</a>', $md );

        // Tables
        $md = preg_replace_callback( '/^\|(.+)\|\n\|[-| :]+\|\n((?:\|.+\|\n?)+)/m', function ( $m ) {
            $headers = array_map( 'trim', explode( '|', trim( $m[1], '|' ) ) );
            $rows_raw = trim( $m[2] );
            $html = '<table><thead><tr>';
            foreach ( $headers as $h ) {
                $html .= '<th>' . $h . '</th>';
            }
            $html .= '</tr></thead><tbody>';
            foreach ( explode( "\n", $rows_raw ) as $row ) {
                $cells = array_map( 'trim', explode( '|', trim( $row, '|' ) ) );
                $html .= '<tr>';
                foreach ( $cells as $c ) {
                    $html .= '<td>' . $c . '</td>';
                }
                $html .= '</tr>';
            }
            $html .= '</tbody></table>';
            return $html;
        }, $md );

        // Unordered lists
        $md = preg_replace_callback( '/(?:^- .+\n?)+/m', function ( $m ) {
            $items = preg_split( '/^- /m', $m[0], -1, PREG_SPLIT_NO_EMPTY );
            $html = '<ul>';
            foreach ( $items as $item ) {
                $html .= '<li>' . trim( $item ) . '</li>';
            }
            $html .= '</ul>';
            return $html;
        }, $md );

        // Ordered lists
        $md = preg_replace_callback( '/(?:^\d+\. .+\n?)+/m', function ( $m ) {
            $items = preg_split( '/^\d+\. /m', $m[0], -1, PREG_SPLIT_NO_EMPTY );
            $html = '<ol>';
            foreach ( $items as $item ) {
                $html .= '<li>' . trim( $item ) . '</li>';
            }
            $html .= '</ol>';
            return $html;
        }, $md );

        // Blockquotes
        $md = preg_replace_callback( '/(?:^> .+\n?)+/m', function ( $m ) {
            $text = preg_replace( '/^> /m', '', $m[0] );
            return '<blockquote>' . trim( $text ) . '</blockquote>';
        }, $md );

        // Paragraphs (lines not already wrapped in HTML)
        $lines = explode( "\n", $md );
        $result = '';
        $in_block = false;
        foreach ( $lines as $line ) {
            $trimmed = trim( $line );
            if ( preg_match( '/^<(h[1-4]|pre|ul|ol|table|hr|blockquote|div|p)/', $trimmed ) ) {
                $in_block = true;
            }
            if ( $in_block ) {
                $result .= $line . "\n";
                if ( preg_match( '/<\/(h[1-4]|pre|ul|ol|table|blockquote|div|p)>/', $trimmed ) || $trimmed === '<hr>' ) {
                    $in_block = false;
                }
            } elseif ( $trimmed === '' ) {
                $result .= "\n";
            } else {
                $result .= '<p>' . $trimmed . '</p>' . "\n";
            }
        }

        return $result;
    }

    public function run() {
        $this->loader->run();
    }

    public function get_plugin_name() {
        return $this->plugin_name;
    }

    public function get_version() {
        return $this->version;
    }
}
