<?php
/**
 * Access Denied Page Customizer
 *
 * Allows users to customize the access denied page through a visual interface.
 * Used when IP addresses or users are blocked by access control rules.
 *
 * @package GuardDog
 * @since 1.8.46
 */

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

class Guard_Dog_Access_Denied_Customizer extends Guard_Dog_Customizer {

    /**
     * Get unique ID for this customizer
     *
     * @return string
     */
    public function get_customizer_id() {
        return 'access_denied';
    }

    /**
     * Get title for this customizer
     *
     * @return string
     */
    public function get_customizer_title() {
        return __('Access Denied Page Customizer', 'guard-dog');
    }

    /**
     * Get description for this customizer
     *
     * @return string
     */
    public function get_customizer_description() {
        return __('Customize the appearance of the access denied page shown to blocked visitors. Changes are saved to your database and can be exported to a theme file for advanced customization.', 'guard-dog');
    }

    /**
     * Register sections and controls
     */
    protected function register_controls() {
        // ===== BRANDING SECTION =====
        $this->add_section('branding', __('Branding', 'guard-dog'), [
            'description' => __('Upload your logo and set your brand colors.', 'guard-dog'),
            'priority' => 10,
        ]);

        $this->add_control('logo', 'image', 'branding', [
            'label' => __('Logo', 'guard-dog'),
            'description' => __('Upload your company logo. Recommended size: 200x50 pixels. Leave empty to show icon only.', 'guard-dog'),
            'storage_type' => 'url',
            'default' => '',
        ]);

        $this->add_control('logo_width', 'number', 'branding', [
            'label' => __('Logo Width (px)', 'guard-dog'),
            'description' => __('Maximum width for the logo in pixels.', 'guard-dog'),
            'default' => 200,
            'input_attrs' => [
                'min' => 50,
                'max' => 600,
                'step' => 10,
            ],
        ]);

        $this->add_control('primary_color', 'color', 'branding', [
            'label' => __('Primary Color', 'guard-dog'),
            'description' => __('Main brand color used for titles and accents.', 'guard-dog'),
            'default' => '#d63638',
        ]);

        $this->add_control('background_color', 'color', 'branding', [
            'label' => __('Background Color', 'guard-dog'),
            'description' => __('Page background color.', 'guard-dog'),
            'default' => '#f0f0f1',
        ]);

        $this->add_control('text_color', 'color', 'branding', [
            'label' => __('Text Color', 'guard-dog'),
            'description' => __('Main text color for page content.', 'guard-dog'),
            'default' => '#1d2327',
        ]);

        // ===== CONTENT SECTION =====
        $this->add_section('content', __('Content', 'guard-dog'), [
            'description' => __('Customize the text content of your access denied page.', 'guard-dog'),
            'priority' => 20,
        ]);

        $this->add_control('page_title', 'text', 'content', [
            'label' => __('Page Title', 'guard-dog'),
            'description' => __('Title displayed in the browser tab.', 'guard-dog'),
            'default' => __('Access Denied', 'guard-dog'),
        ]);

        $this->add_control('heading_text', 'text', 'content', [
            'label' => __('Heading Text', 'guard-dog'),
            'description' => __('Main heading displayed on the page.', 'guard-dog'),
            'default' => __('Access Denied', 'guard-dog'),
        ]);

        $this->add_control('icon_emoji', 'text', 'content', [
            'label' => __('Icon Emoji', 'guard-dog'),
            'description' => __('Emoji icon displayed above the heading. Leave empty for no icon.', 'guard-dog'),
            'default' => '🚫',
            'placeholder' => '🚫',
        ]);

        $this->add_control('message_text', 'textarea', 'content', [
            'label' => __('Message Text', 'guard-dog'),
            'description' => __('Main message displayed to blocked visitors. HTML is allowed.', 'guard-dog'),
            'default' => __('Access to this site is currently restricted. Your IP address has been blocked due to security policies.', 'guard-dog'),
            'rows' => 4,
        ]);

        $this->add_control('show_ip_address', 'checkbox', 'content', [
            'label' => __('Show IP Address', 'guard-dog'),
            'description' => __('Display the visitor\'s IP address on the page.', 'guard-dog'),
            'default' => true,
        ]);

        $this->add_control('ip_label', 'text', 'content', [
            'label' => __('IP Address Label', 'guard-dog'),
            'description' => __('Label text shown before the IP address.', 'guard-dog'),
            'default' => __('Your IP address:', 'guard-dog'),
        ]);

        $this->add_control('footer_text', 'text', 'content', [
            'label' => __('Footer Text', 'guard-dog'),
            'description' => __('Text displayed in the page footer.', 'guard-dog'),
            'default' => __('This site is protected by Guard Dog security plugin.', 'guard-dog'),
        ]);

        // ===== LAYOUT SECTION =====
        $this->add_section('layout', __('Layout & Style', 'guard-dog'), [
            'description' => __('Configure the layout and visual style of your access denied page.', 'guard-dog'),
            'priority' => 30,
        ]);

        $this->add_control('container_background', 'color', 'layout', [
            'label' => __('Container Background', 'guard-dog'),
            'description' => __('Background color for the main content container.', 'guard-dog'),
            'default' => '#ffffff',
        ]);

        $this->add_control('border_radius', 'number', 'layout', [
            'label' => __('Border Radius (px)', 'guard-dog'),
            'description' => __('Rounded corners for the content container. Set to 0 for square corners.', 'guard-dog'),
            'default' => 8,
            'input_attrs' => [
                'min' => 0,
                'max' => 30,
                'step' => 1,
            ],
        ]);

        $this->add_control('container_max_width', 'number', 'layout', [
            'label' => __('Container Max Width (px)', 'guard-dog'),
            'description' => __('Maximum width of the content container.', 'guard-dog'),
            'default' => 500,
            'input_attrs' => [
                'min' => 300,
                'max' => 1000,
                'step' => 50,
            ],
        ]);

        $this->add_control('container_padding', 'number', 'layout', [
            'label' => __('Container Padding (px)', 'guard-dog'),
            'description' => __('Inner padding of the content container.', 'guard-dog'),
            'default' => 40,
            'input_attrs' => [
                'min' => 10,
                'max' => 80,
                'step' => 5,
            ],
        ]);
    }

