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

/**
 * 1. ENQUEUE DATATABLES
 */
add_action('admin_enqueue_scripts', function($hook) {
    if (strpos($hook, 'awesome_food_delivery') === false) return;
    
    wp_enqueue_style('datatables-css', 'https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css');
    wp_enqueue_script('datatables-js', 'https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js', array('jquery'), null, true);
});

/**
 * 2. AJAX HANDLER (Must be defined for the live switch to work)
 */
add_action('wp_ajax_afdp_toggle_featured', function() {
    check_ajax_referer('afdp_featured_nonce', 'nonce');

    $post_id  = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
    $featured = isset($_POST['featured']) ? sanitize_text_field($_POST['featured']) : 'no';

    if ($post_id) {
        update_post_meta($post_id, 'afdp_item_featured', $featured);
        wp_send_json_success('Updated');
    }
    wp_send_json_error('Failed');
});

/**
 * 3. ITEMS LIST TABLE - Full UI with Live Switch
 */
function afdp_items_list() {
    // --- DYNAMIC CURRENCY LOGIC ---
    $currency_code = get_option('afdp_currency', 'USD');
    $symbols = [
        'USD'=>'$', 'GBP'=>'£', 'EUR'=>'€', 'INR'=>'₹', 
        'AED'=>'د.إ', 'BDT'=>'৳', 'CAD'=>'C$', 'SAR'=>'SR'
    ];
    $currency = isset($symbols[$currency_code]) ? $symbols[$currency_code] : '$';

    $items = get_posts([
        'post_type'   => 'afdp_food_item', 
        'numberposts' => -1, 
        'orderby'     => 'ID',
        'order'       => 'DESC',
        'post_status' => 'any'
    ]);
    ?>

    <style>
        :root { 
            --fd-primary: #e53935; 
            --fd-primary-hover: #c62828;
            --fd-border: #ccd0d4; 
            --fd-text: #1d2327;
            --fd-muted: #64748b;
            --fd-success: #10b981;
        }

        .afdp-dashboard { margin-top: 15px; max-width: 1200px; font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif; }
        #fd-items-table-container { 
            background: #fff; border: 1px solid var(--fd-border); border-radius: 12px; 
            overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.05); padding-bottom: 20px;
        }
        #fd-items-table { border: none !important; width: 100% !important; margin: 0 !important; border-collapse: collapse; }
        #fd-items-table thead th { 
            background: #f8f9fa; padding: 16px; font-weight: 700; color: var(--fd-muted); 
            border-bottom: 2px solid #f0f0f1; text-transform: uppercase; font-size: 11px; text-align: left; 
        }
        #fd-items-table td { padding: 14px 16px; vertical-align: middle; border-bottom: 1px solid #f0f0f1; }
        
        /* LIVE SWITCH STYLING */
        .fd-switch { position: relative; display: inline-block; width: 38px; height: 20px; }
        .fd-switch input { opacity: 0; width: 0; height: 0; }
        .fd-slider {
            position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0;
            background-color: #cbd5e1; transition: .3s; border-radius: 24px;
        }
        .fd-slider:before {
            position: absolute; content: ""; height: 14px; width: 14px; left: 3px; bottom: 3px;
            background-color: white; transition: .3s; border-radius: 50%;
        }
        input:checked + .fd-slider { background-color: var(--fd-success); }
        input:checked + .fd-slider:before { transform: translateX(18px); }

        .fd-badge { display: inline-block; padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: 700; margin: 2px; border: 1px solid transparent; }
        .fd-cat-badge { background: #fff5f5; color: var(--fd-primary); border: 1px solid #fecaca; }
        .btn-fd { 
            display: inline-flex; align-items: center; gap: 6px; padding: 7px 12px; 
            border-radius: 6px; font-size: 12px; font-weight: 600; text-decoration: none; 
            transition: 0.2s; cursor: pointer; border: 1px solid transparent;
        }
        .btn-fd svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2.5; }
        .btn-view-fd { color: #475569; border-color: #cbd5e1; background: #fff; }
        .btn-view-fd:hover { background: #f1f5f9; color: #1e293b; }
        .btn-edit-fd { color: var(--fd-primary); border-color: var(--fd-primary); background: transparent; }
        .btn-edit-fd:hover { background: var(--fd-primary); color: #fff; }
        .btn-delete-fd { color: #fff; background: var(--fd-primary); border-color: var(--fd-primary); }
        .btn-delete-fd:hover { background: var(--fd-primary-hover); }
        .fd-item-img { border-radius: 8px; border: 1px solid #eee; object-fit: cover; width: 44px; height: 44px; display: block; }
        .fd-no-img { width: 44px; height: 44px; border-radius: 8px; background: #f8f9fa; display: flex; align-items: center; justify-content: center; color: #cbd5e1; border: 1px solid #eee; }
        .dataTables_wrapper .dataTables_filter { float: left; padding: 20px; width: 100%; box-sizing: border-box; }
        .dataTables_wrapper .dataTables_filter input { 
            border: 1px solid var(--fd-border); border-radius: 8px; padding: 10px 15px; 
            width: 320px; background: #fff; font-size: 14px; outline: none;
        }
        .dataTables_wrapper .dataTables_paginate { padding: 20px; }
        .dataTables_wrapper .dataTables_info { padding: 20px; color: var(--fd-muted); font-size: 13px; }
    </style>

    <div class="wrap afdp-dashboard">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
            <h1 style="font-weight: 800; font-size: 26px; margin:0;">Food Menu Items</h1>
            <a href="?page=awesome_food_delivery&tab=items&sub=add" class="btn-fd" style="background:var(--fd-primary); color:#fff; padding: 12px 24px; border-radius: 8px; font-size: 14px;">+ Add New Item</a>
        </div>

        <div id="fd-items-table-container">
            <table id="fd-items-table">
                <thead>
                    <tr>
                        <th width="60">Photo</th>
                        <th>Item Details</th>
                        <th>Category</th>
                        <th width="80">Featured</th>
                        <th width="120">Price</th>
                        <th width="260" style="text-align: right;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if($items): 
                        foreach($items as $item):
                            $price       = get_post_meta($item->ID, 'afdp_food_price', true); 
                            $is_featured = get_post_meta($item->ID, 'afdp_item_featured', true);
                            $cats        = wp_get_post_terms($item->ID, 'afdp_food_category'); 
                            
                            $view_url = "?page=awesome_food_delivery&tab=items&sub=view&item=" . $item->ID;
                            $edit_url = "?page=awesome_food_delivery&tab=items&sub=add&edit=" . $item->ID;
                            $del_url  = wp_nonce_url(admin_url('admin-post.php?action=afdp_delete_item&item='.$item->ID), 'afdp_delete_item_'.$item->ID);
                    ?>
                        <tr>
                            <td>
                                <?php if (has_post_thumbnail($item->ID)): ?>
                                    <?php echo get_the_post_thumbnail($item->ID, [44, 44], ['class' => 'fd-item-img']); ?>
                                <?php else: ?>
                                    <div class="fd-no-img"><span class="dashicons dashicons-food"></span></div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div style="font-weight: 700; font-size: 15px; color: var(--fd-text);"><?php echo esc_html($item->post_title); ?></div>
                                <div style="color: var(--fd-muted); font-size: 11px; margin-top: 2px;">ID: #<?php echo esc_attr($item->ID); ?></div>
                            </td>
                            <td>
                                <?php if($cats): foreach($cats as $c): ?>
                                    <span class="fd-badge fd-cat-badge"><?php echo esc_html($c->name); ?></span>
                                <?php endforeach; else: echo '<span style="color:#cbd5e1;">—</span>'; endif; ?>
                            </td>
                            <td>
                                <label class="fd-switch">
                                    <input type="checkbox" 
       class="featured-toggle" 
       data-id="<?php echo esc_attr( $item->ID ); ?>" 
       <?php checked( $is_featured, 'yes' ); ?>>
<span class="fd-slider"></span>
                                </label>
                            </td>
                            <td>
                                <strong style="font-size:15px; color: var(--fd-primary);">
                                    <?php echo esc_html( $currency ); ?><?php echo esc_html( number_format( floatval( $price ), 2 ) ); ?>
                                </strong>
                            </td>
                            <td>
                                <div style="display: flex; gap: 8px; justify-content: flex-end;">
                                    <a class="btn-fd btn-view-fd" href="<?php echo esc_url($view_url); ?>">
                                        <svg viewBox="0 0 24 24"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                                        View
                                    </a>
                                    <a class="btn-fd btn-edit-fd" href="<?php echo esc_url($edit_url); ?>">
                                        <svg viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4L18.5 2.5z"></path></svg>
                                        Edit
                                    </a>
                                    <a class="btn-fd btn-delete-fd" onclick="return confirm('Permanently delete this item?')" href="<?php echo esc_url($del_url); ?>">
                                        <svg viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <script>
    jQuery(document).ready(function($){
        // Initialize DataTables
        if ($.fn.DataTable) {
            $('#fd-items-table').DataTable({
                "pageLength": 10,
                "responsive": true,
                "order": [[1, "asc"]],
                "language": {
                    "search": "",
                    "searchPlaceholder": "Search menu...",
                    "paginate": { "next": "Next", "previous": "Prev" }
                },
                "dom": '<"top"f>rt<"bottom"ip><"clear">',
                "columnDefs": [
                    { "orderable": false, "targets": [0, 3, 5] } 
                ]
            });
        }

        // Live AJAX Toggle
        $(document).on('change', '.featured-toggle', function() {
            var item_id = $(this).data('id');
            var is_checked = $(this).is(':checked') ? 'yes' : 'no';
            var $slider = $(this).next('.fd-slider');

            $slider.css('opacity', '0.5');

            $.post(ajaxurl, {
                action: 'afdp_toggle_featured',
                post_id: item_id,
                featured: is_checked,
                nonce: '<?php echo esc_js( wp_create_nonce( "afdp_featured_nonce" ) ); ?>'
            }, function(response) {
                $slider.css('opacity', '1');
            });
        });
    });
    </script>
    <?php
}