<?php

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

class WPDD_Settings {
    
    public static function init() {
        add_action('admin_menu', array(__CLASS__, 'add_settings_page'));
        add_action('admin_init', array(__CLASS__, 'register_settings'));
    }
    
    public static function add_settings_page() {
        add_submenu_page(
            'edit.php?post_type=wpdd_product',
            __('Settings', 'wp-digital-download'),
            __('Settings', 'wp-digital-download'),
            'wpdd_manage_settings',
            'wpdd-settings',
            array(__CLASS__, 'render_settings_page')
        );
    }
    
    public static function register_settings() {
        register_setting('wpdd_settings', 'wpdd_paypal_mode');
        register_setting('wpdd_settings', 'wpdd_paypal_client_id');
        register_setting('wpdd_settings', 'wpdd_paypal_secret');
        register_setting('wpdd_settings', 'wpdd_admin_email');
        register_setting('wpdd_settings', 'wpdd_from_name');
        register_setting('wpdd_settings', 'wpdd_from_email');
        register_setting('wpdd_settings', 'wpdd_currency');
        register_setting('wpdd_settings', 'wpdd_enable_guest_checkout');
        register_setting('wpdd_settings', 'wpdd_default_download_limit');
        register_setting('wpdd_settings', 'wpdd_default_download_expiry');
        register_setting('wpdd_settings', 'wpdd_enable_watermark');
        register_setting('wpdd_settings', 'wpdd_watermark_text');
        register_setting('wpdd_settings', 'wpdd_terms_page');
        register_setting('wpdd_settings', 'wpdd_privacy_page');
        register_setting('wpdd_settings', 'wpdd_commission_rate', array(
            'sanitize_callback' => array(__CLASS__, 'sanitize_commission_rate')
        ));
        register_setting('wpdd_settings', 'wpdd_payout_threshold', array(
            'sanitize_callback' => array(__CLASS__, 'sanitize_payout_threshold')
        ));
        register_setting('wpdd_settings', 'wpdd_file_access_method');
        register_setting('wpdd_settings', 'wpdd_disable_admin_bar');
        
        add_settings_section(
            'wpdd_general_settings',
            __('General Settings', 'wp-digital-download'),
            array(__CLASS__, 'general_section_callback'),
            'wpdd_settings'
        );
        
        add_settings_section(
            'wpdd_paypal_settings',
            __('PayPal Settings', 'wp-digital-download'),
            array(__CLASS__, 'paypal_section_callback'),
            'wpdd_settings'
        );
        
        add_settings_section(
            'wpdd_email_settings',
            __('Email Settings', 'wp-digital-download'),
            array(__CLASS__, 'email_section_callback'),
            'wpdd_settings'
        );
        
        add_settings_section(
            'wpdd_download_settings',
            __('Download Settings', 'wp-digital-download'),
            array(__CLASS__, 'download_section_callback'),
            'wpdd_settings'
        );
        
        add_settings_section(
            'wpdd_watermark_settings',
            __('Watermark Settings', 'wp-digital-download'),
            array(__CLASS__, 'watermark_section_callback'),
            'wpdd_settings'
        );
        
        self::add_general_fields();
        self::add_paypal_fields();
        self::add_email_fields();
        self::add_download_fields();
        self::add_watermark_fields();
    }
    