    /**
     * Generate access denied page HTML output based on settings
     *
     * @param array $settings_or_args Settings array or template arguments with IP
     * @return string Generated HTML
     */
    public function generate_output($settings_or_args = []) {
        // Determine if this is preview mode (passing settings) or actual block mode (passing IP)
        $is_block_mode = isset($settings_or_args['ip_address']);

        if ($is_block_mode) {
            // Block mode: merge external args with saved settings
            $settings = $this->get_settings();
            $external_args = $settings_or_args;
        } else {
            // Preview mode: use passed settings directly (may be unsaved)
            $settings = $settings_or_args;
            $external_args = [];
        }

        // Prepare template arguments with customized values
        $template_args = array_merge([
            // Mock data for preview
            'ip_address' => '192.168.1.100',
            'reason' => 'Preview mode',
        ], $external_args, [
            // Customization settings (from passed settings or saved settings)
            'logo_url' => $settings['logo'] ?? '',
            'logo_width' => $settings['logo_width'] ?? 200,
            'primary_color' => $settings['primary_color'] ?? '#d63638',
            'background_color' => $settings['background_color'] ?? '#f0f0f1',
            'text_color' => $settings['text_color'] ?? '#1d2327',
            'page_title' => $settings['page_title'] ?? __('Access Denied', 'guard-dog'),
            'heading_text' => $settings['heading_text'] ?? __('Access Denied', 'guard-dog'),
            'icon_emoji' => $settings['icon_emoji'] ?? '🚫',
            'message_text' => $settings['message_text'] ?? __('Access to this site is currently restricted. Your IP address has been blocked due to security policies.', 'guard-dog'),
            'show_ip_address' => $settings['show_ip_address'] ?? true,
            'ip_label' => $settings['ip_label'] ?? __('Your IP address:', 'guard-dog'),
            'footer_text' => $settings['footer_text'] ?? __('This site is protected by Guard Dog security plugin.', 'guard-dog'),
            'container_background' => $settings['container_background'] ?? '#ffffff',
            'border_radius' => $settings['border_radius'] ?? 8,
            'container_max_width' => $settings['container_max_width'] ?? 500,
            'container_padding' => $settings['container_padding'] ?? 40,
        ]);

        // Generate HTML
        ob_start();
        $this->render_access_denied_page($template_args);
        return ob_get_clean();
    }

