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

class Manfiet_Expense_Tracker_Settings {
    public function __construct() {
        add_action('admin_menu', [$this, 'add_settings_page']);
        add_action('admin_init', [$this, 'register_settings']);
    }

    public function add_settings_page() {
        add_submenu_page(
            'manfi-expense-tracker',
            __('Manfi Expense Tracker Settings', 'manfi-expense-tracker'),
            __('Settings', 'manfi-expense-tracker'),
            'manage_options',
            'manfiet-expense-settings',
            [$this, 'render_settings_page'],
            30
        );
    }

    public function register_settings() {
        register_setting('manfiet_expense_settings', 'manfiet_default_budget', [
            'type' => 'number',
            'sanitize_callback' => [$this, 'sanitize_budget'],
            'default' => 500,
        ]);

        register_setting('manfiet_expense_settings', 'manfiet_default_weekly_budget', [
            'type' => 'number',
            'sanitize_callback' => [$this, 'sanitize_budget'],
            'default' => 125,
        ]);

        register_setting('manfiet_expense_settings', 'manfiet_default_yearly_budget', [
            'type' => 'number',
            'sanitize_callback' => [$this, 'sanitize_budget'],
            'default' => 6000,
        ]);

        register_setting('manfiet_expense_settings', 'manfiet_export_unknown_user_label', [
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'Unknown User',
        ]);

        register_setting('manfiet_expense_settings', 'manfiet_enable_gutenberg_blocks', [
            'type' => 'boolean',
            'sanitize_callback' => [$this, 'sanitize_checkbox'],
            'default' => 1,
        ]);

        $default_elementor = class_exists('\Elementor\Plugin') ? 1 : 0;
        register_setting('manfiet_expense_settings', 'manfiet_enable_elementor_widgets', [
            'type' => 'boolean',
            'sanitize_callback' => [$this, 'sanitize_checkbox'],
            'default' => $default_elementor,
        ]);

        $domain = wp_parse_url(get_site_url(), PHP_URL_HOST);
        $default_email = 'no-reply@' . ($domain ? $domain : 'manfietracker.com');

        register_setting('manfiet_expense_settings', 'manfiet_email_sender_address', [
            'type' => 'string',
            'sanitize_callback' => 'sanitize_email',
            'default' => $default_email,
        ]);

        register_setting('manfiet_expense_settings', 'manfiet_email_sender_name', [
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'Manfi Expense Tracker',
        ]);

        register_setting('manfiet_expense_settings', 'manfiet_expenses_per_page', [
            'type' => 'number',
            'sanitize_callback' => [$this, 'sanitize_expenses_per_page'],
            'default' => 20,
        ]);

        register_setting('manfiet_expense_settings', 'manfiet_currency', [
            'type' => 'string',
            'sanitize_callback' => [$this, 'sanitize_currency'],
            'default' => 'USD',
        ]);

        register_setting('manfiet_expense_settings', 'manfiet_enable_invoice_manager', [
            'type' => 'boolean',
            'sanitize_callback' => [$this, 'sanitize_checkbox'],
            'default' => 0,
        ]);

        register_setting('manfiet_expense_settings', 'manfiet_invoice_late_fee_enabled', [
            'type' => 'boolean',
            'sanitize_callback' => [$this, 'sanitize_checkbox'],
            'default' => 1,
        ]);

        register_setting('manfiet_expense_settings', 'manfiet_invoice_late_fee_pct', [
            'type' => 'number',
            'sanitize_callback' => 'floatval',
            'default' => 5.0,
        ]);

        register_setting('manfiet_expense_settings', 'manfiet_invoice_late_fee_type', [
            'type' => 'string',
            'sanitize_callback' => 'sanitize_key',
            'default' => 'percentage',
        ]);

        register_setting('manfiet_expense_settings', 'manfiet_invoice_default_terms', [
            'type' => 'string',
            'sanitize_callback' => 'sanitize_textarea_field',
            'default' => "• Payment is due on or before the specified due date.\n• An overdue/late payment fee of {late_fee}% will apply to any unpaid balance after the due date.\n• Please mention the invoice number as reference when making payments.",
        ]);

        add_settings_section(
            'manfiet_general_settings',
            __('General Settings', 'manfi-expense-tracker'),
            null,
            'manfiet-expense-settings'
        );

        $symbol = self::get_current_currency_symbol();

        add_settings_field(
            'manfiet_default_budget',
            /* translators: %s: Currency symbol. */
            sprintf(__('Default Monthly Budget (%s)', 'manfi-expense-tracker'), $symbol),
            [$this, 'default_budget_callback'],
            'manfiet-expense-settings',
            'manfiet_general_settings'
        );

        add_settings_field(
            'manfiet_default_weekly_budget',
            /* translators: %s: Currency symbol. */
            sprintf(__('Default Weekly Budget (%s)', 'manfi-expense-tracker'), $symbol),
            [$this, 'default_weekly_budget_callback'],
            'manfiet-expense-settings',
            'manfiet_general_settings'
        );

        add_settings_field(
            'manfiet_default_yearly_budget',
            /* translators: %s: Currency symbol. */
            sprintf(__('Default Yearly Budget (%s)', 'manfi-expense-tracker'), $symbol),
            [$this, 'default_yearly_budget_callback'],
            'manfiet-expense-settings',
            'manfiet_general_settings'
        );

        add_settings_field(
            'manfiet_export_unknown_user_label',
            __('Missing User Label (Export)', 'manfi-expense-tracker'),
            [$this, 'unknown_user_label_callback'],
            'manfiet-expense-settings',
            'manfiet_general_settings'
        );

        add_settings_field(
            'manfiet_expenses_per_page',
            __('Expenses Per Page', 'manfi-expense-tracker'),
            [$this, 'expenses_per_page_callback'],
            'manfiet-expense-settings',
            'manfiet_general_settings'
        );

        add_settings_field(
            'manfiet_currency',
            __('Currency', 'manfi-expense-tracker'),
            [$this, 'currency_callback'],
            'manfiet-expense-settings',
            'manfiet_general_settings'
        );

        add_settings_field(
            'manfiet_enable_invoice_manager',
            __('Invoice Manager (Beta)', 'manfi-expense-tracker'),
            [$this, 'enable_invoice_manager_callback'],
            'manfiet-expense-settings',
            'manfiet_general_settings'
        );

        add_settings_field(
            'manfiet_enable_gutenberg_blocks',
            __('Enable Gutenberg Blocks', 'manfi-expense-tracker'),
            [$this, 'enable_gutenberg_blocks_callback'],
            'manfiet-expense-settings',
            'manfiet_general_settings'
        );

        add_settings_field(
            'manfiet_enable_elementor_widgets',
            __('Enable Elementor Widgets', 'manfi-expense-tracker'),
            [$this, 'enable_elementor_widgets_callback'],
            'manfiet-expense-settings',
            'manfiet_general_settings'
        );

        add_settings_section(
            'manfiet_email_settings',
            __('Email Notification Settings', 'manfi-expense-tracker'),
            null,
            'manfiet-expense-settings'
        );

        add_settings_field(
            'manfiet_email_sender_address',
            __('Sender Email Address', 'manfi-expense-tracker'),
            [$this, 'email_sender_address_callback'],
            'manfiet-expense-settings',
            'manfiet_email_settings'
        );

        add_settings_field(
            'manfiet_email_sender_name',
            __('Sender Name', 'manfi-expense-tracker'),
            [$this, 'email_sender_name_callback'],
            'manfiet-expense-settings',
            'manfiet_email_settings'
        );
    }

