<?php
defined('ABSPATH') || exit;

class PDFInvX_Settings {
    public function __construct() {
        add_action('admin_init', [$this, 'register_settings']);
        add_filter('woocommerce_email_attachments', [$this, 'attach_pdf_to_email'], 10, 4);
    }

    public function register_settings() {
        register_setting('pdfinvx_settings_group', 'pdfinvx_settings', [$this, 'sanitize_settings']);
    }

    public function render_settings_page() {
        $settings = get_option('pdfinvx_settings', []);
        ?>
        <div class="wrap woocommerce">
            <h1 class="wp-heading-inline"><?php esc_html_e('PDF InvoiceX Settings', 'pdf-invoicex'); ?></h1>
            <nav class="nav-tab-wrapper woo-nav-tab-wrapper">
                <a href="#pdfinvx-general" class="nav-tab nav-tab-active" data-tab="pdfinvx_general"><?php esc_html_e('General', 'pdf-invoicex'); ?></a>
                <a href="#pdfinvx-template" class="nav-tab" data-tab="pdfinvx_template"><?php esc_html_e('Template', 'pdf-invoicex'); ?></a>
                <a href="#pdfinvx-emails" class="nav-tab" data-tab="pdfinvx_emails"><?php esc_html_e('Emails', 'pdf-invoicex'); ?></a>
            </nav>
            <div class="pdfinvx-form-wrapper">
                <form method="post" action="options.php" class="pdfinvx-settings-form">
                    <?php settings_fields('pdfinvx_settings_group'); ?>
                    <div class="pdfinvx-form-inner">
                        <div id="pdfinvx_general" class="pdfinvx-tab-content">
                            <h2><?php esc_html_e('General Settings', 'pdf-invoicex'); ?></h2>
                            <p><?php esc_html_e('Configure general settings for your PDF invoices.', 'pdf-invoicex'); ?></p>
                            <?php
                            $this->render_logo_field($settings);
                            $this->render_address_field($settings);
                            ?>
                            <div class="pdfinvx-field-prefix-suffix-container">
                                <?php
                                $this->render_prefix_field($settings);
                                $this->render_suffix_field($settings);
                                ?>
                            </div>
                            <?php
                            $this->render_footer_field($settings);
                            ?>
                        </div>
                        <div id="pdfinvx_template" class="pdfinvx-tab-content" style="display: none;">
                            <h2><?php esc_html_e('Template Settings', 'pdf-invoicex'); ?></h2>
                            <p><?php esc_html_e('Choose the template for your PDF invoices.', 'pdf-invoicex'); ?></p>
                            <?php $this->render_template_field($settings); ?>
                        </div>
                        <div id="pdfinvx_emails" class="pdfinvx-tab-content" style="display: none;">
                            <h2><?php esc_html_e('Email Settings', 'pdf-invoicex'); ?></h2>
                            <p><?php esc_html_e('Select which emails should include a PDF invoice attachment.', 'pdf-invoicex'); ?></p>
                            <?php $this->render_emails_field($settings); ?>
                        </div>
                        <?php submit_button(__('Save Settings', 'pdf-invoicex'), 'primary pdfinvx-button', 'submit', true); ?>
                    </div>
                </form>
                <div class="pdfinvx-footer">
                    <p>Crafted with <span class="heart">❤️</span> by <a href="https://vishwas.me" target="_blank">Vishwas.R</a></p>
                </div>
            </div>
        </div>
        <?php
    }

    public function render_logo_field($settings) {
        $logo_id = !empty($settings['store_logo_id']) ? absint($settings['store_logo_id']) : 0;
        ?>
        <div class="pdfinvx-field pdfinvx-field-logo">
            <label for="pdfinvx_store_logo_id"><?php esc_html_e('Store Logo', 'pdf-invoicex'); ?></label>
            <div class="pdfinvx-field-input">
                <input type="hidden" name="pdfinvx_settings[store_logo_id]" id="pdfinvx_store_logo_id" value="<?php echo esc_attr($logo_id); ?>">
                <input type="text" id="pdfinvx_store_logo_url" value="<?php echo $logo_id ? esc_url(wp_get_attachment_url($logo_id)) : ''; ?>" readonly>
                <button type="button" class="button pdfinvx-upload-logo"><?php esc_html_e('Upload Logo', 'pdf-invoicex'); ?></button>
            </div>
            <?php if ($logo_id) : ?>
                <div class="pdfinvx-logo-preview">
                    <?php echo wp_get_attachment_image($logo_id, 'medium', false, ['alt' => esc_attr__('Logo Preview', 'pdf-invoicex')]); ?>
                </div>
            <?php endif; ?>
            <p class="description"><?php esc_html_e('Upload a logo to display on the invoice (recommended size: 200x100px).', 'pdf-invoicex'); ?></p>
        </div>
        <?php
    }