    /**
     * Render access denied page with customizations
     *
     * @param array $args Template arguments
     */
    protected function render_access_denied_page($args) {
        extract($args);
        ?>
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title><?php echo esc_html($page_title); ?></title>
            <style type="text/css">
                * {
                    margin: 0;
                    padding: 0;
                    box-sizing: border-box;
                }
                body {
                    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
                    line-height: 1.6;
                    color: <?php echo esc_attr($text_color); ?>;
                    background-color: <?php echo esc_attr($background_color); ?>;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    min-height: 100vh;
                    padding: 20px;
                }
                .access-denied-container {
                    background-color: <?php echo esc_attr($container_background); ?>;
                    max-width: <?php echo esc_attr($container_max_width); ?>px;
                    width: 100%;
                    padding: <?php echo esc_attr($container_padding); ?>px;
                    border-radius: <?php echo esc_attr($border_radius); ?>px;
                    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                    text-align: center;
                }
                .access-denied-logo {
                    margin-bottom: 30px;
                }
                .access-denied-logo img {
                    max-width: <?php echo esc_attr($logo_width); ?>px;
                    height: auto;
                }
                .access-denied-icon {
                    font-size: 64px;
                    line-height: 1;
                    margin-bottom: 20px;
                }
                .access-denied-title {
                    font-size: 32px;
                    font-weight: 600;
                    color: <?php echo esc_attr($primary_color); ?>;
                    margin-bottom: 20px;
                }
                .access-denied-message {
                    font-size: 16px;
                    margin-bottom: 25px;
                    line-height: 1.8;
                }
                .ip-info {
                    background-color: <?php echo esc_attr($background_color); ?>;
                    padding: 15px;
                    border-radius: <?php echo intval($border_radius / 2); ?>px;
                    margin-bottom: 25px;
                    font-family: "Courier New", Courier, monospace;
                    font-size: 14px;
                    color: <?php echo esc_attr($text_color); ?>;
                    opacity: 0.8;
                }
                .access-denied-footer {
                    font-size: 12px;
                    color: <?php echo esc_attr($text_color); ?>;
                    opacity: 0.6;
                    border-top: 1px solid <?php echo esc_attr($background_color); ?>;
                    padding-top: 20px;
                    margin-top: 20px;
                }
                @media (max-width: 600px) {
                    .access-denied-container {
                        padding: 30px 20px;
                    }
                    .access-denied-title {
                        font-size: 24px;
                    }
                    .access-denied-icon {
                        font-size: 48px;
                    }
                }
            </style>
        </head>
        <body>
            <div class="access-denied-container">
                <?php if (!empty($logo_url)): ?>
                    <div class="access-denied-logo">
                        <img src="<?php echo esc_url($logo_url); ?>" alt="<?php echo esc_attr(get_bloginfo('name')); ?>">
                    </div>
                <?php endif; ?>

                <?php if (!empty($icon_emoji)): ?>
                    <div class="access-denied-icon"><?php echo esc_html($icon_emoji); ?></div>
                <?php endif; ?>

                <h1 class="access-denied-title"><?php echo esc_html($heading_text); ?></h1>

                <div class="access-denied-message">
                    <?php echo wp_kses_post($message_text); ?>
                </div>

                <?php if ($show_ip_address): ?>
                    <div class="ip-info">
                        <?php echo esc_html($ip_label); ?> <strong><?php echo esc_html($ip_address); ?></strong>
                    </div>
                <?php endif; ?>

                <div class="access-denied-footer">
                    <?php echo esc_html($footer_text); ?>
                </div>
            </div>
        </body>
        </html>
        <?php
    }

    /**
     * Check if theme override exists
     *
     * @return bool
     */
    protected function has_theme_override() {
        $theme_path = get_stylesheet_directory() . '/guard-dog/access-denied.php';
        $parent_theme_path = get_template_directory() . '/guard-dog/access-denied.php';

        return file_exists($theme_path) || file_exists($parent_theme_path);
    }

