<?php
namespace orderflow\Admin;

use orderflow\Courier\Pathao_Api;
use orderflow\Traits\Core;

class General_Settings {
    use Core;

    public function __construct() {
        
    }

    public static function render_courier_settings_page() {
        self::render_settings('courier');
    }

    public static function render_fraud_customer_block_settings_page() {
        self::render_settings('fraud-customer-block');
    }

    public static function render_partial_payment_settings_page() {
        self::render_settings('partial-payment');
    }

    public static function render_settings($current_tab = 'order-autosave') {
        echo "<div class='order-flow-main-box'>";
        require_once __DIR__ .'/promo.php';
        ?>
        <div class="orderflow-settings-container">
            <div class="orderflow-settings-wrapper">
                <div class="orderflow-settings-content">
                    <?php
                    $tabs = [
                        'order-autosave' => 'render_order_autosave_settings',
                        'courier' => 'render_courier_settings',
                        'fraud-customer-block' => 'render_fraud_customer_block_settings',
                        'partial-payment' => 'render_partial_payment_settings',
                    ];

                    $method = $tabs[$current_tab] ?? 'render_order_autosave_settings';
                    if (method_exists(__CLASS__, $method)) {
                        self::$method();
                    }
                    ?>
                </div>
            </div>
        </div>
        <?php
        echo "<div>";
    }

    public static function submit_partial_payment_settings() {
        if (!self::is_license_active()) {
            return;
        }

        // Save enable/disable option
        update_option('ads_enable_partial_payment', !empty($_POST['ads_enable_partial_payment']));

        // Save enable/disable zero rate option
        update_option('ads_enable_partial_payment_zero_rate', !empty($_POST['ads_enable_partial_payment_zero_rate']));

        // Save courier rate threshold
        $threshold = isset($_POST['ads_courier_rate_threshold'])
            ? max(0, min(100, (int)$_POST['ads_courier_rate_threshold']))
            : 70;
        update_option('ads_courier_rate_threshold', $threshold);

        // Save partial payment amount
        $amount = isset($_POST['ads_partial_payment_amount'])
            ? max(0, (float)$_POST['ads_partial_payment_amount'])
            : 100;
        update_option('ads_partial_payment_amount', $amount);

        update_option('ads_partial_label_one', $_POST['ads_partial_label_one']);
        update_option('ads_partial_label_two', $_POST['ads_partial_label_two']);
    }