    private static function add_general_fields() {
        add_settings_field(
            'wpdd_currency',
            __('Currency', 'wp-digital-download'),
            array(__CLASS__, 'currency_field'),
            'wpdd_settings',
            'wpdd_general_settings',
            array(
                'name' => 'wpdd_currency'
            )
        );
        
        add_settings_field(
            'wpdd_enable_guest_checkout',
            __('Guest Checkout', 'wp-digital-download'),
            array(__CLASS__, 'checkbox_field'),
            'wpdd_settings',
            'wpdd_general_settings',
            array(
                'name' => 'wpdd_enable_guest_checkout',
                'label' => __('Allow guest customers to purchase without creating an account', 'wp-digital-download')
            )
        );
        
        add_settings_field(
            'wpdd_commission_rate',
            __('Platform Commission Rate (%)', 'wp-digital-download'),
            array(__CLASS__, 'number_field'),
            'wpdd_settings',
            'wpdd_general_settings',
            array(
                'name' => 'wpdd_commission_rate',
                'description' => __('Platform commission rate from sales (0-100). Creators receive the remainder.', 'wp-digital-download'),
                'min' => 0,
                'max' => 100,
                'step' => 0.01
            )
        );
        
        add_settings_field(
            'wpdd_payout_threshold',
            __('Automatic Payout Threshold ($)', 'wp-digital-download'),
            array(__CLASS__, 'number_field'),
            'wpdd_settings',
            'wpdd_general_settings',
            array(
                'name' => 'wpdd_payout_threshold',
                'description' => __('Minimum balance for automatic payouts (0 to disable)', 'wp-digital-download'),
                'min' => 0,
                'step' => 0.01
            )
        );
        
        add_settings_field(
            'wpdd_terms_page',
            __('Terms & Conditions Page', 'wp-digital-download'),
            array(__CLASS__, 'page_dropdown_field'),
            'wpdd_settings',
            'wpdd_general_settings',
            array('name' => 'wpdd_terms_page')
        );
        
        add_settings_field(
            'wpdd_privacy_page',
            __('Privacy Policy Page', 'wp-digital-download'),
            array(__CLASS__, 'page_dropdown_field'),
            'wpdd_settings',
            'wpdd_general_settings',
            array('name' => 'wpdd_privacy_page')
        );
    }
    
    private static function add_paypal_fields() {
        add_settings_field(
            'wpdd_paypal_mode',
            __('PayPal Mode', 'wp-digital-download'),
            array(__CLASS__, 'select_field'),
            'wpdd_settings',
            'wpdd_paypal_settings',
            array(
                'name' => 'wpdd_paypal_mode',
                'options' => array(
                    'sandbox' => __('Sandbox (Testing)', 'wp-digital-download'),
                    'live' => __('Live (Production)', 'wp-digital-download')
                )
            )
        );
        
        add_settings_field(
            'wpdd_paypal_client_id',
            __('PayPal Client ID', 'wp-digital-download'),
            array(__CLASS__, 'text_field'),
            'wpdd_settings',
            'wpdd_paypal_settings',
            array('name' => 'wpdd_paypal_client_id')
        );
        
        add_settings_field(
            'wpdd_paypal_secret',
            __('PayPal Secret', 'wp-digital-download'),
            array(__CLASS__, 'password_field'),
            'wpdd_settings',
            'wpdd_paypal_settings',
            array('name' => 'wpdd_paypal_secret')
        );
    }
    
    private static function add_email_fields() {
        add_settings_field(
            'wpdd_admin_email',
            __('Admin Email', 'wp-digital-download'),
            array(__CLASS__, 'email_field'),
            'wpdd_settings',
            'wpdd_email_settings',
            array(
                'name' => 'wpdd_admin_email',
                'description' => __('Email address for admin notifications', 'wp-digital-download')
            )
        );
        
        add_settings_field(
            'wpdd_from_name',
            __('From Name', 'wp-digital-download'),
            array(__CLASS__, 'text_field'),
            'wpdd_settings',
            'wpdd_email_settings',
            array(
                'name' => 'wpdd_from_name',
                'description' => __('Name shown in email headers', 'wp-digital-download')
            )
        );
        
        add_settings_field(
            'wpdd_from_email',
            __('From Email', 'wp-digital-download'),
            array(__CLASS__, 'email_field'),
            'wpdd_settings',
            'wpdd_email_settings',
            array(
                'name' => 'wpdd_from_email',
                'description' => __('Email address shown in email headers', 'wp-digital-download')
            )
        );
    }
    
    private static function add_download_fields() {
        add_settings_field(
            'wpdd_default_download_limit',
            __('Default Download Limit', 'wp-digital-download'),
            array(__CLASS__, 'number_field'),
            'wpdd_settings',
            'wpdd_download_settings',
            array(
                'name' => 'wpdd_default_download_limit',
                'description' => __('Default number of downloads allowed per purchase (0 = unlimited)', 'wp-digital-download'),
                'min' => 0
            )
        );
        
        add_settings_field(
            'wpdd_default_download_expiry',
            __('Default Download Expiry (days)', 'wp-digital-download'),
            array(__CLASS__, 'number_field'),
            'wpdd_settings',
            'wpdd_download_settings',
            array(
                'name' => 'wpdd_default_download_expiry',
                'description' => __('Default number of days downloads remain available (0 = never expires)', 'wp-digital-download'),
                'min' => 0
            )
        );
        
        add_settings_field(
            'wpdd_file_access_method',
            __('File Access Method', 'wp-digital-download'),
            array(__CLASS__, 'select_field'),
            'wpdd_settings',
            'wpdd_download_settings',
            array(
                'name' => 'wpdd_file_access_method',
                'options' => array(
                    'direct' => __('Direct Download', 'wp-digital-download'),
                    'redirect' => __('Redirect to File', 'wp-digital-download'),
                    'force' => __('Force Download', 'wp-digital-download')
                ),
                'description' => __('How files are delivered to customers', 'wp-digital-download')
            )
        );
    }
    