    /**
     * Export settings to theme file
     *
     * @return array Result with success status and message
     */
    protected function export_to_theme() {
        // Get current settings
        $settings = $this->get_settings();

        // Prepare theme directory
        $theme_dir = get_stylesheet_directory() . '/guard-dog';

        // Check if directory exists, create if not
        if (!file_exists($theme_dir)) {
            if (!wp_mkdir_p($theme_dir)) {
                return [
                    'success' => false,
                    'message' => __('Failed to create theme directory. Please check file permissions.', 'guard-dog'),
                ];
            }
        }

        // Generate template file content
        $file_content = $this->generate_theme_template_file($settings);

        // Write file
        $file_path = $theme_dir . '/access-denied.php';

        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
        $result = file_put_contents($file_path, $file_content);

        if ($result === false) {
            return [
                'success' => false,
                'message' => __('Failed to write template file. Please check file permissions.', 'guard-dog'),
            ];
        }

        do_action('guard_dog_customizer_exported_' . $this->get_customizer_id(), $file_path, $settings);

        return [
            'success' => true,
            'message' => sprintf(
                // Translators: %s is the file path.
                __('Template exported successfully to: %s', 'guard-dog'),
                str_replace(ABSPATH, '', $file_path)
            ),
            'file_path' => $file_path,
        ];
    }

