<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Prevent direct access.
}

/**
 * Class WOSR_Order_Status_Overview
 *
 * Manages order status overview restrictions in WooCommerce by user roles.
 * Provides CRUD (Create, Read, Update, Delete) operations for rules and handles
 * AJAX toggling of rule activation states.
 */
class WOSR_Order_Status_Overview {

    /**
     * Constructor.
     *
     * Registers hooks for rendering the tab, handling form submissions,
     * and processing AJAX requests.
     */
    public function __construct() {
		// Render tab content
        add_action( 'wosr_render_tab_order_status_overview', array( $this, 'render_tab' ) );
		
		// Handle CRUD actions
        add_action( 'admin_post_wosr_save_rule_overview', array( $this, 'save_rule' ) );
        add_action( 'admin_post_wosr_update_rule_overview', array( $this, 'update_rule' ) );
        add_action( 'admin_post_wosr_delete_rule_overview', array( $this, 'delete_rule' ) );
		
		// Handle AJAX toggle (enable/disable rules)
        add_action( 'wp_ajax_wosr_toggle_rule_status_overview', array( $this, 'toggle_rule_status' ) );
    }

    /**
     * Render the "Order Status Overview Restriction" tab UI.
     *
     * - Loads rules (from cache or DB).
     * - Displays form for creating/editing rules.
     * - Enforces free version limit (max 2 rules).
     * - Shows existing rules for roles + placeholder for user-based rules (locked in free).
     *
     * @return void
     */
    public function render_tab() {
        global $wpdb;

		$table_name = $wpdb->prefix . 'wosr_order_status_overview';
		$rules = $wpdb->get_results( "SELECT * FROM {$table_name} 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

        $user_roles     = wp_roles()->roles;
        $order_statuses = wc_get_order_statuses();
        $is_editing     = false;

        // Detect edit mode.
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ( isset( $_GET['edit'] ) ) {
            $is_editing = true;
        }

        if ( $is_editing ) {
            // Loading an existing rule.
			$rule_id = isset( $_GET['edit'] ) ? absint( $_GET['edit'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only reading safe GET value of Rule id, no action performed

			// Direct query is safe because the table name is hardcoded and the value is prepared.
			$rule = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table_name} WHERE id = %d", $rule_id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.NoCaching
			
            if ( $rule ) {
                $user_role = json_decode( $rule->user_role, true ) ?? array();
                $statuses  = json_decode( $rule->statuses, true ) ?? array();
            }
        }

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

        // Show success notice.
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ( isset( $_GET['success'] ) ) {
            echo '<div class="wosr-notice-success"><span>' . esc_html__( 'Settings saved successfully!', 'order-role-manager-for-woocommerce' ) . '</span></div>';
        }

        // ---------------- Rule Form ---------------- //
        ?>
        <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
            <input type="hidden" name="action" value="<?php echo esc_attr( $is_editing ? 'wosr_update_rule_overview' : 'wosr_save_rule_overview' ); ?>">
            <?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_overview', 'wosr_nonce' ); ?>

            <table class="form-table wosr-table">
                <tr>
                    <th><label for="user_role"><?php esc_html_e( 'User Role(s)', 'order-role-manager-for-woocommerce' ); ?></label></th>
                    <th><label for="statuses"><?php esc_html_e( 'Allowed Order Status(es) (Overview)', 'order-role-manager-for-woocommerce' ); ?></label></th>
                </tr>
                <tr>
                    <td>
                        <select name="user_role[]" multiple required class="wosr_select2">
                            <?php foreach ( $user_roles as $key => $role ) : ?>
                                <?php if ( 'administrator' === $key ) continue; ?>
                                <option value="<?php echo esc_attr( $key ); ?>" <?php selected( in_array( $key, $user_role ?? array(), true ) ); ?>>
                                    <?php echo esc_html( $role['name'] ); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td>
                        <select name="statuses[]" multiple required class="wosr_select2 statuses">
                            <option value="nothing-allowed" <?php selected( in_array( 'nothing-allowed', $statuses ?? array(), true ) ); ?>>
                                <?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 ?? array(), true ) ); ?>>
                                    <?php echo esc_html( $label ); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                </tr>
            </table>

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

		<h3 class="subheader-h3">Existing Rules for User Roles</h3>
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th>User Roles</th>
                    <th>Allowed Statuses</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php 
            foreach ($rules as $rule): 
                // Get order status names
                $status_ids = json_decode($rule['statuses'], true) ?? [];
			    $status_names = array_map(function ($status) {
					if($status == "nothing-allowed"){
						return 'NO ORDER STATUS ALLOWED';
					}
					$status_name = wc_get_order_status_name($status);
					return !empty($status_name) ? $status_name : '';
			    }, $status_ids);
            	?>
                <tr>
                    
                    <?php 
				    $role_ids = json_decode($rule['user_role'], true) ?? [];
				    $role_names = array_map(function ($role_id) use ($user_roles) {
						return isset($user_roles[$role_id]['name']) ? $user_roles[$role_id]['name'] : '';
				    }, $role_ids);
                    ?>
                    <td><?php echo esc_html(implode(', ', $role_names)); ?></td>
                    
                    <td><?php echo esc_html(implode(', ', $status_names)); ?></td>
                    <td>
                        <?php $checked = ($rule['status'] === 'enabled') ? 'checked' : ''; ?>
                        <label class='switch'>
                         <input type='checkbox' class='wosr-payment-rule-toggle-overview' data-rule-id='<?php echo esc_attr($rule['id']); ?>' <?php echo esc_attr($checked); ?> >

                            <span class='slider round'></span>
                        </label>
						<a href="<?php echo esc_url( add_query_arg('edit' , esc_attr( $rule['id'] ) ) ); ?>" class="button button-primary">✏️ Edit</a>
                        <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_overview">
                            <input type="hidden" name="rule_id" value="<?php echo esc_attr($rule['id']); ?>">
                            <?php wp_nonce_field('wosr_delete_rule_overview', 'wosr_nonce'); ?>
                            <button type="submit" class="button button-secondary delete-rule-btn">❌ Delete</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>

            </tbody>
        </table>

        <h2 class="subheader-h3">Existing Rules for Individual Users</h2>
        <p class="wosr-user-table-description">
            The rules that exist here override the "Existing Rules for User Roles" above.
        </p>

        <div class="wosr-username-dummy-wrapper">
            <div class="wosr-username-dummy-overlay">
                <div>🔒</div>
                <h4>Please upgrade to unlock order restrictions for individual users.</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">Upgrade to Pro</a>
            </div>

            <table class="wp-list-table widefat fixed striped wosr-username-dummy-table">
                <thead>
                    <tr>
                        <th>Username</th>
                        <th>User Role</th>
                        <th>Allowed Statuses</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>john.doe</td>
                        <td>Shop Manager</td>
                        <td>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>on-hold, pending</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>refunded, cancelled</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>failed, on-hold</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>processing, completed</td>
                        <td>
                            <a class="button button-primary">✏️ Edit</a>
                            <button class="button button-secondary">❌ Delete</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <?php
       }