    private static function add_watermark_fields() {
        add_settings_field(
            'wpdd_enable_watermark',
            __('Enable Watermarking', 'wp-digital-download'),
            array(__CLASS__, 'checkbox_field'),
            'wpdd_settings',
            'wpdd_watermark_settings',
            array(
                'name' => 'wpdd_enable_watermark',
                'label' => __('Enable watermarking for images and PDFs by default', 'wp-digital-download')
            )
        );
        
        add_settings_field(
            'wpdd_watermark_text',
            __('Default Watermark Text', 'wp-digital-download'),
            array(__CLASS__, 'text_field'),
            'wpdd_settings',
            'wpdd_watermark_settings',
            array(
                'name' => 'wpdd_watermark_text',
                'description' => __('Available placeholders: {customer_name}, {customer_email}, {order_id}, {date}, {site_name}', 'wp-digital-download')
            )
        );
    }
    
    public static function render_settings_page() {
        ?>
        <div class="wrap">
            <h1><?php _e('WP Digital Download Settings', 'wp-digital-download'); ?></h1>
            
            <div class="wpdd-settings-sidebar">
                <div class="wpdd-settings-box">
                    <h3><?php _e('Quick Setup', 'wp-digital-download'); ?></h3>
                    <p><?php _e('To get started quickly:', 'wp-digital-download'); ?></p>
                    <ol>
                        <li><?php _e('Configure PayPal settings above', 'wp-digital-download'); ?></li>
                        <li><?php _e('Create your first product', 'wp-digital-download'); ?></li>
                        <li><?php _e('Add the shop shortcode [wpdd_shop] to a page', 'wp-digital-download'); ?></li>
                        <li><?php _e('Test with a free product first', 'wp-digital-download'); ?></li>
                    </ol>
                </div>
                
                <div class="wpdd-settings-box">
                    <h3><?php _e('Available Shortcodes', 'wp-digital-download'); ?></h3>
                    <ul>
                        <li><code>[wpdd_shop]</code> - <?php _e('Display product storefront', 'wp-digital-download'); ?></li>
                        <li><code>[wpdd_customer_purchases]</code> - <?php _e('Customer purchase history', 'wp-digital-download'); ?></li>
                        <li><code>[wpdd_checkout]</code> - <?php _e('Checkout page', 'wp-digital-download'); ?></li>
                        <li><code>[wpdd_thank_you]</code> - <?php _e('Thank you page', 'wp-digital-download'); ?></li>
                        <li><code>[wpdd_product id="123"]</code> - <?php _e('Single product display', 'wp-digital-download'); ?></li>
                    </ul>
                </div>
                
                <div class="wpdd-settings-box">
                    <h3><?php _e('System Status', 'wp-digital-download'); ?></h3>
                    <?php self::system_status(); ?>
                </div>
            </div>
            
            <form method="post" action="options.php" class="wpdd-settings-form">
                <?php
                settings_fields('wpdd_settings');
                do_settings_sections('wpdd_settings');
                submit_button();
                ?>
            </form>
        </div>
        
        <style>
            .wpdd-settings-sidebar {
                float: right;
                width: 300px;
                margin-left: 20px;
                position: relative;
                z-index: 10;
            }
            .wpdd-settings-form {
                overflow: hidden;
                margin-right: 340px;
            }
            .wpdd-settings-box {
                background: white;
                border: 1px solid #ccd0d4;
                padding: 20px;
                margin-bottom: 20px;
                box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            }
            .wpdd-settings-box h3 {
                margin-top: 0;
            }
            .wpdd-settings-box code {
                background: #f1f1f1;
                padding: 2px 5px;
                font-size: 12px;
            }
            .wpdd-status-good { color: #46b450; }
            .wpdd-status-warning { color: #ffb900; }
            .wpdd-status-error { color: #dc3232; }
            @media (max-width: 1200px) {
                .wpdd-settings-sidebar {
                    float: none;
                    width: 100%;
                    margin-left: 0;
                    margin-top: 30px;
                }
                .wpdd-settings-form {
                    margin-right: 0;
                }
            }
        </style>
        <?php
    }
    
    public static function general_section_callback() {
        echo '<p>' . __('Configure basic plugin settings.', 'wp-digital-download') . '</p>';
    }
    
    public static function paypal_section_callback() {
        echo '<p>' . __('Configure PayPal payment settings. You can get your API credentials from the PayPal Developer Dashboard.', 'wp-digital-download') . '</p>';
    }
    
    public static function email_section_callback() {
        echo '<p>' . __('Configure email settings for purchase notifications.', 'wp-digital-download') . '</p>';
    }
    
    public static function download_section_callback() {
        echo '<p>' . __('Configure default download and file protection settings.', 'wp-digital-download') . '</p>';
    }
    
    public static function watermark_section_callback() {
        echo '<p>' . __('Configure watermarking settings for images and PDF files.', 'wp-digital-download') . '</p>';
    }
    
    public static function text_field($args) {
        $name = $args['name'] ?? '';
        $value = get_option($name, '');
        $description = isset($args['description']) ? $args['description'] : '';
        
        if (empty($name)) {
            echo '<p>Error: Field name not provided</p>';
            return;
        }
        
        printf(
            '<input type="text" id="%s" name="%s" value="%s" class="regular-text" />',
            esc_attr($name),
            esc_attr($name),
            esc_attr($value)
        );
        
        if ($description) {
            printf('<p class="description">%s</p>', esc_html($description));
        }
    }
    
    public static function password_field($args) {
        $name = $args['name'] ?? '';
        $value = get_option($name, '');
        $description = isset($args['description']) ? $args['description'] : '';
        
        if (empty($name)) {
            echo '<p>Error: Field name not provided</p>';
            return;
        }
        
        printf(
            '<input type="password" id="%s" name="%s" value="%s" class="regular-text" />',
            esc_attr($name),
            esc_attr($name),
            esc_attr($value)
        );
        
        if ($description) {
            printf('<p class="description">%s</p>', esc_html($description));
        }
    }
    
    public static function email_field($args) {
        $name = $args['name'] ?? '';
        $value = get_option($name, '');
        $description = isset($args['description']) ? $args['description'] : '';
        
        if (empty($name)) {
            echo '<p>Error: Field name not provided</p>';
            return;
        }
        
        printf(
            '<input type="email" id="%s" name="%s" value="%s" class="regular-text" />',
            esc_attr($name),
            esc_attr($name),
            esc_attr($value)
        );
        
        if ($description) {
            printf('<p class="description">%s</p>', esc_html($description));
        }
    }
    
    public static function number_field($args) {
        $name = $args['name'] ?? '';
        $value = get_option($name, '');
        $description = isset($args['description']) ? $args['description'] : '';
        $min = isset($args['min']) ? $args['min'] : 0;
        $max = isset($args['max']) ? $args['max'] : '';
        
        if (empty($name)) {
            echo '<p>Error: Field name not provided</p>';
            return;
        }
        
        printf(
            '<input type="number" id="%s" name="%s" value="%s" min="%s" %s />',
            esc_attr($name),
            esc_attr($name),
            esc_attr($value),
            esc_attr($min),
            $max ? 'max="' . esc_attr($max) . '"' : ''
        );
        
        if ($description) {
            printf('<p class="description">%s</p>', esc_html($description));
        }
    }
    
    public static function checkbox_field($args) {
        $name = $args['name'] ?? '';
        $value = get_option($name, 0);
        $label = $args['label'] ?? '';
        
        if (empty($name)) {
            echo '<p>Error: Field name not provided</p>';
            return;
        }
        
        printf(
            '<label><input type="checkbox" id="%s" name="%s" value="1" %s /> %s</label>',
            esc_attr($name),
            esc_attr($name),
            checked($value, 1, false),
            esc_html($label)
        );
    }
    
    public static function select_field($args) {
        $name = $args['name'] ?? '';
        $value = get_option($name, '');
        $options = $args['options'] ?? array();
        $description = isset($args['description']) ? $args['description'] : '';
        
        if (empty($name)) {
            echo '<p>Error: Field name not provided</p>';
            return;
        }
        
        printf('<select id="%s" name="%s">', esc_attr($name), esc_attr($name));
        
        foreach ($options as $option_value => $option_label) {
            printf(
                '<option value="%s" %s>%s</option>',
                esc_attr($option_value),
                selected($value, $option_value, false),
                esc_html($option_label)
            );
        }
        
        echo '</select>';
        
        if ($description) {
            printf('<p class="description">%s</p>', esc_html($description));
        }
    }
    
    public static function currency_field($args) {
        $currencies = array(
            'USD' => 'US Dollar ($)',
            'EUR' => 'Euro (€)',
            'GBP' => 'British Pound (£)',
            'CAD' => 'Canadian Dollar (C$)',
            'AUD' => 'Australian Dollar (A$)',
            'JPY' => 'Japanese Yen (¥)'
        );
        
        $args['options'] = $currencies;
        self::select_field($args);
    }
    
    public static function page_dropdown_field($args) {
        $name = $args['name'] ?? '';
        $value = get_option($name, '');
        
        if (empty($name)) {
            echo '<p>Error: Field name not provided</p>';
            return;
        }
        
        wp_dropdown_pages(array(
            'name' => $name,
            'id' => $name,
            'selected' => $value,
            'show_option_none' => __('— Select —', 'wp-digital-download'),
            'option_none_value' => ''
        ));
    }
    
    private static function system_status() {
        $status = array();
        
        $upload_dir = wp_upload_dir();
        $protected_dir = trailingslashit($upload_dir['basedir']) . WPDD_UPLOADS_DIR;
        
        if (is_writable($upload_dir['basedir'])) {
            $status[] = array(
                'label' => __('Upload Directory', 'wp-digital-download'),
                'value' => __('Writable', 'wp-digital-download'),
                'class' => 'wpdd-status-good'
            );
        } else {
            $status[] = array(
                'label' => __('Upload Directory', 'wp-digital-download'),
                'value' => __('Not Writable', 'wp-digital-download'),
                'class' => 'wpdd-status-error'
            );
        }
        
        if (file_exists($protected_dir)) {
            $status[] = array(
                'label' => __('Protected Directory', 'wp-digital-download'),
                'value' => __('Exists', 'wp-digital-download'),
                'class' => 'wpdd-status-good'
            );
        } else {
            $status[] = array(
                'label' => __('Protected Directory', 'wp-digital-download'),
                'value' => __('Missing', 'wp-digital-download'),
                'class' => 'wpdd-status-warning'
            );
        }
        
        if (function_exists('imagecreatefrompng')) {
            $status[] = array(
                'label' => __('GD Library', 'wp-digital-download'),
                'value' => __('Available', 'wp-digital-download'),
                'class' => 'wpdd-status-good'
            );
        } else {
            $status[] = array(
                'label' => __('GD Library', 'wp-digital-download'),
                'value' => __('Not Available', 'wp-digital-download'),
                'class' => 'wpdd-status-warning'
            );
        }
        
        $paypal_client_id = get_option('wpdd_paypal_client_id');
        if ($paypal_client_id) {
            $status[] = array(
                'label' => __('PayPal', 'wp-digital-download'),
                'value' => __('Configured', 'wp-digital-download'),
                'class' => 'wpdd-status-good'
            );
        } else {
            $status[] = array(
                'label' => __('PayPal', 'wp-digital-download'),
                'value' => __('Not Configured', 'wp-digital-download'),
                'class' => 'wpdd-status-warning'
            );
        }
        
        echo '<ul>';
        foreach ($status as $item) {
            printf(
                '<li>%s: <span class="%s">%s</span></li>',
                esc_html($item['label']),
                esc_attr($item['class']),
                esc_html($item['value'])
            );
        }
        echo '</ul>';
    }
    
    public static function sanitize_commission_rate($input) {
        $value = floatval($input);
        if ($value < 0) {
            $value = 0;
            add_settings_error('wpdd_commission_rate', 'invalid_rate', __('Commission rate cannot be less than 0%. Set to 0%.', 'wp-digital-download'));
        } elseif ($value > 100) {
            $value = 100;
            add_settings_error('wpdd_commission_rate', 'invalid_rate', __('Commission rate cannot exceed 100%. Set to 100%.', 'wp-digital-download'));
        }
        return $value;
    }
    
    public static function sanitize_payout_threshold($input) {
        $value = floatval($input);
        if ($value < 0) {
            $value = 0;
            add_settings_error('wpdd_payout_threshold', 'invalid_threshold', __('Payout threshold cannot be negative. Set to 0 (disabled).', 'wp-digital-download'));
        }
        return $value;
    }
}