    public function render_address_field($settings) {
        $address = !empty($settings['store_address']) ? $settings['store_address'] : '';
        ?>
        <div class="pdfinvx-field pdfinvx-field-address">
            <label for="pdfinvx_store_address"><?php esc_html_e('Store Address', 'pdf-invoicex'); ?></label>
            <div class="pdfinvx-field-input">
                <textarea name="pdfinvx_settings[store_address]" id="pdfinvx_store_address" rows="5"><?php echo esc_textarea($address); ?></textarea>
            </div>
            <p class="description"><?php esc_html_e('Enter your store address as it should appear on the invoice.', 'pdf-invoicex'); ?></p>
        </div>
        <?php
    }

    public function render_prefix_field($settings) {
        $prefix = !empty($settings['invoice_prefix']) ? $settings['invoice_prefix'] : 'INV-';
        ?>
        <div class="pdfinvx-field pdfinvx-field-prefix">
            <label for="pdfinvx_invoice_prefix"><?php esc_html_e('Invoice Number Prefix', 'pdf-invoicex'); ?></label>
            <div class="pdfinvx-field-input">
                <input type="text" name="pdfinvx_settings[invoice_prefix]" id="pdfinvx_invoice_prefix" value="<?php echo esc_attr($prefix); ?>">
            </div>
            <p class="description"><?php esc_html_e('Prefix for invoice numbers (e.g., INV-).', 'pdf-invoicex'); ?></p>
        </div>
        <?php
    }

    public function render_suffix_field($settings) {
        $suffix = !empty($settings['invoice_suffix']) ? $settings['invoice_suffix'] : '';
        ?>
        <div class="pdfinvx-field pdfinvx-field-suffix">
            <label for="pdfinvx_invoice_suffix"><?php esc_html_e('Invoice Number Suffix', 'pdf-invoicex'); ?></label>
            <div class="pdfinvx-field-input">
                <input type="text" name="pdfinvx_settings[invoice_suffix]" id="pdfinvx_invoice_suffix" value="<?php echo esc_attr($suffix); ?>">
            </div>
            <p class="description"><?php esc_html_e('Suffix for invoice numbers (e.g., -2025).', 'pdf-invoicex'); ?></p>
        </div>
        <?php
    }

    public function render_footer_field($settings) {
        $footer = !empty($settings['footer_text']) ? $settings['footer_text'] : '';
        ?>
        <div class="pdfinvx-field pdfinvx-field-footer">
            <label for="pdfinvx_footer_text"><?php esc_html_e('Footer Text', 'pdf-invoicex'); ?></label>
            <div class="pdfinvx-field-input">
                <textarea name="pdfinvx_settings[footer_text]" id="pdfinvx_footer_text" rows="3"><?php echo esc_textarea($footer); ?></textarea>
            </div>
            <p class="description"><?php esc_html_e('Text to display in the invoice footer (e.g., terms or thank you message).', 'pdf-invoicex'); ?></p>
        </div>
        <?php
    }