    public function sanitize_budget($value) {
        return absint($value);
    }

    public function default_budget_callback() {
        $value = get_option('manfiet_default_budget', 5000);
        echo '<input type="number" name="manfiet_default_budget" value="' . esc_attr($value) . '" min="0" class="manfiet-input manfiet-settings-input" />';
    }

    public function default_weekly_budget_callback() {
        $value = get_option('manfiet_default_weekly_budget', 20000);
        echo '<input type="number" name="manfiet_default_weekly_budget" value="' . esc_attr($value) . '" min="0" class="manfiet-input manfiet-settings-input" />';
    }

    public function default_yearly_budget_callback() {
        $value = get_option('manfiet_default_yearly_budget', 240000);
        echo '<input type="number" name="manfiet_default_yearly_budget" value="' . esc_attr($value) . '" min="0" class="manfiet-input manfiet-settings-input" />';
    }

    public function unknown_user_label_callback() {
        $value = get_option('manfiet_export_unknown_user_label', __('Unknown User', 'manfi-expense-tracker'));
        echo '<input type="text" name="manfiet_export_unknown_user_label" value="' . esc_attr($value) . '" class="manfiet-input manfiet-settings-input" />';
        echo '<p class="description manfiet-settings-help">' . esc_html__('Used in exports when a linked user account no longer exists.', 'manfi-expense-tracker') . '</p>';
    }

    public function sanitize_checkbox($value) {
        return !empty($value) ? 1 : 0;
    }

    public function enable_gutenberg_blocks_callback() {
        $value = get_option('manfiet_enable_gutenberg_blocks', 1);
        echo '<label class="manfiet-checkbox-label">';
        echo '<input type="checkbox" name="manfiet_enable_gutenberg_blocks" value="1" ' . checked(1, $value, false) . ' />';
        echo ' ' . esc_html__('Enable the custom Gutenberg blocks for expenses and budgets.', 'manfi-expense-tracker');
        echo '</label>';
    }