    public static function render_partial_payment_settings() {
        if (isset($_POST['ads_save_partial_payment_settings'])) {
            check_admin_referer('ads_partial_payment_settings_form_nonce')
                ? self::submit_partial_payment_settings()
                : self::render_error('Security check failed');
        }

        $enabled = get_option('ads_enable_partial_payment', false);
        $enabled_zero_rate = get_option('ads_enable_partial_payment_zero_rate', false);
        $threshold = get_option('ads_courier_rate_threshold', 70);
        $amount = get_option('ads_partial_payment_amount', 100);
        $ads_partial_label_one = get_option('ads_partial_label_one', 'এখন পরিশোধ করুন');
        $ads_partial_label_two = get_option('ads_partial_label_two', 'ডেলিভারিতে পরিশোধ করুন');
        ?>
        <div class="orderflow-section">
            <h2 class="orderflow-section-title">Partial Payment Settings</h2>
            <form method="post">
                <?php wp_nonce_field('ads_partial_payment_settings_form_nonce'); ?>
                <div class="orderflow-form-container">
                    <div class="orderflow-field-row">
                        <div class="orderflow-field-label">Enable Partial Payment

                            <p class="ads-settings-description">
                                Enable or disable the partial payment feature for orders with low delivery success rates.
                            </p>
                        </div>
                        <div class="orderflow-field-input">
                            <label class="orderflow-toggle-switch">
                                <input type="checkbox"
                                       name="ads_enable_partial_payment"
                                       value="1"
                                    <?= checked($enabled); ?>>
                                <span class="orderflow-slider"></span>
                            </label>
                        </div>
                    </div>
                    <div class="orderflow-field-row">
                        <div class="orderflow-field-label">Enable Partial Payment for 0% Rate

                            <p class="ads-settings-description">
                                Enable partial payment feature for orders with 0% delivery success rates.
                            </p>
                        </div>
                        <div class="orderflow-field-input">
                            <label class="orderflow-toggle-switch">
                                <input type="checkbox"
                                       name="ads_enable_partial_payment_zero_rate"
                                       value="1"
                                    <?= checked($enabled_zero_rate); ?>>
                                <span class="orderflow-slider"></span>
                            </label>
                        </div>
                    </div>
                    <div class="orderflow-field-row">
                        <div class="orderflow-field-label">Courier Rate Threshold (%)
                            <p class="ads-settings-description">
                                Orders with delivery success rates below this threshold will require partial payment.
                                Default: 70%
                            </p></div>
                        <div class="orderflow-field-input">
                            <input type="number"
                                   name="ads_courier_rate_threshold"
                                   value="<?= esc_attr($threshold); ?>"
                                   min="0"
                                   max="100"
                                   step="1">
                        </div>
                    </div>
                    <div class="orderflow-field-row">
                        <div class="orderflow-field-label">Partial Payment Amount   <p class="ads-settings-description">
                                The fixed amount to be paid upfront when partial payment is required.
                                Default: 100
                            </p></div>
                        <div class="orderflow-field-input">
                            <input type="number"
                                   name="ads_partial_payment_amount"
                                   value="<?= esc_attr($amount); ?>"
                                   min="0"
                                   step="0.01">

                        </div>
                    </div>
                    <div class="orderflow-field-row">
                        <div class="orderflow-field-label">Label One</div>
                        <div class="orderflow-field-input">
                            <input type="text"
                                   name="ads_partial_label_one"
                                   value="<?= esc_attr($ads_partial_label_one); ?>">
                        </div>
                    </div>
                    <div class="orderflow-field-row">
                        <div class="orderflow-field-label">Label Two </div>
                        <div class="orderflow-field-input">
                            <input type="text"
                                   name="ads_partial_label_two"
                                   value="<?= esc_attr($ads_partial_label_two); ?>">

                        </div>
                    </div>
                </div>
                <button type="submit" class="orderflow-submit-button" name="ads_save_partial_payment_settings">
                    Save Settings
                </button>
            </form>
        </div>
        <?php
    }

    public static function submit_courier_settings() {
        if (!self::is_license_active()) {
            return;
        }

        // Save enable/disable option
        update_option('ads_enable_fraud_checker', !empty($_POST['ads_enable_fraud_checker']));


        // Reload the page
        $redirect_url = admin_url('admin.php?page=orderflow-courier&updated=1');
        wp_redirect($redirect_url);
        exit;
    }

    public static function render_courier_settings() {
        // Check for test results in option
        $test_results = get_option('ads_courier_api_test_results');
        if ($test_results) {
            // Delete the option after retrieving
            delete_option('ads_courier_api_test_results');

            // Display test results
            echo '<div class="notice-container">';
            echo '<h3>API Test Results</h3>';

            foreach ($test_results as $courier => $result) {
                $status_class = $result['status'] === 'error' ? 'api-test-error' : 'success';
                $icon = $result['status'] === 'error' ? '⛔' : '✅';

                echo '<div class="api-test-notice ' . $status_class . '">';
                echo '<span class="notice-icon">' . $icon . '</span>';
                echo '<strong>' . ucfirst($courier) . ' API:</strong> ' . esc_html($result['message']);

                // Show additional details for errors
                if ($result['status'] === 'error' && isset($result['data']['error_type'])) {
                    echo '<div class="error-details">Error Type: ' . esc_html($result['data']['error_type']) . '</div>';
                }

                echo '</div>';
            }
            echo '</div>';
        }

        if (isset($_POST['ads_save_courier_settings'])) {
            check_admin_referer('ads_courier_settings_form_nonce')
                ? self::submit_courier_settings()
                : self::render_error('Security check failed');
        }

        $enabled = get_option('ads_enable_fraud_checker', false);
        ?>
        <div class="orderflow-section">
            <h2 class="orderflow-section-title">Courier Settings</h2>
            <p class="orderflow-subtitle">Settings for courier service.</p>
            <form method="post">
                <?php wp_nonce_field('ads_courier_settings_form_nonce'); ?>
                <div class="orderflow-form-container">
                    <div class="orderflow-field-row">
                        <div class="orderflow-field-label">Enable Fraud Checker

                            <p class="ads-settings-description">
                                Enable or disable the fraud checker feature.
                            </p>
                        </div>
                        <div class="orderflow-field-input">
                            <label class="orderflow-toggle-switch">
                                <input type="checkbox"
                                       name="ads_enable_fraud_checker"
                                       value="1"
                                    <?= checked($enabled); ?>>
                                <span class="orderflow-slider"></span>
                            </label>
                        </div>
                    </div>
                </div>
                <button type="submit" class="orderflow-submit-button" name="ads_save_courier_settings">
                    Save Settings
                </button>
            </form>
        </div>

        <style>
            .notice-container {
                margin: 20px 0;
                padding: 15px;
                background: #f9f9f9;
                border-left: 4px solid #00a0d2;
                border-radius: 3px;
            }

            .api-test-notice {
                display: flex;
                align-items: center;
                padding: 10px;
                margin: 5px 0;
                border-radius: 3px;
            }

            .api-test-notice.success {
                background-color: #edfaef;
                border-left: 4px solid #46b450;
            }

            .api-test-notice.api-test-error {
                background-color: #fdf2f2;
                border-left: 4px solid #dc3232;
            }

            .notice-icon {
                font-size: 1.2em;
                margin-right: 10px;
            }

            .error-details {
                margin-top: 5px;
                font-size: 0.9em;
                color: #666;
                padding-left: 30px;
            }
        </style>
        <?php
    }

