<?php

namespace Unlockafe_Addons\Classes;

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

class Settings_Controller
{
    private $option_group = 'unlockafe_coupons_settings_group';
    private $option_name = 'unlockafe_coupons_settings';

    public function __construct()
    {
        add_action('admin_menu', [$this, 'register_settings_page'], 99);
        add_action('admin_init', [$this, 'register_settings']);
    }

    public function register_settings_page()
    {
        add_submenu_page(
            'unlockafe-coupons-reporting',
            __('Settings', 'unlock-addons-for-elementor'),
            __('Settings', 'unlock-addons-for-elementor'),
            'manage_woocommerce',
            'unlockafe-coupons-settings',
            [$this, 'render_settings_page']
        );
    }

    public function register_settings()
    {
        register_setting($this->option_group, $this->option_name, [$this, 'sanitize_settings']);

        add_settings_section(
            'unlockafe_coupons_general_section',
            __('General Settings', 'unlock-addons-for-elementor'),
            null,
            $this->option_group
        );

        add_settings_field(
            'auto_apply_coupons',
            __('Auto-Apply Coupons', 'unlock-addons-for-elementor'),
            [$this, 'render_auto_apply_field'],
            $this->option_group,
            'unlockafe_coupons_general_section'
        );
    }

    public function render_auto_apply_field()
    {
        $options = get_option($this->option_name);
        $checked = isset($options['auto_apply_coupons']) && $options['auto_apply_coupons'] ? 'checked'
            : '';
        echo '<input type="checkbox" name="' . esc_attr($this->option_name) . '[auto_apply_coupons]" ' . $checked . '/>';
        echo '<p class="description">' . __('Enable the automatic application of valid coupons for customers.', 'unlock-addons-for-elementor') . '</p>';
    }

    public function sanitize_settings($input)
    {
        $new_input = [];
        if (isset($input['auto_apply_coupons'])) {
            $new_input['auto_apply_coupons'] = absint($input['auto_apply_coupons']);
        }
        return $new_input;
    }

    public function render_settings_page()
    {
        ?>
        <div class="wrap">
            <h1><?php echo esc_html__('Advanced Coupons Settings', 'unlock-addons-for-elementor'); ?></h1>
            <form action="options.php" method="post">
                <?php
                settings_fields($this->option_group);
                do_settings_sections($this->option_group);
                submit_button();
                ?>
            </form>
        </div>
        <?php
    }
}
