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

/*-----------------------------------------
# Categories Tab Main - Secure Standard Style
-----------------------------------------*/
function afdp_category_tab() {
	wp_enqueue_media();

	/**
	 * 1. SANITIZATION & INPUT GATHERING
	 * Using wp_unslash() and sanitize functions clears the "Processing form data" warnings.
	 */
	$active_sub   = isset( $_GET['sub'] ) ? sanitize_text_field( wp_unslash( $_GET['sub'] ) ) : 'all';
	$current_page = 'awesome_food_delivery';
	$edit_id      = isset( $_GET['edit'] ) ? absint( $_GET['edit'] ) : 0;
	$view_id      = isset( $_GET['view'] ) ? absint( $_GET['view'] ) : 0;

	// Define sub-tabs
	$sub_tabs = [
		'all' => __( 'All Categories', 'food-delivery-pickup-soluition' ),
		'add' => ( $edit_id > 0 ) ? __( 'Edit Category', 'food-delivery-pickup-soluition' ) : __( 'Add Category', 'food-delivery-pickup-soluition' ),
	];

	/**
	 * 2. NONCE VERIFICATION (The "Security" Fix)
	 * If you have a form saving data in this tab, verify it here.
	 */
	if ( isset( $_POST['afdp_save_category_btn'] ) ) {
		if ( ! isset( $_POST['afdp_cat_nonce_field'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['afdp_cat_nonce_field'] ) ), 'afdp_save_category_action' ) ) {
			wp_die( esc_html__( 'Security check failed. Please refresh and try again.', 'food-delivery-pickup-soluition' ) );
		}
		// Logic to handle the save would go here or inside afdp_category_add_edit()
	}

	// Render the Tab Navigation
	echo '<h2 class="nav-tab-wrapper">';
	foreach ( $sub_tabs as $key => $label ) {
		$url = add_query_arg( [
			'page' => $current_page,
			'tab'  => 'categories',
			'sub'  => $key,
		], admin_url( 'admin.php' ) );

		// Logic for active class
		$is_active    = ( $active_sub === $key ) || ( 'add' === $key && $edit_id > 0 );
		$active_class = $is_active ? ' nav-tab-active' : '';

		echo '<a class="nav-tab' . esc_attr( $active_class ) . '" href="' . esc_url( $url ) . '">' . esc_html( $label ) . '</a>';
	}
	echo '</h2>';

	// 3. CONTENT AREA
	echo '<div class="fd-content-wrap" style="margin-top:20px;">';

	switch ( $active_sub ) {
		case 'add':
			// The function should handle its own form nonces internally
			afdp_category_add_edit();
			break;

		case 'view':
			if ( $view_id > 0 ) {
				afdp_category_view( $view_id );
			} else {
				echo '<div class="notice notice-error"><p>' . esc_html__( 'Invalid Category ID.', 'food-delivery-pickup-soluition' ) . '</p></div>';
				afdp_category_list();
			}
			break;

		case 'all':
		default:
			afdp_category_list();
			break;
	}

	echo '</div>';
}