    /**
     * Generate theme template file content
     *
     * @param array $settings Customizer settings
     * @return string PHP template file content
     */
    protected function generate_theme_template_file($settings) {
        // Extract and escape settings
        $logo_url = esc_js($settings['logo'] ?? '');
        $logo_width = absint($settings['logo_width'] ?? 200);
        $primary_color = esc_js($settings['primary_color'] ?? '#d63638');
        $background_color = esc_js($settings['background_color'] ?? '#f0f0f1');
        $text_color = esc_js($settings['text_color'] ?? '#1d2327');
        $page_title = esc_js($settings['page_title'] ?? 'Access Denied');
        $heading_text = esc_js($settings['heading_text'] ?? 'Access Denied');
        $icon_emoji = esc_js($settings['icon_emoji'] ?? '🚫');
        $message_text = esc_js($settings['message_text'] ?? 'Access to this site is currently restricted. Your IP address has been blocked due to security policies.');
        $show_ip_address = isset($settings['show_ip_address']) ? (bool)$settings['show_ip_address'] : true;
        $ip_label = esc_js($settings['ip_label'] ?? 'Your IP address:');
        $footer_text = esc_js($settings['footer_text'] ?? 'This site is protected by Guard Dog security plugin.');
        $container_background = esc_js($settings['container_background'] ?? '#ffffff');
        $border_radius = absint($settings['border_radius'] ?? 8);
        $container_max_width = absint($settings['container_max_width'] ?? 500);
        $container_padding = absint($settings['container_padding'] ?? 40);

        // Build template file content as string using heredoc
        $template = <<<'TEMPLATE'
<?php
/**
 * Access Denied Page Template
 *
 * Generated by Guard Dog Access Denied Page Customizer
 * Settings can be further customized by editing this file directly.
 *
 * Available variables:
 * @var string $ip_address The IP address being blocked
 * @var string $reason The reason for blocking (optional)
 *
 * @package GuardDog
 * @since 1.8.46
 */

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

// Customization settings (from customizer)
TEMPLATE;

        // Add the settings values
        $template .= "\n\$logo_url = '" . addslashes($logo_url) . "';\n";
        $template .= "\$logo_width = " . intval($logo_width) . ";\n";
        $template .= "\$primary_color = '" . addslashes($primary_color) . "';\n";
        $template .= "\$background_color = '" . addslashes($background_color) . "';\n";
        $template .= "\$text_color = '" . addslashes($text_color) . "';\n";
        $template .= "\$page_title = '" . addslashes($page_title) . "';\n";
        $template .= "\$heading_text = '" . addslashes($heading_text) . "';\n";
        $template .= "\$icon_emoji = '" . addslashes($icon_emoji) . "';\n";
        $template .= "\$message_text = '" . addslashes($message_text) . "';\n";
        $template .= "\$show_ip_address = " . ($show_ip_address ? 'true' : 'false') . ";\n";
        $template .= "\$ip_label = '" . addslashes($ip_label) . "';\n";
        $template .= "\$footer_text = '" . addslashes($footer_text) . "';\n";
        $template .= "\$container_background = '" . addslashes($container_background) . "';\n";
        $template .= "\$border_radius = " . intval($border_radius) . ";\n";
        $template .= "\$container_max_width = " . intval($container_max_width) . ";\n";
        $template .= "\$container_padding = " . intval($container_padding) . ";\n";

        // Continue with the rest of the template
        $template .= <<<'TEMPLATE'

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo esc_html($page_title); ?></title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
            line-height: 1.6;
            color: <?php echo esc_attr($text_color); ?>;
            background-color: <?php echo esc_attr($background_color); ?>;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            padding: 20px;
        }
        .access-denied-container {
            background-color: <?php echo esc_attr($container_background); ?>;
            max-width: <?php echo esc_attr($container_max_width); ?>px;
            width: 100%;
            padding: <?php echo esc_attr($container_padding); ?>px;
            border-radius: <?php echo esc_attr($border_radius); ?>px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
        .access-denied-logo {
            margin-bottom: 30px;
        }
        .access-denied-logo img {
            max-width: <?php echo esc_attr($logo_width); ?>px;
            height: auto;
        }
        .access-denied-icon {
            font-size: 64px;
            line-height: 1;
            margin-bottom: 20px;
        }
        .access-denied-title {
            font-size: 32px;
            font-weight: 600;
            color: <?php echo esc_attr($primary_color); ?>;
            margin-bottom: 20px;
        }
        .access-denied-message {
            font-size: 16px;
            margin-bottom: 25px;
            line-height: 1.8;
        }
        .ip-info {
            background-color: <?php echo esc_attr($background_color); ?>;
            padding: 15px;
            border-radius: <?php echo intval($border_radius / 2); ?>px;
            margin-bottom: 25px;
            font-family: "Courier New", Courier, monospace;
            font-size: 14px;
            color: <?php echo esc_attr($text_color); ?>;
            opacity: 0.8;
        }
        .access-denied-footer {
            font-size: 12px;
            color: <?php echo esc_attr($text_color); ?>;
            opacity: 0.6;
            border-top: 1px solid <?php echo esc_attr($background_color); ?>;
            padding-top: 20px;
            margin-top: 20px;
        }
        @media (max-width: 600px) {
            .access-denied-container {
                padding: 30px 20px;
            }
            .access-denied-title {
                font-size: 24px;
            }
            .access-denied-icon {
                font-size: 48px;
            }
        }
    </style>
</head>
<body>
    <div class="access-denied-container">
        <?php if (!empty($logo_url)): ?>
            <div class="access-denied-logo">
                <img src="<?php echo esc_url($logo_url); ?>" alt="<?php echo esc_attr(get_bloginfo('name')); ?>">
            </div>
        <?php endif; ?>

        <?php if (!empty($icon_emoji)): ?>
            <div class="access-denied-icon"><?php echo esc_html($icon_emoji); ?></div>
        <?php endif; ?>

        <h1 class="access-denied-title"><?php echo esc_html($heading_text); ?></h1>

        <div class="access-denied-message">
            <?php echo wp_kses_post($message_text); ?>
        </div>

        <?php if ($show_ip_address && isset($ip_address)): ?>
            <div class="ip-info">
                <?php echo esc_html($ip_label); ?> <strong><?php echo esc_html($ip_address); ?></strong>
            </div>
        <?php endif; ?>

        <div class="access-denied-footer">
            <?php echo esc_html($footer_text); ?>
        </div>
    </div>
</body>
</html>
TEMPLATE;

        return $template;
    }

    /**
     * Check if current page is the customizer page
     *
     * @param string $hook Current admin page hook
     * @return bool
     */
    protected function is_customizer_page($hook) {
        return strpos($hook, 'guard-dog-access-denied-customizer') !== false;
    }

    /**
     * Render the customizer page (public method for admin menu)
     */
    public static function render_page() {
        $instance = new self();
        $instance->render();
    }
}
