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

// Settings Page
function acwbsrh_settings_page() {
    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'auto-content-writer-by-srh'));
    }
    
    ?>
     <?php settings_errors(); ?> <!-- Show success/error messages -->
    <div class="wrap">
        <h1><?php echo esc_html__('Auto Blog Writer - Settings', 'auto-content-writer-by-srh'); ?></h1>
        <form method="post" action="options.php">
            <?php
            settings_fields('acwbsrh_settings_group');
            do_settings_sections('acwbsrh-settings');
            submit_button();
            ?>
        </form>
    </div>
    <?php
}

// Register Settings
add_action('admin_init', 'acwbsrh_register_settings');
function acwbsrh_register_settings() {
    register_setting('acwbsrh_settings_group', 'acwbsrh_settings', 'acwbsrh_sanitize_settings');

    add_settings_section(
        'acwbsrh_settings_section',
        esc_html__('Blog Generation Settings', 'auto-content-writer-by-srh'),
        'acwbsrh_settings_section_description',
        'acwbsrh-settings'
    );

    add_settings_field('business_name', esc_html__('Business Name', 'auto-content-writer-by-srh'), 'acwbsrh_text_callback', 'acwbsrh-settings', 'acwbsrh_settings_section', [
        'id' => 'business_name',
        'description' => esc_html__('The name of your business or brand. This helps personalize blog tone and mentions.', 'auto-content-writer-by-srh')
    ]);

    add_settings_field('business_type', esc_html__('Business Type', 'auto-content-writer-by-srh'), 'acwbsrh_text_callback', 'acwbsrh-settings', 'acwbsrh_settings_section', [
        'id' => 'business_type',
        'description' => esc_html__('E.g., "Plumbing company", "E-commerce store", "Digital agency". Used for context in prompts.', 'auto-content-writer-by-srh')
    ]);

    add_settings_field('services_offered', esc_html__('Services Offered (comma-separated)', 'auto-content-writer-by-srh'), 'acwbsrh_textarea_callback', 'acwbsrh-settings', 'acwbsrh_settings_section', [
        'id' => 'services_offered',
        'description' => esc_html__('List your main services separated by commas. These are used to tailor content relevance.', 'auto-content-writer-by-srh')
    ]);

    add_settings_field('tone_of_voice', esc_html__('Preferred Tone of Voice', 'auto-content-writer-by-srh'), 'acwbsrh_dropdown_callback', 'acwbsrh-settings', 'acwbsrh_settings_section', [
        'id' => 'tone_of_voice',
        'options' => ['Professional', 'Friendly', 'Chatty', 'Direct'],
        'description' => esc_html__('Choose the style in which your blogs should be written.', 'auto-content-writer-by-srh')
    ]);

    add_settings_field('target_audience', esc_html__('Target Audience (optional)', 'auto-content-writer-by-srh'), 'acwbsrh_textarea_callback', 'acwbsrh-settings', 'acwbsrh_settings_section', [
        'id' => 'target_audience',
        'description' => esc_html__('Describe who your ideal customer is. E.g., "Homeowners", "Small business owners", "Tech-savvy readers".', 'auto-content-writer-by-srh')
    ]);

    add_settings_field('usp', esc_html__('Unique Selling Point / Brand Style (optional)', 'auto-content-writer-by-srh'), 'acwbsrh_textarea_callback', 'acwbsrh-settings', 'acwbsrh_settings_section', [
        'id' => 'usp',
        'description' => esc_html__('What makes your business unique? Mention tone, values, or approach to highlight in blog posts.', 'auto-content-writer-by-srh')
    ]);

    add_settings_field('blog_frequency', esc_html__('Preferred Blog Frequency', 'auto-content-writer-by-srh'), 'acwbsrh_dropdown_callback', 'acwbsrh-settings', 'acwbsrh_settings_section', [
        'id' => 'blog_frequency',
        'options' => ['Weekly', 'Bi-Weekly', 'Monthly'],
        'description' => wp_kses_post(sprintf(
            // translators: %s is the URL to the "Generate Blog Now" page in the admin.
            __('Defines how often blogs are auto-generated after clicking <a href="%s" target="_blank">Generate Blog Now</a>.<br>- Weekly = every 7 days<br>- Bi-Weekly = every 14 days<br>- Monthly = every 28 days', 'auto-content-writer-by-srh'),
            esc_url(admin_url('admin.php?page=acwbsrh-manual'))
        ))
    ]);

    add_settings_field('post_status', esc_html__('Default Post Status', 'auto-content-writer-by-srh'), 'acwbsrh_dropdown_callback', 'acwbsrh-settings', 'acwbsrh_settings_section', [
        'id' => 'post_status',
        'options' => ['Draft', 'Published'],
        'description' => esc_html__('Choose whether generated blogs should be published immediately or saved as drafts.', 'auto-content-writer-by-srh')
    ]);
}

