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

/**
 * Add / Edit Extra - Updated with Dynamic Currency Support
 */
function afdp_add_extra_tab() {
    // 1. VALIDATE AND SANITIZE GET DATA
    $afon_edit_id   = isset($_GET['edit']) ? absint(wp_unslash($_GET['edit'])) : null;
    $afon_extras    = get_option('fd_extras', []);
    $afon_edit_item = ($afon_edit_id !== null && isset($afon_extras[$afon_edit_id])) ? $afon_extras[$afon_edit_id] : null;

    // --- 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] : '$';

    // --- FORM SUBMISSION LOGIC ---
    $request_method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : '';

    if ($request_method === 'POST' && isset($_POST['afon_extra_nonce'])) {
        if (wp_verify_nonce(sanitize_key(wp_unslash($_POST['afon_extra_nonce'])), 'afon_save_extra')) {
            
            $afon_name    = isset($_POST['afon_extra_name']) ? sanitize_text_field(wp_unslash($_POST['afon_extra_name'])) : '';
            $afon_file_id = isset($_POST['afon_extra_file']) ? absint(wp_unslash($_POST['afon_extra_file'])) : 0;
            $afon_price   = isset($_POST['afon_extra_price']) ? floatval(wp_unslash($_POST['afon_extra_price'])) : 0;
            $afon_qty     = isset($_POST['afon_extra_qty']) ? intval(wp_unslash($_POST['afon_extra_qty'])) : 0;
            $current_id   = (isset($_POST['afon_edit_id']) && $_POST['afon_edit_id'] !== '') ? intval(wp_unslash($_POST['afon_edit_id'])) : null;

            $afon_new_entry = [
                'name'     => $afon_name,
                'file_id'  => $afon_file_id,
                'price'    => $afon_price,
                'quantity' => $afon_qty
            ];

            if ($current_id !== null) {
                $afon_extras[$current_id] = $afon_new_entry;
                echo '<div class="notice notice-success is-dismissible" style="border-left-color: #e53935;"><p>Extra topping updated.</p></div>';
            } else {
                $afon_extras[] = $afon_new_entry;
                echo '<div class="notice notice-success is-dismissible" style="border-left-color: #e53935;"><p>New extra topping created.</p></div>';
            }

            update_option('fd_extras', $afon_extras);
            $afon_edit_item = $afon_new_entry;
            $afon_edit_id   = $current_id; 
        }
    }

    $afon_img_id  = isset($afon_edit_item['file_id']) ? absint($afon_edit_item['file_id']) : 0;
    $afon_img_url = $afon_img_id ? wp_get_attachment_url($afon_img_id) : '';
    ?>

    <style>
        :root { 
            --fd-primary: #e53935; 
            --fd-primary-hover: #c62828;
            --fd-border: #ccd0d4; 
            --fd-text: #1d2327;
            --fd-muted: #64748b;
        }
        
        .afdp-item-editor { margin-top: 20px; max-width: 1100px; }
        .fd-main-label { display: block; margin-bottom: 8px; font-weight: 600; color: var(--fd-text); font-size: 14px; }
        .fd-title-input { 
            width: 100%; border: 1px solid var(--fd-border); border-radius: 10px;
            font-size: 20px; font-weight: 700; padding: 15px; outline: none; 
            transition: 0.2s; margin-bottom: 25px; background: #fff; box-sizing: border-box;
        }
        .fd-title-input:focus { border-color: var(--fd-primary); box-shadow: 0 0 0 3px rgba(229, 57, 53, 0.1); }
        .fd-grid-wrapper { display: grid; grid-template-columns: 1fr 340px; gap: 25px; }
        .fd-card { background: #fff; border: 1px solid var(--fd-border); border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); margin-bottom: 25px; overflow: hidden; }
        .fd-card-head { padding: 15px 20px; border-bottom: 1px solid #f0f0f1; background: #fafafa; }
        .fd-card-head h3 { margin: 0; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; color: var(--fd-muted); }
        .fd-card-body { padding: 20px; }
        .fd-price-group { position: relative; display: flex; align-items: center; }
        .fd-price-symbol { position: absolute; left: 15px; font-weight: 700; color: var(--fd-primary); font-size: 18px; }
        .fd-price-input { width: 100%; padding: 12px 12px 12px 35px; border: 1px solid var(--fd-border); border-radius: 8px; font-size: 18px; font-weight: 700; outline: none; }
        .fd-image-zone { text-align: center; border: 2px dashed var(--fd-border); padding: 30px; border-radius: 12px; cursor: pointer; background: #fcfcfc; transition: 0.3s; }
        .fd-image-zone:hover { border-color: var(--fd-primary); background: #fff5f5; }
        .fd-image-zone img { border-radius: 8px; max-width: 100px; height: auto; box-shadow: 0 4px 10px rgba(0,0,0,0.1); }
        .fd-bottom-bar { 
            position: sticky; bottom: 20px; z-index: 99; background: #fff; 
            padding: 15px 25px; border-radius: 12px; display: flex; justify-content: space-between; 
            align-items: center; box-shadow: 0 -5px 25px rgba(0,0,0,0.08); border: 1px solid var(--fd-border); margin-top: 40px; 
        }
        .btn-fd { 
            display: inline-flex; align-items: center; gap: 8px; padding: 10px 24px; 
            border-radius: 8px; font-size: 14px; font-weight: 600; text-decoration: none; 
            transition: 0.2s; cursor: pointer; border: 1px solid transparent;
        }
        .btn-primary-fd { background: var(--fd-primary); color: #fff; border-color: var(--fd-primary); }
        .btn-primary-fd:hover { background: var(--fd-primary-hover); }
        .btn-outline-fd { color: var(--fd-muted); border-color: var(--fd-border); background: #fff; }
        .btn-outline-fd:hover { background: #f8f9fa; color: var(--fd-text); }
    </style>

    <div class="wrap afdp-item-editor">
        <form method="post" id="fd-extra-edit-form">
            <?php wp_nonce_field('afon_save_extra', 'afon_extra_nonce'); ?>
            <input type="hidden" name="afon_edit_id" value="<?php echo esc_attr($afon_edit_id); ?>">
            
            <label class="fd-main-label">Topping Name</label>
            <input type="text" name="afon_extra_name" class="fd-title-input" placeholder="e.g. Extra Mozzarella" value="<?php echo esc_attr($afon_edit_item['name'] ?? ''); ?>" required>

            <div class="fd-grid-wrapper">
                <div class="fd-primary-col">
                    <div class="fd-card">
                        <div class="fd-card-head"><h3>Topping Icon</h3></div>
                        <div class="fd-card-body">
                            <input type="hidden" name="afon_extra_file" id="afon_extra_file_id" value="<?php echo esc_attr($afon_img_id); ?>">
                            <div id="afon_image_container" class="fd-image-zone">
                                <div id="afon_image_preview">
                                    <?php if ($afon_img_url): ?>
                                        <img src="<?php echo esc_url($afon_img_url); ?>">
                                        <p style="margin-top:10px; color: var(--fd-primary); font-weight:600; font-size:12px;">Change Icon</p>
                                    <?php else: ?>
                                        <span class="dashicons dashicons-insert" style="font-size: 40px; width:40px; height:40px; color: #ccd0d4;"></span>
                                        <p style="margin: 10px 0 0; color: var(--fd-muted); font-size:13px;">Click to select icon</p>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <button type="button" id="afon_remove_img" class="btn-fd" style="width:100%; justify-content:center; color:#e53935; border:none; background:none; font-size:12px; display:<?php echo $afon_img_url ? 'flex' : 'none'; ?>;">Remove Icon</button>
                        </div>
                    </div>
                </div>

                <div class="fd-sidebar-col">
                    <div class="fd-card">
                        <div class="fd-card-head"><h3>Configuration</h3></div>
                        <div class="fd-card-body">
                            <label class="fd-main-label">Price (+)</label>
                            <div class="fd-price-group" style="margin-bottom:20px;">
                                <span class="fd-price-symbol"><?php echo esc_html( $currency ); ?></span>
                                <input type="number" step="0.01" name="afon_extra_price" class="fd-price-input" value="<?php echo esc_attr($afon_edit_item['price'] ?? 0); ?>" placeholder="0.00" required>
                            </div>

                            <label class="fd-main-label">Inventory Level</label>
                            <input type="number" min="0" name="afon_extra_qty" class="fd-select" value="<?php echo esc_attr($afon_edit_item['quantity'] ?? 0); ?>" required style="height: 45px; font-weight: 600; width: 100%; border: 1px solid var(--fd-border); border-radius: 8px; padding: 0 10px;">
                        </div>
                    </div>

                    <div class="fd-card">
                        <div class="fd-card-head"><h3>Summary</h3></div>
                        <div class="fd-card-body">
                            <div style="display: flex; justify-content: space-between; font-size: 13px; margin-bottom: 8px;">
                                <span style="color: var(--fd-muted);">Availability:</span>
                                <strong style="color: <?php echo ($afon_edit_item['quantity'] ?? 0) > 0 ? '#2e7d32' : '#e53935'; ?>">
                                    <?php echo ($afon_edit_item['quantity'] ?? 0) > 0 ? 'Available' : 'Out of Stock'; ?>
                                </strong>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="fd-bottom-bar">
                <div style="font-size:13px; color: var(--fd-muted); font-weight: 500;">
                    <span class="dashicons dashicons-admin-settings" style="vertical-align: middle;"></span> 
                    Global Resource Configuration
                </div>
                <div style="display: flex; gap: 12px;">
                    <a href="<?php echo esc_url(admin_url('admin.php?page=awesome_food_delivery&tab=extras')); ?>" class="btn-fd btn-outline-fd">Cancel</a>
                    <button type="submit" class="btn-fd btn-primary-fd">
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path><polyline points="17 21 17 13 7 13 7 21"></polyline><polyline points="7 3 7 8 15 8"></polyline></svg>
                        <?php echo $afon_edit_id !== null ? 'Update Resource' : 'Save Topping'; ?>
                    </button>
                </div>
            </div>
        </form>
    </div>

    <script>
    jQuery(document).ready(function($){
        var frame;
        $('#afon_image_container').on('click', function(e){
            e.preventDefault();
            if (frame) { frame.open(); return; }
            frame = wp.media({
                title: 'Select Topping Icon',
                button: { text: 'Use this Icon' },
                multiple: false
            });
            frame.on('select', function(){
                var attachment = frame.state().get('selection').first().toJSON();
                $('#afon_extra_file_id').val(attachment.id);
                $('#afon_image_preview').html('<img src="'+attachment.url+'"><p style="margin-top:10px; color: var(--fd-primary); font-weight:600; font-size:12px;">Change Icon</p>');
                $('#afon_remove_img').show();
            });
            frame.open();
        });

        $('#afon_remove_img').on('click', function(e){
            e.preventDefault();
            $('#afon_extra_file_id').val('0');
            $('#afon_image_preview').html('<span class="dashicons dashicons-insert" style="font-size:40px; width:40px; height:40px; color:#ccd0d4;"></span><p style="margin:10px 0 0; color:var(--fd-muted); font-size:13px;">Click to select icon</p>');
            $(this).hide();
        });
    });
    </script>
    <?php
}