<?php
/**
 * Order Status Restriction Tab
 *
 * This class handles:
 * - Rendering the "Order Status Restriction" settings tab in the plugin.
 * - Saving, updating, and deleting order status restriction rules.
 * - Enabling/disabling rules via AJAX.
 *
 * Each rule defines:
 *  - User roles affected
 *  - Payment methods included
 *  - Allowed order statuses
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

class WOSR_Order_Status {

    /**
     * Constructor.
     * Registers hooks for rendering and handling form submissions.
     */
    public function __construct() {
        // Render tab content
        add_action('wosr_render_tab_order_status', array($this, 'render_tab'));

        // Handle CRUD actions
        add_action('admin_post_wosr_save_rule', array($this, 'save_rule'));
        add_action('admin_post_wosr_update_rule', array($this, 'update_rule'));
        add_action('admin_post_wosr_delete_rule', array($this, 'delete_rule'));

        // Handle AJAX toggle (enable/disable rules)
        add_action('wp_ajax_wosr_toggle_rule_status', array($this, 'toggle_rule_status'));
    }

    /**
     * Render the "Order Status Restriction" tab.
     *
     * - Displays a form for creating/updating rules.
     * - Lists existing rules.
     * - Shows upgrade prompts if Free version limits are reached.
     */
    public function render_tab() {
        global $wpdb;

        $table = $wpdb->prefix . 'wosr_order_status';

        // All caching is done via WOSR_Cache class which internally uses wp_cache_get/set/delete.
		$rules = $wpdb->get_results( "SELECT * FROM {$table} ORDER BY id DESC LIMIT 2", ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.NoCaching
		
        // Load WooCommerce data
        $payment_gateways = WC()->payment_gateways()->payment_gateways();
        $user_roles       = wp_roles()->roles;
        $order_statuses   = wc_get_order_statuses();

        // Editing mode check
        $is_editing = isset($_GET['edit']); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only reading safe GET value, no action performed
        $rule_id    = $is_editing ? intval($_GET['edit']) : null; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only reading safe GET value, no action performed

        // If editing, fetch the rule being edited
        if ($is_editing) {
            $table = $wpdb->prefix . 'wosr_order_status';

			$rule = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $rule_id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.NoCaching

            $user_role      = json_decode($rule->user_role ?? '[]', true);
            $payment_method = json_decode($rule->payment_method ?? '[]', true);
            $statuses       = json_decode($rule->statuses ?? '[]', true);
        }

        echo '<h3 class="header-h3">' . esc_html__('Order Status Update Restriction', 'order-role-manager-for-woocommerce') . '</h3>';

        // Success notice (read-only, safe)
        $success = isset($_GET['success']) ? sanitize_text_field(wp_unslash($_GET['success'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only reading safe GET value, no action performed

        if ($success) {
            echo '<div class="wosr-notice-success"><span>' .
                esc_html__('Settings saved successfully!', 'order-role-manager-for-woocommerce') .
            '</span></div>';
        }

        /**
         * =========================
         * Rule Create/Update Form
         * =========================
         */
        ?>
        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
            <input type="hidden" name="action" value="<?php echo $is_editing ? 'wosr_update_rule' : 'wosr_save_rule'; ?>">
            <?php if ($is_editing): ?>
                <input type="hidden" name="rule_id" value="<?php echo esc_attr($rule->id); ?>">
            <?php endif; ?>
            <?php wp_nonce_field('wosr_save_rule', 'wosr_nonce'); ?>

            <table class="form-table wosr-table">
                <tr>
                    <th><?php esc_html_e('User Role', 'order-role-manager-for-woocommerce'); ?></th>
                    <th><?php esc_html_e('Payment Method(s)', 'order-role-manager-for-woocommerce'); ?></th>
                    <th><?php esc_html_e('Allowed Order Status(es)', 'order-role-manager-for-woocommerce'); ?></th>
                </tr>
                <tr>
                    <!-- User Role select -->
                    <td>
                        <select name="user_role[]" multiple required class="wosr_select2">
                            <?php foreach ($user_roles as $key => $role): ?>
                                <?php if ($key === 'administrator') continue; ?>
                                <option value="<?php echo esc_attr($key); ?>" <?php selected(in_array($key, $user_role ?? [])); ?>>
                                    <?php echo esc_html($role['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>

                    <!-- Payment Methods select -->
                    <td>
                        <select name="payment_method[]" multiple required class="wosr_select2 payment-methods">
                            <option value="all_payment_methods" <?php selected(in_array('all_payment_methods', $payment_method ?? [])); ?>>
                                <?php esc_html_e('ALL PAYMENT METHODS', 'order-role-manager-for-woocommerce'); ?>
                            </option>
                            <?php foreach ($payment_gateways as $key => $gateway): ?>
                                <option value="<?php echo esc_attr($key); ?>" <?php selected(in_array($key, $payment_method ?? [])); ?>>
                                    <?php echo esc_html($gateway->title); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>

                    <!-- Allowed Statuses select -->
                    <td>
                        <select name="statuses[]" multiple required class="wosr_select2 statuses">
                            <option value="nothing-allowed" <?php selected(in_array('nothing-allowed', $statuses ?? [])); ?>>
                                <?php esc_html_e('NO ORDER STATUS ALLOWED', 'order-role-manager-for-woocommerce'); ?>
                            </option>
                            <?php foreach ($order_statuses as $key => $label): ?>
                                <option value="<?php echo esc_attr($key); ?>" <?php selected(in_array($key, $statuses ?? [])); ?>>
                                    <?php echo esc_html($label); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                </tr>
            </table>

            <!-- Submit button -->
            <p class="submit">
                <input type="submit" class="button-primary" 
                    value="<?php echo $is_editing ? esc_attr__('Update Rule', 'order-role-manager-for-woocommerce') : esc_attr__('Save Rule', 'order-role-manager-for-woocommerce'); ?>" >
            </p>
        </form>

        <?php
        /**
         * =========================
         * Existing Rules List
         * =========================
         */
        ?>
        <h3 class="subheader-h3"><?php esc_html_e('Existing Rules for User Roles', 'order-role-manager-for-woocommerce'); ?></h3>
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th><?php esc_html_e('User Role', 'order-role-manager-for-woocommerce'); ?></th>
                    <th><?php esc_html_e('Payment Method', 'order-role-manager-for-woocommerce'); ?></th>
                    <th><?php esc_html_e('Allowed Statuses', 'order-role-manager-for-woocommerce'); ?></th>
                    <th><?php esc_html_e('Actions', 'order-role-manager-for-woocommerce'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rules as $rule): ?>
                    <?php
                    // Decode stored values
                    $role_ids           = json_decode( $rule['user_role'], true );
                    $payment_method_ids = json_decode( $rule['payment_method'], true );
                    $status_ids         = json_decode( $rule['statuses'], true );
                    $role_ids           = is_array( $role_ids ) ? $role_ids : array();
                    $payment_method_ids = is_array( $payment_method_ids ) ? $payment_method_ids : array();
                    $status_ids         = is_array( $status_ids ) ? $status_ids : array();

                    // Map role IDs to names
                    $role_names = array_map(
                        static function ( $id ) use ( $user_roles ) {
                            return isset( $user_roles[ $id ]['name'] ) ? $user_roles[ $id ]['name'] : $id;
                        },
                        $role_ids
                    );

                    // Map payment method IDs to names
                    $payment_method_names = array_map(
                        static function ( $id ) use ( $payment_gateways ) {
                            if ( 'all_payment_methods' === $id ) {
                                return __( 'ALL PAYMENT METHODS', 'order-role-manager-for-woocommerce' );
                            }

                            if ( isset( $payment_gateways[ $id ] ) && is_object( $payment_gateways[ $id ] ) && is_callable( array( $payment_gateways[ $id ], 'get_title' ) ) ) {
                                return $payment_gateways[ $id ]->get_title();
                            }

                            return sprintf(
                                /* translators: %s: stored payment gateway ID. */
                                __( '%s (unavailable)', 'order-role-manager-for-woocommerce' ),
                                $id
                            );
                        },
                        $payment_method_ids
                    );

                    // Map status IDs to labels
                    $status_names = array_map(function ($status) {
                        return $status === 'nothing-allowed'
                            ? __('NO ORDER STATUS ALLOWED', 'order-role-manager-for-woocommerce')
                            : wc_get_order_status_name($status);
                    }, $status_ids);
                    ?>
                    <tr>
                        <td><?php echo esc_html(implode(', ', $role_names)); ?></td>
                        <td><?php echo esc_html(implode(', ', $payment_method_names)); ?></td>
                        <td><?php echo esc_html(implode(', ', $status_names)); ?></td>
                        <td>
                            <!-- Rule toggle -->
                            <?php $checked = ($rule['status'] === 'enabled') ? 'checked' : ''; ?>
                            <label class="switch">
                                <input type="checkbox" class="wosr-payment-rule-toggle" data-rule-id="<?php echo esc_attr($rule['id']); ?>" <?php echo esc_attr($checked); ?>>
                                <span class="slider round"></span>
                            </label>

                            <!-- Edit link -->
                            <a href="<?php echo esc_url(add_query_arg('edit', esc_attr($rule['id']))); ?>" class="button button-primary">✏️ <?php esc_html_e('Edit', 'order-role-manager-for-woocommerce'); ?></a>

                            <!-- Delete form -->
                            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="delete-rule-form">
                                <input type="hidden" name="action" value="wosr_delete_rule">
                                <input type="hidden" name="rule_id" value="<?php echo esc_attr($rule['id']); ?>">
                                <?php wp_nonce_field('wosr_delete_rule', 'wosr_nonce'); ?>
                                <button type="submit" class="button button-secondary delete-rule-btn">❌ <?php esc_html_e('Delete', 'order-role-manager-for-woocommerce'); ?></button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <!-- Dummy table for Individual Users (Pro feature only) -->
        <h3 class="subheader-h3"><?php esc_html_e('Existing Rules for Individual Users', 'order-role-manager-for-woocommerce'); ?></h3>
        <p class="wosr-user-table-description">
            <?php esc_html_e('The rules here override the rules for User Roles above.', 'order-role-manager-for-woocommerce'); ?>
        </p>
        <div class="wosr-username-dummy-wrapper">
            <div class="wosr-username-dummy-overlay">
                <div>🔒</div>
                <h4><?php esc_html_e('Please upgrade to unlock order restrictions for individual users.', 'order-role-manager-for-woocommerce'); ?></h4>
                <a href="<?php echo esc_url(admin_url('admin.php?billing_cycle=annual&page=wosr-settings-pricing')); ?>" class="button button-primary wosr-username-dummy-upgrade-btn">
                    <?php esc_html_e('Upgrade to Pro', 'order-role-manager-for-woocommerce'); ?>
                </a>
            </div>

            <!-- Dummy sample table -->
            <table class="wp-list-table widefat fixed striped wosr-username-dummy-table">
                <thead>
                    <tr>
                        <th>Username</th>
                        <th>User Role</th>
                        <th>Payment Methods</th>
                        <th>Allowed Statuses</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>john.doe</td>
                        <td>Shop Manager</td>
                        <td>PayPal, Direct Bank Transfer</td>
                        <td>pending, processing, completed</td>
                        <td>
                            <a class="button button-primary">✏️ Edit</a>
                            <button class="button button-secondary">❌ Delete</button>
                        </td>
                    </tr>
                    <tr>
                        <td>jane.smith</td>
                        <td>Order Manager</td>
                        <td>Credit Card, Cash on Delivery</td>
                        <td>processing, on-hold</td>
                        <td>
                            <a class="button button-primary">✏️ Edit</a>
                            <button class="button button-secondary">❌ Delete</button>
                        </td>
                    </tr>
                    <tr>
                        <td>william.green</td>
                        <td>View Orders</td>
                        <td>PayPal</td>
                        <td>completed, refunded</td>
                        <td>
                            <a class="button button-primary">✏️ Edit</a>
                            <button class="button button-secondary">❌ Delete</button>
                        </td>
                    </tr>
                    <tr>
                        <td>linda.jones</td>
                        <td>Developer</td>
                        <td>Direct Bank Transfer, Check Payments</td>
                        <td>on-hold, cancelled</td>
                        <td>
                            <a class="button button-primary">✏️ Edit</a>
                            <button class="button button-secondary">❌ Delete</button>
                        </td>
                    </tr>
                    <tr>
                        <td>michael.brown</td>
                        <td>Shop Manager</td>
                        <td>Cash on Delivery, Credit Card</td>
                        <td>pending, failed</td>
                        <td>
                            <a class="button button-primary">✏️ Edit</a>
                            <button class="button button-secondary">❌ Delete</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <?php
    }

    /**
     * Save a new rule (Create).
     * Validates nonce, permissions, and free version rule limit.
     */
    public function save_rule() {
        if (
            ! isset($_POST['wosr_nonce']) ||
            ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['wosr_nonce'])), 'wosr_save_rule')
        ) {
            wp_die(esc_html__('Security check failed', 'order-role-manager-for-woocommerce'));
        }

        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Unauthorized', 'order-role-manager-for-woocommerce'));
        }
		
        global $wpdb;
        $table = $wpdb->prefix . 'wosr_order_status';
		
        // Sanitize array inputs
        $payment_method = WOSR_Permissions::sanitize_payment_methods( $_POST['payment_method'] ?? array() );
        $user_role      = WOSR_Permissions::sanitize_roles( $_POST['user_role'] ?? array() );
        $statuses       = WOSR_Permissions::sanitize_statuses( $_POST['statuses'] ?? array() );

		if ( empty( $payment_method ) || empty( $user_role ) || empty( $statuses ) ) {
			wp_die( esc_html__( 'Please select valid roles, payment methods, and order statuses.', 'order-role-manager-for-woocommerce' ), '', array( 'response' => 400 ) );
		}
		$count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.NoCaching
		if ( $count >= 2 ) {
			wp_die( esc_html__( 'The free version supports a maximum of two rules.', 'order-role-manager-for-woocommerce' ), '', array( 'response' => 403 ) );
		}

		// Direct query to a custom table
		// Caching for reads is already handled in WOSR_Cache
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching 
        $wpdb->insert(
            $table,
            [
                'payment_method' => wp_json_encode($payment_method),
                'user_role'      => wp_json_encode($user_role),
                'statuses'       => wp_json_encode($statuses),
            ],
            ['%s', '%s', '%s']
        );

		WOSR_Permissions::clear_request_cache();

        wp_safe_redirect(admin_url('admin.php?page=wosr-settings&tab=order_status&success=1'));
        exit;
    }

    /**
     * Update an existing rule.
     */
    public function update_rule() {
        if (
            ! isset($_POST['wosr_nonce']) ||
            ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['wosr_nonce'])), 'wosr_save_rule')
        ) {
            wp_die(esc_html__('Security check failed', 'order-role-manager-for-woocommerce'));
        }

        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Unauthorized', 'order-role-manager-for-woocommerce'));
        }

        global $wpdb;

        // Sanitize array inputs
        $payment_method = WOSR_Permissions::sanitize_payment_methods( $_POST['payment_method'] ?? array() );
        $user_role      = WOSR_Permissions::sanitize_roles( $_POST['user_role'] ?? array() );
        $statuses       = WOSR_Permissions::sanitize_statuses( $_POST['statuses'] ?? array() );
        $rule_id        = isset($_POST['rule_id']) ? absint($_POST['rule_id']) : 0;

        if ( ! $rule_id || empty( $payment_method ) || empty( $user_role ) || empty( $statuses ) ) {
            wp_die(esc_html__('Missing or invalid rule ID', 'order-role-manager-for-woocommerce'));
        }
		
		// Direct query to a custom table
		// Caching for reads is already handled in WOSR_Cache
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching 
		$wpdb->update(
			"{$wpdb->prefix}wosr_order_status",
			[
				'payment_method' => wp_json_encode( $payment_method ),
				'user_role'      => wp_json_encode( $user_role ),
				'statuses'       => wp_json_encode( $statuses ),
			],
			[ 'id' => $rule_id ],
			[ '%s', '%s', '%s' ],
			[ '%d' ]
		);

		WOSR_Permissions::clear_request_cache();

		wp_safe_redirect( admin_url( 'admin.php?page=wosr-settings&tab=order_status&success=1' ) );
		exit;
	}

    public function delete_rule() {
        if (
			! isset($_POST['wosr_nonce']) ||
			! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['wosr_nonce'])), 'wosr_delete_rule')
		) {
			wp_die(esc_html__('Security check failed', 'order-role-manager-for-woocommerce'));
		}

        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Unauthorized', 'order-role-manager-for-woocommerce'));
        }

		$rule_id = isset( $_POST['rule_id'] ) ? absint( $_POST['rule_id'] ) : 0;
        if ( $rule_id ) {
			global $wpdb;
		    

			// Direct query to a custom table
			// Caching for reads is already handled in WOSR_Cache
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching 
			$wpdb->delete(
				"{$wpdb->prefix}wosr_order_status",
				[ 'id' => $rule_id ],
				[ '%d' ]
			);
			WOSR_Permissions::clear_request_cache();
		}

        wp_safe_redirect(admin_url('admin.php?page=wosr-settings&tab=order_status&success=1'));
        exit;
    }

    public function toggle_rule_status() {

        if (
			! isset( $_POST['rule_id'], $_POST['status'], $_POST['nonce'] ) ||
			! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wosr_toggle_status' )
		) {
			wp_send_json_error( array( 'message' => __( 'Invalid request', 'order-role-manager-for-woocommerce' ) ), 403 );
		}
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error( array( 'message' => __( 'Unauthorized', 'order-role-manager-for-woocommerce' ) ), 403 );
        }

        global $wpdb;
        $rule_id = intval($_POST['rule_id']);
        $status = ($_POST['status'] === 'true') ? 'enabled' : 'disabled';
        

		// Direct query to a custom table
		// Caching for reads is already handled in WOSR_Cache
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching 
		$updated = $wpdb->update(
            "{$wpdb->prefix}wosr_order_status",
            ['status' => $status],
            ['id' => $rule_id]
        );
        
		WOSR_Permissions::clear_request_cache();
		
        if ($updated !== false) {
            wp_send_json_success(['message' => 'Status updated successfully']);
        } else {
            wp_send_json_error(['message' => 'Failed to update statuses']);
        }
    }
}

new WOSR_Order_Status();