    public function enable_elementor_widgets_callback() {
        $default = class_exists('\Elementor\Plugin') ? 1 : 0;
        $value = get_option('manfiet_enable_elementor_widgets', $default);
        echo '<label class="manfiet-checkbox-label">';
        echo '<input type="checkbox" name="manfiet_enable_elementor_widgets" value="1" ' . checked(1, $value, false) . ' />';
        echo ' ' . esc_html__('Enable the custom Elementor widgets for expenses and budgets.', 'manfi-expense-tracker');
        echo '</label>';
    }

    public function email_sender_address_callback() {
        $domain = wp_parse_url(get_site_url(), PHP_URL_HOST);
        $default = 'no-reply@' . ($domain ? $domain : 'manfietracker.com');
        $value = get_option('manfiet_email_sender_address', $default);
        echo '<input type="email" name="manfiet_email_sender_address" value="' . esc_attr($value) . '" class="manfiet-input manfiet-settings-input" />';
        echo '<p class="description manfiet-settings-help">' . esc_html__('The "From" email address used in budget alerts and monthly reports.', 'manfi-expense-tracker') . '</p>';
    }

    public function email_sender_name_callback() {
        $value = get_option('manfiet_email_sender_name', 'Manfi Expense Tracker');
        echo '<input type="text" name="manfiet_email_sender_name" value="' . esc_attr($value) . '" class="manfiet-input manfiet-settings-input" />';
        echo '<p class="description manfiet-settings-help">' . esc_html__('The sender name displayed in the recipient\'s email client.', 'manfi-expense-tracker') . '</p>';
    }

    public function sanitize_expenses_per_page($value) {
        $val = absint($value);
        return $val > 0 ? $val : 20;
    }

    public function expenses_per_page_callback() {
        $value = get_option('manfiet_expenses_per_page', 20);
        echo '<input type="number" name="manfiet_expenses_per_page" value="' . esc_attr($value) . '" min="1" max="500" class="manfiet-input manfiet-settings-input" />';
        echo '<p class="description manfiet-settings-help">' . esc_html__('Number of expense records to show per page in the All Expenses list.', 'manfi-expense-tracker') . '</p>';
    }

    public function render_settings_page() {
        echo '<div class="wrap">';
        echo '<h2 class="wp-header-end" style="display:none;"></h2>';
        echo '<div id="manfi-expense-tracker"></div>';
        echo '</div>';
    }

    public static function get_current_currency_symbol() {
        $currency_code = get_option('manfiet_currency', 'USD');
        $symbols = [
            'USD' => '$',
            'EUR' => '€',
            'GBP' => '£',
            'INR' => '₹',
            'BDT' => '৳',
            'CAD' => 'C$',
            'AUD' => 'A$',
            'JPY' => '¥',
            'CNY' => '¥',
        ];
        return isset($symbols[$currency_code]) ? $symbols[$currency_code] : '$';
    }

    public function sanitize_currency($value) {
        $allowed = ['USD', 'EUR', 'GBP', 'INR', 'BDT', 'CAD', 'AUD', 'JPY', 'CNY'];
        return in_array($value, $allowed, true) ? $value : 'USD';
    }

    public function currency_callback() {
        $value = get_option('manfiet_currency', 'USD');
        $currencies = [
            'USD' => __('USD ($)', 'manfi-expense-tracker'),
            'EUR' => __('EUR (€)', 'manfi-expense-tracker'),
            'GBP' => __('GBP (£)', 'manfi-expense-tracker'),
            'INR' => __('INR (₹)', 'manfi-expense-tracker'),
            'BDT' => __('BDT (৳)', 'manfi-expense-tracker'),
            'CAD' => __('CAD (C$)', 'manfi-expense-tracker'),
            'AUD' => __('AUD (A$)', 'manfi-expense-tracker'),
            'JPY' => __('JPY (¥)', 'manfi-expense-tracker'),
            'CNY' => __('CNY (¥)', 'manfi-expense-tracker'),
        ];
        echo '<select name="manfiet_currency" class="manfiet-input manfiet-settings-input">';
        foreach ($currencies as $code => $label) {
            echo '<option value="' . esc_attr($code) . '" ' . selected($value, $code, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select>';
        echo '<p class="description manfiet-settings-help">' . esc_html__('Select your preferred currency for expense and budget tracking.', 'manfi-expense-tracker') . '</p>';
    }

    public function enable_invoice_manager_callback() {
        $value = get_option('manfiet_enable_invoice_manager', 0);
        echo '<label class="manfiet-checkbox-label">';
        echo '<input type="checkbox" name="manfiet_enable_invoice_manager" value="1" ' . checked(1, $value, false) . ' />';
        echo ' ' . esc_html__('Enable the Invoice Manager (Beta) features and menus.', 'manfi-expense-tracker');
        echo '</label>';
    }
}