// Settings Section Description
function acwbsrh_settings_section_description() {
    echo '<div class="notice notice-warning" style="padding: 15px; margin-bottom: 20px;">
        <p><strong>' . esc_html__('Important:', 'auto-content-writer-by-srh') . '</strong> ' . esc_html__('These settings are essential for high-quality AI-generated content. They provide the core context ("the bible") for your blog prompts. Please fill them carefully.', 'auto-content-writer-by-srh') . '</p>
    </div>';
}

// Text Field Callback
function acwbsrh_text_callback($args) {
    $acwbsrh_options = get_option('acwbsrh_settings');
    $acwbsrh_value = isset($acwbsrh_options[$args['id']]) ? esc_attr($acwbsrh_options[$args['id']]) : '';
    echo '<input type="text" name="acwbsrh_settings[' . esc_attr($args['id']) . ']" value="' . esc_attr($acwbsrh_value) . '" class="regular-text">';
    if (!empty($args['description'])) {
        echo '<p class="description">' . wp_kses_post($args['description']) . '</p>';
    }
}

// Dropdown Callback
function acwbsrh_dropdown_callback($args) {
    $acwbsrh_options = get_option('acwbsrh_settings');
     $acwbsrh_selected = isset($acwbsrh_options[$args['id']]) ? $acwbsrh_options[$args['id']] : '';
	echo '<select name="acwbsrh_settings[' . esc_attr($args['id']) . ']">';
	foreach ($args['options'] as $acwbsrh_option) {
		$acwbsrh_sel = selected($acwbsrh_selected, $acwbsrh_option, false);
		printf(
			'<option value="%s" %s>%s</option>',
			esc_attr($acwbsrh_option),
			esc_attr($acwbsrh_sel),
			esc_html($acwbsrh_option)
		);
	}
	echo '</select>';


    if (!empty($args['description'])) {
        echo '<p class="description">' . wp_kses_post($args['description']) . '</p>';
    }
}

// Textarea Callback
function acwbsrh_textarea_callback($args) {
    $acwbsrh_options = get_option('acwbsrh_settings');
    $acwbsrh_value = isset($acwbsrh_options[$args['id']]) ? esc_textarea($acwbsrh_options[$args['id']]) : '';
    echo '<textarea name="acwbsrh_settings[' . esc_attr($args['id']) . ']" rows="5" cols="50" class="large-text">' . esc_textarea($acwbsrh_value) . '</textarea>';
    if (!empty($args['description'])) {
        echo '<p class="description">' . wp_kses_post($args['description']) . '</p>';
    }
}

// Sanitize Settings
function acwbsrh_sanitize_settings($input) {
    $sanitized = [];
    $sanitized['business_name']      = sanitize_text_field($input['business_name'] ?? '');
    $sanitized['business_type']      = sanitize_text_field($input['business_type'] ?? '');
    $sanitized['services_offered']   = sanitize_textarea_field($input['services_offered'] ?? '');
    $sanitized['tone_of_voice']      = sanitize_text_field($input['tone_of_voice'] ?? '');
    $sanitized['target_audience']    = sanitize_textarea_field($input['target_audience'] ?? '');
    $sanitized['usp']                = sanitize_textarea_field($input['usp'] ?? '');
    $sanitized['blog_frequency']     = sanitize_text_field($input['blog_frequency'] ?? '');
    $sanitized['post_status']        = sanitize_text_field($input['post_status'] ?? '');
    return $sanitized;
}