    // ---------------- CRUD + AJAX methods ---------------- //

    /**
     * Save a new order status overview rule.
     *
     * Validates nonce, capability, and ensures free version limit.
     * Stores rule in custom table.
     *
     * @return void
     */
    public function save_rule() {
        if (
            !isset($_POST['wosr_nonce']) ||
            !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['wosr_nonce'])), 'wosr_save_rule_overview')
        ) {
            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 and validate inputs
        $user_roles = WOSR_Permissions::sanitize_roles( $_POST['user_role'] ?? array() );
        $statuses   = WOSR_Permissions::sanitize_statuses( $_POST['statuses'] ?? array() );

        if (empty($user_roles) || empty($statuses)) {
            wp_safe_redirect(admin_url('admin.php?page=wosr-settings&tab=order_status_overview&error=1'));
            exit;
        }

		$table_name = $wpdb->prefix . 'wosr_order_status_overview';
		$count      = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table_name}" ); // 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 ) );
		}

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Direct query to a custom table
        $wpdb->insert(
			$table_name,
            [
                'user_role' => json_encode($user_roles),
                'statuses'  => json_encode($statuses),
            ],
            ['%s', '%s']
        );
		// Invalidate cached rules
		WOSR_Permissions::clear_request_cache();
		
        wp_safe_redirect(admin_url('admin.php?page=wosr-settings&tab=order_status_overview&success=1'));
        exit;
    }

    /**
     * Update an existing order status overview rule.
     *
     * @return void
     */
    public function update_rule() {
        if (
			! isset( $_POST['wosr_nonce'] ) ||
			! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['wosr_nonce'] ) ), 'wosr_save_rule_overview' )
		) {
			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;

		if ( isset( $_POST['user_role'], $_POST['statuses'], $_POST['rule_id'] ) ) {
			$user_role = WOSR_Permissions::sanitize_roles( $_POST['user_role'] );
			$statuses  = WOSR_Permissions::sanitize_statuses( $_POST['statuses'] );

			$rule_id = absint( $_POST['rule_id'] );
			if ( ! $rule_id || empty( $user_role ) || empty( $statuses ) ) {
				wp_die( esc_html__( 'Missing or invalid rule data.', 'order-role-manager-for-woocommerce' ), '', array( 'response' => 400 ) );
			}


		// 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_overview",
				[
					'user_role' => json_encode($user_role),
					'statuses'  => json_encode($statuses),
				],
				[ 'id' => $rule_id ]
			);

			WOSR_Permissions::clear_request_cache();
		}

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

    /**
     * Delete a rule by ID.
     *
     * @return void
     */
    public function delete_rule() {
        if (
			! isset( $_POST['wosr_nonce'] ) ||
			! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['wosr_nonce'] ) ), 'wosr_delete_rule_overview' )
		) {
			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;
		if ( isset( $_POST['rule_id'] ) ) {
			$rule_id = intval( $_POST['rule_id'] );

			// 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_overview",
				[ 'id' => $rule_id ]
			);
			WOSR_Permissions::clear_request_cache();
		}

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

    /**
     * Toggle rule enable/disable via AJAX.
     *
     * @return void
     */
    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_overview",
            ['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_Overview();
