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

/**
 * Items Tab Controller - SaaS Style
 */
function afdp_items_tab(){
    wp_enqueue_media(); // Required for food images

    // Determine active sub-tab
    $sub = isset($_GET['sub']) ? sanitize_text_field($_GET['sub']) : 'all';
    $current_page = 'awesome_food_delivery';

    $tabs = [
        'all' => 'All Items',
        'add' => 'Add New Item',
    ];

    echo '<h2 class="nav-tab-wrapper">';
    foreach($tabs as $k => $label){
        $url = add_query_arg([
            'page' => $current_page,
            'tab'  => 'items',
            'sub'  => $k
        ], admin_url('admin.php'));

        // Keep 'Add' tab active if we are currently editing
        $is_active = ($sub === $k) || ($k === 'add' && isset($_GET['edit']));
        $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>';

    echo '<div class="fd-content-wrap" style="margin-top:20px;">';

    // Switch content based on sub-tab
    switch ($sub) {
        case 'add':
            // Logic for Add or Edit (handles internally via $_GET['edit'])
            afdp_add_edit_item_tab();
            break;

        case 'view':
            $item_id = isset($_GET['item']) ? intval($_GET['item']) : 0;
            if ($item_id > 0) {
                afdp_view_item_tab($item_id);
            } else {
                echo '<div class="notice notice-error"><p>Invalid Item ID.</p></div>';
                afdp_items_list();
            }
            break;

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

    echo '</div>';
}