<?php
namespace orderflow\Admin;

class Customer_Access {
    public function __construct() {
        // AJAX handlers
        add_action('wp_ajax_ads_set_customer_access', [$this, 'handle_customer_access']);
        add_action('wp_ajax_nopriv_ads_set_customer_access', [$this, 'handle_customer_access']);

        add_action('admin_footer', [$this, 'output_inline_scripts']);
    }

    /**
     * Outputs inline JavaScript with necessary configurations
     */
    public function output_inline_scripts(): void {
        // Create security nonce
        $nonce = wp_create_nonce('ads_set_customer_access_secure_nonce');

        ?>
        <script type="text/javascript">
            (function($) {
                "use strict";

                // Configuration object
                const adsConfig = {
                    ajaxUrl: '<?php echo admin_url('admin-ajax.php'); ?>',
                    nonce: '<?php echo $nonce; ?>'
                };

                // Event handler for customer access buttons
                $(document).on('click', '.ads-customer-access-btn', function(e) {
                    e.preventDefault();
                    e.stopPropagation();

                    const $button = $(this);
                    const type = $button.data('type');
                    const value = $button.data('value');

                    // AJAX request
                    $.ajax({
                        url: adsConfig.ajaxUrl,
                        type: 'POST',
                        data: {
                            action: 'ads_set_customer_access',
                            _ajax_nonce: adsConfig.nonce,
                            type: type,
                            value: value
                        },
                        success: function(response) {
                            if (response.success) {
                                const newStatus = response.data;

                                // Update button appearance
                                if (newStatus === 'blocked') {
                                    $button
                                        .removeClass('ads-customer-access-allowed')
                                        .addClass('ads-customer-access-blocked');
                                } else {
                                    $button
                                        .removeClass('ads-customer-access-blocked')
                                        .addClass('ads-customer-access-allowed');
                                }
                            }
                        },
                        error: function() {
                            console.error('Customer access update failed');
                        }
                    });
                });
            })(jQuery);
        </script>
        <?php
    }

    /**
     * Handles customer access AJAX requests
     */
    public function handle_customer_access(): void {
        // Security verification
        check_ajax_referer('ads_set_customer_access_secure_nonce');

        // Sanitize input data
        $type = isset($_POST['type']) ? sanitize_text_field(wp_unslash($_POST['type'])) : '';
        $value = isset($_POST['value']) ? sanitize_text_field(wp_unslash($_POST['value'])) : '';

        // Validate input
        if (empty($type) || empty($value)) {
            wp_send_json_error('Invalid data parameters');
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'ads_customers_data';

        // Check for existing record
        $existing_record = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT data_access FROM {$table_name} 
                WHERE data_type = %s AND data_value = %s  AND data_value = %s ",
                $type,
                $value,
                $value
            )
        );

        if ($existing_record) {
            // Toggle existing access status
            $new_access = ($existing_record->data_access === 'allowed') ? 'blocked' : 'allowed';

            $wpdb->update(
                $table_name,
                ['data_access' => $new_access],
                ['data_type' => $type, 'data_value' => $value],
                ['%s'],
                ['%s', '%s']
            );
        } else {
            // Create new record with default blocked access
            $new_access = 'blocked';

            $wpdb->insert(
                $table_name,
                [
                    'data_type' => $type,
                    'data_value' => $value,
                    'data_access' => $new_access
                ],
                ['%s', '%s', '%s']
            );
        }

        wp_send_json_success($new_access);
    }
}