    public function render_template_field($settings) {
        $template = !empty($settings['template']) ? $settings['template'] : 'default';
        $templates = apply_filters('pdfinvx_templates', [
            'default' => [
                'name' => __('Default Template', 'pdf-invoicex'),
                'image' => PDFINVX51_PLUGIN_URL . 'assets/images/templates/default.jpg',
                'description' => __('A clean, professional layout suitable for most businesses.', 'pdf-invoicex')
            ],
            'modern' => [
                'name' => __('Modern Template', 'pdf-invoicex'),
                'image' => PDFINVX51_PLUGIN_URL . 'assets/images/templates/modern.jpg',
                'description' => __('A contemporary design with a minimal aesthetic.', 'pdf-invoicex')
            ],
            'classic' => [
                'name' => __('Classic Template', 'pdf-invoicex'),
                'image' => PDFINVX51_PLUGIN_URL . 'assets/images/templates/classic.jpg',
                'description' => __('A traditional invoice layout with a formal appearance.', 'pdf-invoicex')
            ],
            'colorful' => [
                'name' => __('Colorful Template', 'pdf-invoicex'),
                'image' => PDFINVX51_PLUGIN_URL . 'assets/images/templates/colorful.jpg',
                'description' => __('A vibrant design that stands out with accent colors.', 'pdf-invoicex')
            ],
        ]);
        ?>
        <div class="pdfinvx-field pdfinvx-field-template">
            <label><?php esc_html_e('Invoice Template', 'pdf-invoicex'); ?></label>
            <div class="pdfinvx-templates-grid">
                <?php foreach ($templates as $key => $template_data) : ?>
                    <div class="pdfinvx-template-card<?php echo esc_attr( $template === $key ? ' pdfinvx-template-selected' : '' ); ?>" data-template="<?php echo esc_attr($key); ?>">
                        <div class="pdfinvx-template-preview">
                            <?php
                            $image_url = esc_url($template_data['image']);
                            if ($image_url && @getimagesize($image_url)) :
                            ?>
                                <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- URL is escaped with esc_url ?>
                                <?php // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage -- Static plugin asset, not an attachment ?>
                                <img src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($template_data['name']); ?>">
                            <?php else : ?>
                                <div class="pdfinvx-placeholder-image"><?php esc_html_e('Image not available', 'pdf-invoicex'); ?></div>
                            <?php endif; ?>
                            <?php if ($template === $key) : ?>
                                <div class="pdfinvx-template-selected-badge">
                                    <span class="dashicons dashicons-yes-alt"></span>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="pdfinvx-template-info">
                            <h3><?php echo esc_html($template_data['name']); ?></h3>
                            <p><?php echo esc_html($template_data['description']); ?></p>
                        </div>
                        <div class="pdfinvx-template-actions" style="display: none;">
                            <button type="button" class="button pdfinvx-preview-template" data-template="<?php echo esc_attr($key); ?>">
                                <span class="dashicons dashicons-visibility"></span> <?php esc_html_e('Preview', 'pdf-invoicex'); ?>
                            </button>
                            <label class="pdfinvx-template-select">
                                <input type="radio" name="pdfinvx_settings[template]" value="<?php echo esc_attr($key); ?>" <?php checked($template, $key); ?>>
                                <?php esc_html_e('Select', 'pdf-invoicex'); ?>
                            </label>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            <div id="pdfinvx-template-preview-modal" class="pdfinvx-modal">
                <div class="pdfinvx-modal-content">
                    <span class="pdfinvx-modal-close">&times;</span>
                    <h2 class="pdfinvx-modal-title"><?php esc_html_e('Template Preview', 'pdf-invoicex'); ?></h2>
                    <div class="pdfinvx-modal-body">
                        <?php // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage -- Static plugin asset, not an attachment ?>
                        <img id="pdfinvx-preview-image" src="" alt="<?php echo esc_attr__('Template Preview', 'pdf-invoicex'); ?>">
                    </div>
                    <div class="pdfinvx-modal-footer">
                        <button type="button" class="button button-primary pdfinvx-use-template">
                            <?php esc_html_e('Use This Template', 'pdf-invoicex'); ?>
                        </button>
                        <button type="button" class="button pdfinvx-modal-close-btn">
                            <?php esc_html_e('Close', 'pdf-invoicex'); ?>
                        </button>
                    </div>
                </div>
            </div>
            <p class="description"><?php esc_html_e('Select the invoice template that best fits your brand. Preview each option before making your selection.', 'pdf-invoicex'); ?></p>
        </div>
        <?php
    }

    public function render_emails_field($settings) {
        $emails = !empty($settings['attach_to_emails']) ? $settings['attach_to_emails'] : [];
        $wc_emails = WC()->mailer()->get_emails();
        ?>
        <div class="pdfinvx-field pdfinvx-field-emails">
            <label><?php esc_html_e('Attach to Emails', 'pdf-invoicex'); ?></label>
            <div class="pdfinvx-field-input pdfinvx-emails-container">
                <?php foreach ($wc_emails as $email) : ?>
                    <label class="pdfinvx-checkbox">
                        <input type="checkbox" name="pdfinvx_settings[attach_to_emails][]" value="<?php echo esc_attr($email->id); ?>" <?php checked(in_array($email->id, $emails, true)); ?>>
                        <span class="pdfinvx-checkbox-label"><?php echo esc_html($email->title); ?></span>
                    </label>
                <?php endforeach; ?>
            </div>
            <p class="description"><?php esc_html_e('Select WooCommerce emails to attach PDF invoices to.', 'pdf-invoicex'); ?></p>
        </div>
        <?php
    }

    public function sanitize_settings($input) {
        $sanitized = [];
        $sanitized['store_logo_id'] = absint($input['store_logo_id'] ?? 0);
        $sanitized['store_address'] = wp_kses_post($input['store_address'] ?? '');
        $sanitized['invoice_prefix'] = sanitize_text_field($input['invoice_prefix'] ?? 'INV-');
        $sanitized['invoice_suffix'] = sanitize_text_field($input['invoice_suffix'] ?? '');
        $sanitized['footer_text'] = wp_kses_post($input['footer_text'] ?? '');
        $sanitized['template'] = sanitize_key($input['template'] ?? 'default');
        $sanitized['attach_to_emails'] = array_map('sanitize_key', $input['attach_to_emails'] ?? []);
        return $sanitized;
    }

    public function attach_pdf_to_email($attachments, $email_id, $order, $email) {
        $generator = new PDFInvX_Generator();
        return $generator->attach_to_email($attachments, $email_id, $order, $email);
    }
}
?>