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

/**
 * Handle Menu Item Deletion
 */
add_action('admin_post_afdp_delete_item', 'afdp_delete_item');

function afdp_delete_item() {
    // 1. Capability & Security Check
    if (!current_user_can('manage_options')) {
        wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'food-delivery-pickup-soluition' ) );
    }

    $item_id = isset($_GET['item']) ? intval($_GET['item']) : 0;
    $nonce   = isset($_GET['_wpnonce']) ? $_GET['_wpnonce'] : '';

    // 2. Nonce Verification
    if (!$item_id || !wp_verify_nonce($nonce, 'afdp_delete_item_' . $item_id)) {
        wp_die( esc_html__( 'Security check failed. Please try again.', 'food-delivery-pickup-soluition' ) );
    }

    // 3. Verify it's actually our post type before deleting
    $post = get_post($item_id);
    if ($post && $post->post_type === 'afdp_food_item') {
        // Use true to bypass trash for a snappier SaaS feel, or false to keep in trash
        wp_delete_post($item_id, true);
        
        // 4. Redirect with a success flag
        $redirect_url = add_query_arg([
            'page'    => 'awesome_food_delivery',
            'tab'     => 'items',
            'sub'     => 'all',
            'deleted' => '1'
        ], admin_url('admin.php'));
        
        wp_safe_redirect( $redirect_url );
exit;
    } else {
        wp_die( esc_html__( 'Invalid item or item already deleted.', 'food-delivery-pickup-soluition' ) );
    }
}