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

class WPBS_SMTP {
    
    public static function init() {
        $enabled = get_option('wpbs_smtp_enabled', false);
        if ($enabled) {
            add_action('phpmailer_init', [__CLASS__, 'configure_phpmailer']);
        }
    }
    
    public static function configure_phpmailer($phpmailer) {
        $phpmailer->isSMTP();
        $phpmailer->Host       = get_option('wpbs_smtp_host', '');
        $phpmailer->SMTPAuth   = true;
        $phpmailer->Port       = get_option('wpbs_smtp_port', 587);
        $phpmailer->Username   = get_option('wpbs_smtp_username', '');
        $phpmailer->Password   = get_option('wpbs_smtp_password', '');
        $phpmailer->SMTPSecure = get_option('wpbs_smtp_encryption', 'tls');
        
        $from_email = get_option('wpbs_smtp_from_email', '');
        $from_name  = get_option('wpbs_smtp_from_name', '');
        if ($from_email) $phpmailer->From = $from_email;
        if ($from_name) $phpmailer->FromName = $from_name;
    }
    
    public static function render_settings_page() {
        if (isset($_POST['wpbs_smtp_nonce']) && wp_verify_nonce($_POST['wpbs_smtp_nonce'], 'wpbs_smtp')) {
            update_option('wpbs_smtp_enabled', isset($_POST['wpbs_smtp_enabled']));
            update_option('wpbs_smtp_host', sanitize_text_field($_POST['wpbs_smtp_host'] ?? ''));
            update_option('wpbs_smtp_port', absint($_POST['wpbs_smtp_port'] ?? 587));
            update_option('wpbs_smtp_username', sanitize_text_field($_POST['wpbs_smtp_username'] ?? ''));
            update_option('wpbs_smtp_password', sanitize_text_field($_POST['wpbs_smtp_password'] ?? ''));
            update_option('wpbs_smtp_encryption', sanitize_text_field($_POST['wpbs_smtp_encryption'] ?? 'tls'));
            update_option('wpbs_smtp_from_email', sanitize_email($_POST['wpbs_smtp_from_email'] ?? ''));
            update_option('wpbs_smtp_from_name', sanitize_text_field($_POST['wpbs_smtp_from_name'] ?? ''));
            echo '<div class="notice notice-success"><p>SMTP settings saved.</p></div>';
        }
        
        // Handle test email
        if (isset($_POST['wpbs_smtp_test_nonce']) && wp_verify_nonce($_POST['wpbs_smtp_test_nonce'], 'wpbs_smtp_test')) {
            $to = sanitize_email($_POST['wpbs_smtp_test_email'] ?? '');
            if ($to) {
                $sent = wp_mail($to, 'WP Bootstrap Studio — SMTP Test', 'This is a test email from WP Bootstrap Studio. Your SMTP is working!');
                if ($sent) {
                    echo '<div class="notice notice-success"><p>Test email sent to ' . esc_html($to) . '!</p></div>';
                } else {
                    echo '<div class="notice notice-error"><p>Failed to send test email. Check your settings.</p></div>';
                }
            }
        }
        
        $presets = [
            'gmail' => ['host' => 'smtp.gmail.com', 'port' => 587, 'encryption' => 'tls'],
            'sendgrid' => ['host' => 'smtp.sendgrid.net', 'port' => 587, 'encryption' => 'tls'],
            'mailgun' => ['host' => 'smtp.mailgun.org', 'port' => 587, 'encryption' => 'tls'],
            'ses' => ['host' => 'email-smtp.us-east-1.amazonaws.com', 'port' => 587, 'encryption' => 'tls'],
        ];
        ?>
        <div class="wrap">
            <h1>SMTP Settings</h1>
            <p>Configure outgoing email delivery. No extra plugins needed.</p>
            
            <form method="post">
                <?php wp_nonce_field('wpbs_smtp', 'wpbs_smtp_nonce'); ?>
                <table class="form-table">
                    <tr>
                        <th>Enable SMTP</th>
                        <td><label><input type="checkbox" name="wpbs_smtp_enabled" value="1" <?php checked(get_option('wpbs_smtp_enabled')); ?>> Override WordPress default mail with SMTP</label></td>
                    </tr>
                    <tr>
                        <th>Quick Presets</th>
                        <td>
                            <?php foreach ($presets as $name => $preset) : ?>
                                <button type="button" class="button wpbs-smtp-preset" data-host="<?php echo esc_attr($preset['host']); ?>" data-port="<?php echo esc_attr($preset['port']); ?>" data-encryption="<?php echo esc_attr($preset['encryption']); ?>"><?php echo ucfirst($name); ?></button>
                            <?php endforeach; ?>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="smtp-host">SMTP Host</label></th>
                        <td><input type="text" id="smtp-host" name="wpbs_smtp_host" value="<?php echo esc_attr(get_option('wpbs_smtp_host')); ?>" class="regular-text"></td>
                    </tr>
                    <tr>
                        <th><label for="smtp-port">Port</label></th>
                        <td><input type="number" id="smtp-port" name="wpbs_smtp_port" value="<?php echo esc_attr(get_option('wpbs_smtp_port', 587)); ?>" class="small-text"></td>
                    </tr>
                    <tr>
                        <th><label for="smtp-encryption">Encryption</label></th>
                        <td>
                            <select id="smtp-encryption" name="wpbs_smtp_encryption">
                                <option value="tls" <?php selected(get_option('wpbs_smtp_encryption', 'tls'), 'tls'); ?>>TLS</option>
                                <option value="ssl" <?php selected(get_option('wpbs_smtp_encryption'), 'ssl'); ?>>SSL</option>
                                <option value="" <?php selected(get_option('wpbs_smtp_encryption'), ''); ?>>None</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="smtp-username">Username</label></th>
                        <td><input type="text" id="smtp-username" name="wpbs_smtp_username" value="<?php echo esc_attr(get_option('wpbs_smtp_username')); ?>" class="regular-text"></td>
                    </tr>
                    <tr>
                        <th><label for="smtp-password">Password</label></th>
                        <td><input type="password" id="smtp-password" name="wpbs_smtp_password" value="<?php echo esc_attr(get_option('wpbs_smtp_password')); ?>" class="regular-text"></td>
                    </tr>
                    <tr>
                        <th><label for="smtp-from-email">From Email</label></th>
                        <td><input type="email" id="smtp-from-email" name="wpbs_smtp_from_email" value="<?php echo esc_attr(get_option('wpbs_smtp_from_email')); ?>" class="regular-text"></td>
                    </tr>
                    <tr>
                        <th><label for="smtp-from-name">From Name</label></th>
                        <td><input type="text" id="smtp-from-name" name="wpbs_smtp_from_name" value="<?php echo esc_attr(get_option('wpbs_smtp_from_name')); ?>" class="regular-text"></td>
                    </tr>
                </table>
                <?php submit_button('Save SMTP Settings'); ?>
            </form>
            
            <hr>
            <h2>Send Test Email</h2>
            <form method="post">
                <?php wp_nonce_field('wpbs_smtp_test', 'wpbs_smtp_test_nonce'); ?>
                <p>
                    <input type="email" name="wpbs_smtp_test_email" placeholder="test@example.com" class="regular-text">
                    <button type="submit" class="button">Send Test</button>
                </p>
            </form>
        </div>
        
        <script>
        document.querySelectorAll('.wpbs-smtp-preset').forEach(btn => {
            btn.addEventListener('click', () => {
                document.getElementById('smtp-host').value = btn.dataset.host;
                document.getElementById('smtp-port').value = btn.dataset.port;
                document.getElementById('smtp-encryption').value = btn.dataset.encryption;
            });
        });
        </script>
        <?php
    }
}
