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

/**
 * MASTER FILE: ADD/EDIT FOOD ITEM
 * Layout: SaaS Modern Grid (Primary Red Theme)
 * UI: S-Switch Toggles for Extras, Numeric-only Pricing
 */
function afdp_add_edit_item_tab() {
    $edit_item_id = isset($_GET['edit']) ? intval($_GET['edit']) : 0;
    $item = $edit_item_id ? get_post($edit_item_id) : null;

    /*--------------------------------------------------------------
    # 1. FORM SUBMISSION LOGIC
    --------------------------------------------------------------*/
    if (!empty($_POST) && isset($_POST['afdp_item_nonce']) && wp_verify_nonce($_POST['afdp_item_nonce'], 'afdp_save_item_action')) {
        $title  = sanitize_text_field($_POST['afdp_item_name']);
        $desc   = wp_kses_post($_POST['afdp_item_desc']);
        $price  = floatval($_POST['afdp_item_price']);
        $cat    = intval($_POST['afdp_item_cat']);
        $extras = isset($_POST['afdp_item_extras']) ? array_map('intval', $_POST['afdp_item_extras']) : [];

        $post_args = [
            'post_type'    => 'afdp_food_item',
            'post_title'   => $title,
            'post_content' => $desc,
            'post_status'  => 'publish'
        ];

        if ($item) {
            $post_args['ID'] = $edit_item_id;
            wp_update_post($post_args);
        } else {
            $edit_item_id = wp_insert_post($post_args);
        }

        if ($edit_item_id) {
            update_post_meta($edit_item_id, 'afdp_food_price', $price);
            wp_set_post_terms($edit_item_id, [$cat], 'afdp_food_category');
            update_post_meta($edit_item_id, 'afdp_item_extras', $extras);
            
            if (isset($_POST['afdp_item_image_id'])) {
                $img_id = intval($_POST['afdp_item_image_id']);
                ($img_id > 0) ? set_post_thumbnail($edit_item_id, $img_id) : delete_post_thumbnail($edit_item_id);
            }
            echo '<div class="notice notice-success is-dismissible"><p>Item saved successfully!</p></div>';
            $item = get_post($edit_item_id); 
        }
    }

    /*--------------------------------------------------------------
    # 2. DATA PREPARATION
    --------------------------------------------------------------*/
    $title_val  = $item ? $item->post_title : '';
    $desc_val   = $item ? $item->post_content : '';
    $price_val  = $item ? get_post_meta($edit_item_id, 'afdp_food_price', true) : '';
    $cat_id     = $item ? (wp_get_post_terms($edit_item_id, 'afdp_food_category', ['fields' => 'ids'])[0] ?? 0) : 0;
    $extras_sel = $item ? (get_post_meta($edit_item_id, 'afdp_item_extras', true) ?: []) : [];
    $img_id     = $item ? get_post_thumbnail_id($edit_item_id) : 0;
    $img_url    = $img_id ? wp_get_attachment_url($img_id) : '';

    $categories = get_terms(['taxonomy' => 'afdp_food_category', 'hide_empty' => false]);
    $extras_all = get_option('fd_extras', []); 
    ?>

    <style>
        :root { 
            --fd-primary: #e53935; 
            --fd-primary-dark: #b71c1c;
            --fd-border: #ccd0d4; 
            --fd-bg-lite: #f8fafc;
            --fd-text-main: #1e293b;
            --fd-text-muted: #64748b;
        }

        .afdp-editor-container { margin-top: 25px; max-width: 1200px; }
        
        /* Main Grid Layout */
        .fd-main-layout { display: grid; grid-template-columns: 1fr 360px; gap: 25px; }

        /* Card Styling */
        .fd-card { background: #fff; border: 1px solid var(--fd-border); border-radius: 12px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); margin-bottom: 25px; overflow: hidden; }
        .fd-card-header { padding: 15px 20px; border-bottom: 1px solid #f1f5f9; background: #fafafa; }
        .fd-card-header h3 { margin: 0; font-size: 13px; font-weight: 700; color: var(--fd-text-muted); text-transform: uppercase; letter-spacing: 0.5px; }
        .fd-card-body { padding: 20px; }

        /* Form Controls */
        .fd-label { display: block; margin-bottom: 8px; font-weight: 600; color: var(--fd-text-main); font-size: 14px; }
        .fd-title-input { width: 100%; border: 1px solid var(--fd-border); border-radius: 10px; font-size: 22px; font-weight: 700; padding: 15px; margin-bottom: 25px; outline: none; }
        .fd-title-input:focus { border-color: var(--fd-primary); box-shadow: 0 0 0 3px rgba(229, 57, 53, 0.1); }
        
        /* Pricing Input (No Currency) */
        .fd-numeric-input { width: 100%; padding: 12px 15px; border: 1px solid var(--fd-border); border-radius: 8px; font-size: 18px; font-weight: 700; color: var(--fd-primary); outline: none; }

        /* S-Switch Toggle Component */
        .fd-switch-item { display: flex; align-items: center; justify-content: space-between; padding: 12px; border: 1px solid #f1f5f9; border-radius: 8px; margin-bottom: 10px; transition: 0.2s; }
        .fd-switch-item:hover { background: var(--fd-bg-lite); border-color: #e2e8f0; }
        
        .fd-s-switch { position: relative; display: inline-block; width: 42px; height: 22px; }
        .fd-s-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: 34px; }
        .fd-slider:before { position: absolute; content: ""; height: 16px; width: 16px; left: 3px; bottom: 3px; background-color: white; transition: .3s; border-radius: 50%; }
        input:checked + .fd-slider { background-color: var(--fd-primary); }
        input:checked + .fd-slider:before { transform: translateX(20px); }

        /* Image Uploader */
        .fd-image-dropzone { border: 2px dashed var(--fd-border); border-radius: 12px; padding: 30px; text-align: center; cursor: pointer; background: var(--fd-bg-lite); transition: 0.3s; }
        .fd-image-dropzone:hover { border-color: var(--fd-primary); background: #fff; }
        .fd-image-dropzone img { max-width: 100%; border-radius: 8px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); }

        /* Sticky Bottom Bar */
        .fd-action-bar { position: sticky; bottom: 20px; background: #fff; padding: 15px 25px; border-radius: 12px; border: 1px solid var(--fd-border); display: flex; justify-content: space-between; align-items: center; box-shadow: 0 -10px 25px rgba(0,0,0,0.05); margin-top: 30px; }
        .btn-fd-main { background: var(--fd-primary); color: #fff; border: none; padding: 12px 28px; border-radius: 8px; font-weight: 700; cursor: pointer; font-size: 14px; transition: 0.2s; }
        .btn-fd-main:hover { background: var(--fd-primary-dark); transform: translateY(-1px); }
    </style>

    <div class="wrap afdp-editor-container">
        <form method="post">
            <?php wp_nonce_field('afdp_save_item_action', 'afdp_item_nonce'); ?>
            
            <label class="fd-label">Menu Item Name</label>
            <input type="text" name="afdp_item_name" class="fd-title-input" placeholder="e.g. Classic Beef Burger" value="<?php echo esc_attr($title_val); ?>" required>

            <div class="fd-main-layout">
                <div class="fd-col-left">
                    <div class="fd-card">
                        <div class="fd-card-header"><h3>Description</h3></div>
                        <div class="fd-card-body" style="padding:10px;">
                            <?php wp_editor($desc_val, 'afdp_item_desc', [
                                'textarea_rows' => 12, 
                                'media_buttons' => false,
                                'tinymce' => array(
                                    'toolbar1' => 'bold,italic,underline,separator,bullist,numlist,separator,link,unlink',
                                )
                            ]); ?>
                        </div>
                    </div>

                    <div class="fd-card">
                        <div class="fd-card-header"><h3>Customization & Extras</h3></div>
                        <div class="fd-card-body">
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                <?php if($extras_all): foreach($extras_all as $id => $ex): 
                                    $checked = in_array($id, $extras_sel) ? 'checked' : '';
                                ?>
                                    <div class="fd-switch-item">
                                        <div>
                                            <div style="font-weight:700; font-size:13px; color:var(--fd-text-main);"><?php echo esc_html($ex['name']); ?></div>
                                            <div style="color:var(--fd-primary); font-size:11px; font-weight:800;">+<?php echo number_format($ex['price'], 2); ?></div>
                                        </div>
                                        <label class="fd-s-switch">
                                            <input type="checkbox" name="afdp_item_extras[]" value="<?php echo esc_attr($id); ?>" <?php echo esc_attr($checked); ?>>
                                            <span class="fd-slider"></span>
                                        </label>
                                    </div>
                                <?php endforeach; else: ?>
                                    <p style="color:var(--fd-text-muted); font-style:italic;">No extras found in database.</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="fd-col-right">
                    <div class="fd-card">
                        <div class="fd-card-header"><h3>Pricing & Category</h3></div>
                        <div class="fd-card-body">
                            <div style="margin-bottom: 20px;">
                                <label class="fd-label">Base Price</label>
                                <input type="number" step="0.01" name="afdp_item_price" class="fd-numeric-input" value="<?php echo esc_attr($price_val); ?>" placeholder="0.00">
                            </div>

                            <div>
                                <label class="fd-label">Category</label>
                                <select name="afdp_item_cat" style="width:100%; padding:10px; border-radius:8px; border-color:var(--fd-border);">
                                    <?php foreach($categories as $c): ?>
                                        <option value="<?php echo esc_attr($c->term_id); ?>" <?php selected($cat_id, $c->term_id); ?>><?php echo esc_html($c->name); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="fd-card">
                        <div class="fd-card-header"><h3>Featured Photo</h3></div>
                        <div class="fd-card-body">
                            <input type="hidden" name="afdp_item_image_id" id="afdp_item_image_id" value="<?php echo esc_attr($img_id); ?>">
                            <div id="afdp_image_trigger" class="fd-image-dropzone">
                                <?php if($img_url): ?>
                                    <img src="<?php echo esc_url($img_url); ?>">
                                    <p style="margin-top:10px; font-size:11px; color:var(--fd-primary); font-weight:700;">Click to Replace</p>
                                <?php else: ?>
                                    <span class="dashicons dashicons-format-image" style="font-size:48px; width:48px; height:48px; color:#cbd5e1;"></span>
                                    <p style="margin-top:10px; color:var(--fd-text-muted); font-size:13px;">Upload Image</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="fd-action-bar">
                <div style="color:var(--fd-text-muted); font-size:13px;">
                    <span class="dashicons dashicons-admin-tools" style="font-size:18px; margin-right:5px;"></span>
                    Toggle "Extras" to allow customers to add them to this item.
                </div>
                <div style="display:flex; gap:15px; align-items:center;">
                    <a href="?page=awesome_food_delivery&tab=items" style="text-decoration:none; color:var(--fd-text-muted); font-weight:600;">Discard</a>
                    <button type="submit" class="btn-fd-main">Save Menu Item</button>
                </div>
            </div>
        </form>
    </div>

    <script>
    jQuery(document).ready(function($){
        var afdp_media_frame;
        $('#afdp_image_trigger').on('click', function(e){
            e.preventDefault();
            if(afdp_media_frame){ afdp_media_frame.open(); return; }
            afdp_media_frame = wp.media({ title: 'Select Food Photo', multiple: false });
            afdp_media_frame.on('select', function(){
                var attachment = afdp_media_frame.state().get('selection').first().toJSON();
                $('#afdp_item_image_id').val(attachment.id);
                $('#afdp_image_trigger').html('<img src="'+attachment.url+'"><p style="margin-top:10px; font-size:11px; color:var(--fd-primary); font-weight:700;">Click to Replace</p>');
            });
            afdp_media_frame.open();
        });
    });
    </script>
    <?php
}