    public static function submit_fraud_customer_block_settings() {
        if ( ! self::is_license_active() ) {
            return;
        }

        $checkboxes = [
            'ads_validate_phone_number_length_number',
            'ads_block_phone_numbers',
            'ads_block_ip_addresses',
            'ads_block_email_addresses',
            'ads_restrict_multiple_orders'
        ];

        foreach ($checkboxes as $option) {
            update_option($option, !empty($_POST[$option]));
        }

        update_option('ads_restrict_multiple_orders_time',
            isset($_POST['ads_restrict_multiple_orders_time'])
                ? max(1, (int)$_POST['ads_restrict_multiple_orders_time'])
                : 24
        );

        update_option('ads_restrict_multiple_orders_limit',
            isset($_POST['ads_restrict_multiple_orders_limit'])
                ? max(1, (int)$_POST['ads_restrict_multiple_orders_limit'])
                : 1
        );

        update_option('ads_checkout_process_error_contact_phone_number',
            isset($_POST['ads_checkout_process_error_contact_phone_number'])
                ? sanitize_text_field($_POST['ads_checkout_process_error_contact_phone_number'])
                : ''
        );
    }

    public static function render_fraud_customer_block_settings() {
        if (isset($_POST['ads_save_fraud_customer_block_settings'])) {
            check_admin_referer('ads_fraud_customer_block_settings_form_nonce')
                ? self::submit_fraud_customer_block_settings()
                : self::render_error('Security check failed');
        }

        $checkboxes = [
            'ads_validate_phone_number_length_number' => array(
                'text'  => 'Check 11 digits of phone number',
                'dis'  => 'Validate 11-digit phone numbers.',
            ),
            'ads_block_phone_numbers' => array(
                'text'  => 'Block Phone Numbers',
                'dis'  => 'Block orders from blocked phone numbers.',
            ),
            'ads_block_email_addresses' => array(
                'text'  => 'Block Email Addresses',
                'dis'  => 'Block orders from blocked email addresses.',
            ),
            'ads_block_ip_addresses' => array(
                'text'  => 'Block IP Addresses',
                'dis'  => 'Block orders from blocked IP addresses.',
            ),
            'ads_restrict_multiple_orders' =>  array(
                'text'  => 'Restrict multiple orders from same Phone & IP',
                'dis'  => 'Limit orders from the same phone/IP.',
            )
        ];

        $text_fields = [
            'ads_restrict_multiple_orders_time' => [
                'label' => 'Restrict multiple orders Time (Hours)',
                'dis' => 'Time limit in hours for multiple orders.',
                'default' => 24,
                'min' => 1,
                'max' => 168
            ],
            'ads_restrict_multiple_orders_limit' => [
                'label' => 'Restrict multiple orders limit',
                'dis' => 'Maximum number of orders allowed in the time limit.',
                'default' => 1,
                'min' => 1,
                'max' => 100
            ],
            'ads_checkout_process_error_contact_phone_number' => [
                'label' => 'Checkout Process Error Contact Phone Number',
                'dis' => 'Phone number to display for checkout errors.',
                'default' => '',
                'type' => 'text'
            ]
        ];
        ?>
        <div class="orderflow-section">
            <h2 class="orderflow-section-title">Fraud Customer Block Settings</h2>
            <p class="orderflow-subtitle">Set rules to automatically block potentially fraudulent orders.</p>
            <form method="post">
                <?php wp_nonce_field('ads_fraud_customer_block_settings_form_nonce'); ?>
                <div class="orderflow-form-container">
                    <?php foreach ($checkboxes as $key => $label): ?>
                        <div class="orderflow-field-row">
                            <div class="orderflow-field-label">
                                <?= esc_html($label['text']); ?>
                                <p class="ads-settings-description"><?= esc_html($label['dis']); ?></p>
                            </div>
                            <div class="orderflow-field-input">
                                <label class="orderflow-toggle-switch">
                                    <input type="checkbox"
                                           name="<?= esc_attr($key); ?>"
                                           value="1"
                                        <?= checked(get_option($key)); ?>>
                                    <span class="orderflow-slider"></span>
                                </label>
                            </div>
                        </div>
                    <?php endforeach; ?>

                    <!-- Container for fields that should be toggled -->
                    <div class="restrict-multiple-orders-from-phone" style="display: none;">
                        <?php
                        // Only show time and limit fields in this container
                        foreach ($text_fields as $key => $field):
                            if ($key === 'ads_checkout_process_error_contact_phone_number') {
                                continue; // Skip the contact phone field
                            }
                            ?>
                            <div class="orderflow-field-row">
                                <div class="orderflow-field-label"><?= esc_html($field['label']); ?>  <p class="ads-settings-description"><?= esc_html($field['dis']); ?></p></div>
                                <div class="orderflow-field-input">
                                    <input type="<?= $field['type'] ?? 'number'; ?>"
                                           name="<?= esc_attr($key); ?>"
                                           value="<?= esc_attr(get_option($key, $field['default'])); ?>"
                                           min="<?= $field['min'] ?? '' ?>"
                                           max="<?= $field['max'] ?? '' ?>">
                                    <?php if (isset($field['min'])): ?>
                                        <p class="description">
                                            Min: <?= $field['min']; ?>, Max: <?= $field['max']; ?>
                                        </p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Always visible contact phone field -->
                    <div class="orderflow-field-row">
                        <div class="orderflow-field-label">
                            <?= esc_html($text_fields['ads_checkout_process_error_contact_phone_number']['label']); ?>
                            <p class="ads-settings-description"><?= esc_html($text_fields['ads_checkout_process_error_contact_phone_number']['dis']); ?></p>
                        </div>
                        <div class="orderflow-field-input">
                            <input type="text"
                                   name="ads_checkout_process_error_contact_phone_number"
                                   value="<?= esc_attr(get_option('ads_checkout_process_error_contact_phone_number', $text_fields['ads_checkout_process_error_contact_phone_number']['default'])); ?>">
                        </div>
                    </div>
                </div>
                <button type="submit" class="orderflow-submit-button" name="ads_save_fraud_customer_block_settings">
                    Save Settings
                </button>
            </form>
        </div>

        <script>
            jQuery(document).ready(function($) {
                // Function to toggle visibility based on checkbox
                function toggleRestrictionFields() {
                    const isChecked = $('input[name="ads_restrict_multiple_orders"]').is(':checked');
                    $('.restrict-multiple-orders-from-phone').css('display', isChecked ? 'block' : 'none');
                }

                // Set initial state
                toggleRestrictionFields();

                // Checkbox change listener
                $('input[name="ads_restrict_multiple_orders"]').on('change', function() {
                    toggleRestrictionFields();
                });
            });
        </script>
        <?php
    }

    private static function render_error($message) {
        echo '<div class="orderflow-error"><p>' . esc_html($message) . '.</p></div>';
    }
}