<?php $pageTitle = Lang::get('edit_coin') . ' - ' . Lang::get('app_name'); ?>
<?php require APP_ROOT . '/views/layouts/header.php'; ?>

<div class="max-w-3xl mx-auto">
    <div class="flex items-center justify-between mb-6">
        <h1 class="text-2xl font-bold"><?= Lang::get('edit_coin') ?></h1>
        <div class="flex items-center gap-3">
                        <a href="<?= APP_URL ?>/subcollections/<?= $coin['subcollection_id'] ?>" class="text-gray-500 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 text-sm transition-colors">
                &larr; <?= htmlspecialchars($coin['subcollection_name']) ?>
            </a>
        </div>
    </div>

    <form method="POST" action="<?= APP_URL ?>/coins/<?= $coin['id'] ?>" enctype="multipart/form-data">
        <input type="hidden" name="csrf_token" value="<?= Session::getCsrfToken() ?>">
        <input type="hidden" name="view" value="<?= htmlspecialchars($_GET['view'] ?? 'grid') ?>">

        <!-- Images -->
        <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 mb-6">
            <h2 class="text-lg font-semibold mb-4"><?= Lang::get('image_obverse') ?> / <?= Lang::get('image_reverse') ?></h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label for="image_obverse" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('image_obverse') ?></label>
                    <div class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-4 text-center hover:border-primary-400 dark:hover:border-primary-500 transition-colors cursor-pointer" onclick="document.getElementById('image_obverse').click()">
                        <img id="preview_obverse" src="<?= $coin['image_obverse'] ? APP_URL . '/uploads/items/' . htmlspecialchars($coin['image_obverse']) : APP_URL . '/images/placeholder-coin.svg' ?>" class="<?= $coin['image_obverse'] ? '' : 'opacity-50' ?> w-full h-40 object-contain rounded-lg mb-2">
                        <div id="placeholder_obverse" class="<?= $coin['image_obverse'] ? 'hidden' : '' ?>">
                            <p class="text-sm text-gray-500 dark:text-gray-400"><?= Lang::get('upload') ?> <?= Lang::get('image_obverse') ?></p>
                        </div>
                    </div>
                    <input type="file" id="image_obverse" name="image_obverse" accept="image/*" class="hidden" onchange="previewImage(this, 'preview_obverse', 'placeholder_obverse')">
                    <input type="hidden" id="numista_image_obverse" name="numista_image_obverse" value="">
                </div>
                <div>
                    <label for="image_reverse" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('image_reverse') ?></label>
                    <div class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-4 text-center hover:border-primary-400 dark:hover:border-primary-500 transition-colors cursor-pointer" onclick="document.getElementById('image_reverse').click()">
                        <img id="preview_reverse" src="<?= $coin['image_reverse'] ? APP_URL . '/uploads/items/' . htmlspecialchars($coin['image_reverse']) : APP_URL . '/images/placeholder-coin.svg' ?>" class="<?= $coin['image_reverse'] ? '' : 'opacity-50' ?> w-full h-40 object-contain rounded-lg mb-2">
                        <div id="placeholder_reverse" class="<?= $coin['image_reverse'] ? 'hidden' : '' ?>">
                            <p class="text-sm text-gray-500 dark:text-gray-400"><?= Lang::get('upload') ?> <?= Lang::get('image_reverse') ?></p>
                        </div>
                    </div>
                    <input type="file" id="image_reverse" name="image_reverse" accept="image/*" class="hidden" onchange="previewImage(this, 'preview_reverse', 'placeholder_reverse')">
                    <input type="hidden" id="numista_image_reverse" name="numista_image_reverse" value="">
                </div>
            </div>
        </div>

        <!-- Additional Images -->
        <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 mb-6">
            <h2 class="text-lg font-semibold mb-4"><?= Lang::get('additional_images') ?></h2>
            <?php if (!empty($additionalImages)): ?>
            <div id="existingImages" class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3 mb-4">
                <?php foreach ($additionalImages as $img): ?>
                <div class="relative group" data-image-id="<?= $img['id'] ?>">
                    <img src="<?= APP_URL ?>/uploads/items/<?= htmlspecialchars($img['filename']) ?>" class="w-full h-28 object-cover rounded-lg border border-gray-200 dark:border-gray-600">
                    <button type="button" onclick="markImageForDeletion(this, <?= $img['id'] ?>)" class="absolute top-1 right-1 w-6 h-6 bg-red-500 hover:bg-red-600 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity btn-gradient btn-gradient-red" title="<?= Lang::get('remove') ?>">
                        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                    </button>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
            <div id="dropZone" class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-8 text-center hover:border-primary-400 dark:hover:border-primary-500 transition-colors cursor-pointer">
                <svg class="w-12 h-12 mx-auto text-gray-400 dark:text-gray-500 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/></svg>
                <p class="text-sm text-gray-500 dark:text-gray-400 mb-1"><?= Lang::get('drag_drop_images') ?></p>
                <p class="text-xs text-gray-400 dark:text-gray-500"><?= Lang::get('or_click_to_browse') ?></p>
            </div>
            <input type="file" id="additionalImagesInput" name="additional_images[]" accept="image/*" multiple class="hidden">
            <div id="additionalPreviews" class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3 mt-4"></div>
            <div id="deleteImagesContainer"></div>
        </div>

        <!-- Numista Integration -->
        <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 mb-6">
            <h2 class="text-lg font-semibold mb-4"><?= Lang::get('numista_search') ?></h2>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                <div>
                    <label for="numista_country" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('country') ?></label>
                    <select id="numista_country" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                        <option value="">-</option>
                    </select>
                </div>
                <div>
                    <label for="numista_year" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('year') ?></label>
                    <input type="text" id="numista_year" placeholder="<?= htmlspecialchars(Lang::get('numista_year_placeholder')) ?>" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                </div>
                <div>
                    <label for="numista_value" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('value') ?></label>
                    <input type="text" id="numista_value" placeholder="<?= htmlspecialchars(Lang::get('numista_coin_value_placeholder')) ?>" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                </div>
            </div>
            <button type="button" id="searchNumista" data-type="coin" class="btn-gradient btn-gradient-blue btn-gradient-icon">
                <?= Lang::get('search_numista') ?>
            </button>
            <div id="numistaResults" class="mt-4 hidden">
                <!-- Search results will appear here -->
            </div>
            <div id="numistaLoading" class="mt-4 hidden">
                <div class="flex items-center text-gray-500 dark:text-gray-400">
                    <svg class="animate-spin h-5 w-5 mr-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <?= Lang::get('numista_search_loading') ?>
                </div>
            </div>
            <div id="numistaError" class="mt-4 hidden">
                <div class="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 text-red-700 dark:text-red-300">
                    <p id="numistaErrorMessage"></p>
                </div>
            </div>
        </div>

        <!-- Osnovni podaci -->
        <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 mb-6">
            <h2 class="text-lg font-semibold mb-4"><?= Lang::get('basic_data') ?></h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <div>
                    <label for="country" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('country') ?></label>
                    <input type="text" id="country" name="country" value="<?= htmlspecialchars($coin['country'] ?? '') ?>"
                           class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                </div>
                <div>
                    <label for="year_minted" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('year_minted') ?></label>
                    <input type="text" id="year_minted" name="year_minted" value="<?= htmlspecialchars($coin['year_minted'] ?? '') ?>"
                           class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                </div>
                <div>
                    <label for="nominal_value" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('nominal_value') ?></label>
                    <input type="text" id="nominal_value" name="nominal_value" value="<?= htmlspecialchars($coin['nominal_value'] ?? '') ?>"
                           class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                </div>
                <div>
                    <label for="catalog_number" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('catalog_number') ?></label>
                    <input type="text" id="catalog_number" name="catalog_number" value="<?= htmlspecialchars($coin['catalog_number'] ?? '') ?>"
                           class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                </div>
            </div>
        </div>

        <!-- Tehnički podaci -->
        <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 mb-6">
            <h2 class="text-lg font-semibold mb-4"><?= Lang::get('technical_data') ?></h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <div>
                    <label for="material" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('material') ?></label>
                    <select id="material" name="material" onchange="toggleAlloyField(this.value)"
                            class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                        <option value="">-</option>
                        <option value="copper" <?= ($coin['material'] ?? '') === 'copper' ? 'selected' : '' ?>><?= Lang::get('material_copper') ?></option>
                        <option value="silver" <?= ($coin['material'] ?? '') === 'silver' ? 'selected' : '' ?>><?= Lang::get('material_silver') ?></option>
                        <option value="gold" <?= ($coin['material'] ?? '') === 'gold' ? 'selected' : '' ?>><?= Lang::get('material_gold') ?></option>
                        <option value="brass" <?= ($coin['material'] ?? '') === 'brass' ? 'selected' : '' ?>><?= Lang::get('material_brass') ?></option>
                        <option value="aluminum" <?= ($coin['material'] ?? '') === 'aluminum' ? 'selected' : '' ?>><?= Lang::get('material_aluminum') ?></option>
                        <option value="alloy" <?= ($coin['material'] ?? '') === 'alloy' ? 'selected' : '' ?>><?= Lang::get('material_alloy') ?></option>
                    </select>
                </div>
                <div id="alloyDetailsContainer" class="<?= ($coin['material'] ?? '') === 'alloy' ? '' : 'hidden' ?>">
                    <label for="alloy_details" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('alloy_details') ?></label>
                    <input type="text" id="alloy_details" name="alloy_details" value="<?= htmlspecialchars($coin['alloy_details'] ?? '') ?>"
                           class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                </div>
                <div>
                    <label for="weight" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('weight') ?> (g)</label>
                    <input type="number" id="weight" name="weight" step="0.001" min="0" value="<?= htmlspecialchars($coin['weight'] ?? '') ?>"
                           class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                </div>
                <div>
                    <label for="diameter" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('diameter') ?> (mm)</label>
                    <input type="number" id="diameter" name="diameter" step="0.001" min="0" value="<?= htmlspecialchars($coin['diameter'] ?? '') ?>"
                           class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                </div>
                <div>
                    <label for="thickness" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('thickness') ?> (mm)</label>
                    <input type="number" id="thickness" name="thickness" step="0.001" min="0" value="<?= htmlspecialchars($coin['thickness'] ?? '') ?>"
                           class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                </div>
                <div>
                    <label for="orientation" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('orientation') ?></label>
                    <select id="orientation" name="orientation"
                            class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                        <option value="">-</option>
                        <option value="medal" <?= ($coin['orientation'] ?? '') === 'medal' ? 'selected' : '' ?>><?= Lang::get('orientation_medal') ?></option>
                        <option value="coin" <?= ($coin['orientation'] ?? '') === 'coin' ? 'selected' : '' ?>><?= Lang::get('orientation_coin') ?></option>
                    </select>
                </div>
                <div>
                    <label for="mintage" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('mintage') ?></label>
                    <input type="number" id="mintage" name="mintage" min="0" value="<?= htmlspecialchars($coin['mintage'] ?? '') ?>"
                           class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                </div>
            </div>
        </div>

        <!-- Dizajn -->
        <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 mb-6">
            <h2 class="text-lg font-semibold mb-4"><?= Lang::get('design') ?></h2>
            <div class="space-y-4">
                <div>
                    <label for="description_obverse" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('description_obverse') ?></label>
                    <textarea id="description_obverse" name="description_obverse" rows="3"
                              class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors resize-y"><?= htmlspecialchars($coin['description_obverse'] ?? '') ?></textarea>
                </div>
                <div>
                    <label for="description_reverse" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('description_reverse') ?></label>
                    <textarea id="description_reverse" name="description_reverse" rows="3"
                              class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors resize-y"><?= htmlspecialchars($coin['description_reverse'] ?? '') ?></textarea>
                </div>
                <div>
                    <label for="legends" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('legends') ?></label>
                    <textarea id="legends" name="legends" rows="3"
                              class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors resize-y"><?= htmlspecialchars($coin['legends'] ?? '') ?></textarea>
                </div>
            </div>
        </div>

        
        <!-- Variants -->
        <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 mb-6">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-lg font-semibold"><?= Lang::get('variants') ?></h2>
                <button type="button" id="addVariantBtn" class="btn-gradient btn-gradient-blue btn-gradient-icon btn-gradient-sm">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"/></svg>
                    <?= Lang::get('add_variant') ?>
                </button>
            </div>
            <div id="variantsContainer">
                <?php if (empty($variants)): ?>
                <div class="variant-row flex flex-wrap items-end gap-3 mb-3 p-3 bg-gray-50 dark:bg-gray-700/30 rounded-lg border border-gray-200 dark:border-gray-600">
                    <div class="flex-1 min-w-[140px]">
                        <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1"><?= Lang::get('condition') ?></label>
                        <select name="variant_condition[]" class="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                            <option value="">-</option>
                            <?php foreach ($conditionOptions as $co): ?>
                                <option value="<?= $co['id'] ?>"><?= htmlspecialchars($co['label']) ?><?= $co['description'] ? ' (' . htmlspecialchars($co['description']) . ')' : '' ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="flex-1 min-w-[140px]">
                        <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1"><?= Lang::get('additional_note') ?></label>
                        <input type="text" name="variant_note[]" class="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                    </div>
                    <div class="flex items-center gap-2">
                        <label class="flex items-center space-x-2 cursor-pointer">
                            <span class="text-xs font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('owned') ?></span>
                            <div class="relative">
                                <input type="checkbox" name="variant_owned[0]" value="1" class="sr-only peer">
                                <div class="w-9 h-5 bg-gray-300 dark:bg-gray-600 rounded-full peer peer-checked:bg-green-500 transition-colors"></div>
                                <div class="absolute left-0.5 top-0.5 w-4 h-4 bg-white rounded-full shadow-sm peer-checked:translate-x-4 transition-transform"></div>
                            </div>
                        </label>
                        <button type="button" class="remove-variant-btn text-gray-400 hover:text-red-500 transition-colors hidden" title="<?= Lang::get('remove') ?>">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                        </button>
                    </div>
                </div>
                <?php else: ?>
                <?php foreach ($variants as $vi => $v): ?>
                <div class="variant-row flex flex-wrap items-end gap-3 mb-3 p-3 bg-gray-50 dark:bg-gray-700/30 rounded-lg border border-gray-200 dark:border-gray-600">
                    <div class="flex-1 min-w-[140px]">
                        <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1"><?= Lang::get('condition') ?></label>
                        <select name="variant_condition[]" class="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                            <option value="">-</option>
                            <?php foreach ($conditionOptions as $co): ?>
                                <option value="<?= $co['id'] ?>" <?= ($v['condition_id'] == $co['id']) ? 'selected' : '' ?>><?= htmlspecialchars($co['label']) ?><?= $co['description'] ? ' (' . htmlspecialchars($co['description']) . ')' : '' ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="flex-1 min-w-[140px]">
                        <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1"><?= Lang::get('additional_note') ?></label>
                        <input type="text" name="variant_note[]" value="<?= htmlspecialchars($v['note'] ?? '') ?>" class="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                    </div>
                    <div class="flex items-center gap-2">
                        <label class="flex items-center space-x-2 cursor-pointer">
                            <span class="text-xs font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('owned') ?></span>
                            <div class="relative">
                                <input type="checkbox" name="variant_owned[<?= $vi ?>]" value="1" <?= $v['owned'] ? 'checked' : '' ?> class="sr-only peer">
                                <div class="w-9 h-5 bg-gray-300 dark:bg-gray-600 rounded-full peer peer-checked:bg-green-500 transition-colors"></div>
                                <div class="absolute left-0.5 top-0.5 w-4 h-4 bg-white rounded-full shadow-sm peer-checked:translate-x-4 transition-transform"></div>
                            </div>
                        </label>
                        <button type="button" class="remove-variant-btn text-gray-400 hover:text-red-500 transition-colors" title="<?= Lang::get('remove') ?>">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                        </button>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <!-- Dodatno -->
        <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 mb-6">
            <h2 class="text-lg font-semibold mb-4"><?= Lang::get('additional') ?></h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label for="origin" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('origin') ?></label>
                    <input type="text" id="origin" name="origin" value="<?= htmlspecialchars($coin['origin'] ?? '') ?>"
                           class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                </div>
                <div>
                    <label for="purchase_price" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('purchase_price') ?></label>
                    <input type="text" id="purchase_price" name="purchase_price" value="<?= htmlspecialchars($coin['purchase_price'] ?? '') ?>"
                           class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                </div>
                <div>
                    <label for="current_value" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('current_value') ?></label>
                    <input type="text" id="current_value" name="current_value" value="<?= htmlspecialchars($coin['current_value'] ?? '') ?>"
                           class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors">
                </div>
            </div>
            <div class="mt-4">
                <label for="note" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"><?= Lang::get('note') ?></label>
                <textarea id="note" name="note" rows="3" placeholder="<?= Lang::get('note_placeholder') ?>"
                          class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none transition-colors resize-y"><?= htmlspecialchars($coin['note'] ?? '') ?></textarea>
            </div>
        </div>

        <div class="flex justify-between items-center">
            <div class="flex space-x-3">
                <button type="submit" class="btn-gradient btn-gradient-blue btn-gradient-icon">
                    <?= Lang::get('save') ?>
                </button>
                <a href="<?= APP_URL ?>/subcollections/<?= $coin['subcollection_id'] ?>" class="btn-gradient btn-gradient-gray btn-gradient-icon">
                    <?= Lang::get('cancel') ?>
                </a>
                <a href="<?= APP_URL ?>/marketplace/create?source=coin&id=<?= $coin['id'] ?>" class="btn-gradient btn-gradient-green btn-gradient-icon" title="<?= Lang::get('sell_on_marketplace') ?>">
                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"/></svg>
                    <?= Lang::get('sell_on_marketplace') ?>
                </a>
            </div>
            <button type="button" onclick="deleteCoin()" class="btn-gradient btn-gradient-red btn-gradient-icon">
                <?= Lang::get('delete') ?>
            </button>
        </div>
    </form>
</div>

<script>
let isInWishlist = false;
let wishlistItem = null;

// Check wishlist status on page load
document.addEventListener('DOMContentLoaded', function() {
    // Only check wishlist status if wishlist elements exist
    const wishlistBtn = document.getElementById('wishlist-btn');
    if (wishlistBtn) {
        checkWishlistStatus();
    }
});

function checkWishlistStatus() {
    fetch(`<?= APP_URL ?>/api/wishlist/check?item_type=coin&item_id=<?= $coin['id'] ?>`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                isInWishlist = data.is_in_wishlist;
                wishlistItem = data.wishlist_item;
                updateWishlistButton();
            }
        })
        .catch(error => {
            console.error('Error checking wishlist status:', error);
        });
}

function toggleWishlist(itemType, itemId) {
    if (isInWishlist) {
        removeFromWishlist(itemType, itemId);
    } else {
        showAddToWishlistModal(itemType, itemId);
    }
}

function showAddToWishlistModal(itemType, itemId) {
    const modalHtml = `
        <div class="modal fade" id="addToWishlistModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Add to Wishlist</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="addToWishlistForm">
                            <input type="hidden" name="item_type" value="${itemType}">
                            <input type="hidden" name="item_id" value="${itemId}">
                            <input type="hidden" name="csrf_token" value="<?= Session::getCsrfToken() ?>">
                            
                            <div class="mb-3">
                                <label for="wishlist_notes" class="form-label">Notes (optional)</label>
                                <textarea class="form-control" id="wishlist_notes" name="notes" rows="3" 
                                          placeholder="Add your notes about this item..."></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label for="wishlist_target_price" class="form-label">Target Price (RSD, optional)</label>
                                <input type="number" class="form-control" id="wishlist_target_price" name="target_price" 
                                       step="0.01" min="0" placeholder="0.00">
                            </div>
                            
                            <div class="mb-3">
                                <label for="wishlist_priority" class="form-label">Priority</label>
                                <select class="form-select" id="wishlist_priority" name="priority">
                                    <option value="low">Low</option>
                                    <option value="medium" selected>Medium</option>
                                    <option value="high">High</option>
                                </select>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" onclick="addToWishlist()">Add to Wishlist</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal if any
    const existingModal = document.getElementById('addToWishlistModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // Add modal to body and show it
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    const modal = new bootstrap.Modal(document.getElementById('addToWishlistModal'));
    modal.show();
}

function addToWishlist() {
    const formData = new FormData(document.getElementById('addToWishlistForm'));
    
    fetch('<?= APP_URL ?>/api/wishlist/add', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            isInWishlist = true;
            wishlistItem = {
                notes: formData.get('notes'),
                target_price: formData.get('target_price'),
                priority: formData.get('priority')
            };
            updateWishlistButton();
            bootstrap.Modal.getInstance(document.getElementById('addToWishlistModal')).hide();
            showToast('Item added to wishlist', 'success');
        } else {
            showToast(data.message || 'Failed to add to wishlist', 'error');
        }
    })
    .catch(error => {
        showToast('An error occurred', 'error');
    });
}

function removeFromWishlist(itemType, itemId) {
    if (!confirm('Are you sure you want to remove this item from your wishlist?')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('item_id', itemId);
    formData.append('item_type', itemType);
    formData.append('csrf_token', '<?= Session::getCsrfToken() ?>');
    
    fetch('<?= APP_URL ?>/api/wishlist/remove', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            isInWishlist = false;
            wishlistItem = null;
            updateWishlistButton();
            showToast('Item removed from wishlist', 'success');
        } else {
            showToast(data.message || 'Failed to remove from wishlist', 'error');
        }
    })
    .catch(error => {
        showToast('An error occurred', 'error');
    });
}

function updateWishlistButton() {
    const btn = document.getElementById('wishlist-btn');
    const icon = document.getElementById('wishlist-icon');
    const text = document.getElementById('wishlist-text');
    
    // Check if wishlist elements exist before trying to update them
    if (!btn || !icon || !text) return;
    
    if (isInWishlist) {
        btn.className = 'flex items-center gap-2 px-4 py-2 rounded-lg border border-red-300 bg-red-50 text-red-600 hover:bg-red-100 transition-colors';
        icon.className = 'fas fa-heart';
        text.textContent = 'Remove from Wishlist';
    } else {
        btn.className = 'flex items-center gap-2 px-4 py-2 rounded-lg border border-gray-300 hover:border-red-300 hover:bg-red-50 hover:text-red-600 transition-colors';
        icon.className = 'far fa-heart';
        text.textContent = 'Add to Wishlist';
    }
}

function deleteCoin() {
    if (confirm('Are you sure you want to delete this coin? This action cannot be undone.')) {
        window.location.href = '<?= APP_URL ?>/coins/<?= $coin['id'] ?>/delete';
    }
}

function showDeleteModal(type, id) {
    // Prevent multiple modals
    if (window.deleteModalOpen) {
        return;
    }
    window.deleteModalOpen = true;
    
    const modalHtml = `
        <div id="deleteModal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999; display: flex; align-items: center; justify-content: center;">
            <div style="background: white; border-radius: 8px; max-width: 500px; width: 90%; box-shadow: 0 20px 60px rgba(0,0,0,0.3);">
                <div style="padding: 20px; border-bottom: 1px solid #eee; display: flex; justify-content: space-between; align-items: center;">
                    <h5 style="color: #dc3545; margin: 0; font-size: 18px; display: flex; align-items: center;">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Confirm Deletion
                    </h5>
                    <button type="button" onclick="closeDeleteModal()" style="background: none; border: none; font-size: 24px; color: #6c757d; cursor: pointer; padding: 0; line-height: 1;">&times;</button>
                </div>
                <div style="padding: 30px 20px;">
                    <div style="text-align: center; margin-bottom: 20px;">
                        <div style="color: #dc3545; margin-bottom: 15px;">
                            <i class="fas fa-trash-alt fa-3x"></i>
                        </div>
                        <h6 style="margin-bottom: 15px;">Are you sure you want to delete this ${type}?</h6>
                        <p style="color: #6c757d; margin: 0;">This action cannot be undone and will permanently remove the ${type} from your collection.</p>
                    </div>
                </div>
                <div style="padding: 20px; border-top: 1px solid #eee; display: flex; justify-content: center; gap: 10px;">
                    <button type="button" onclick="closeDeleteModal()" style="background: #6c757d; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; font-size: 14px;">
                        <i class="fas fa-times me-2"></i>Cancel
                    </button>
                    <button type="button" onclick="confirmDelete('${type}', '${id}')" style="background: #dc3545; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; font-size: 14px;">
                        <i class="fas fa-trash me-2"></i>Delete
                    </button>
                </div>
            </div>
        </div>
    `;
    
    // Add modal to page
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // Add escape key listener
    const escapeHandler = (e) => {
        if (e.key === 'Escape') {
            closeDeleteModal();
        }
    };
    document.addEventListener('keydown', escapeHandler);
    
    // Store handler for cleanup
    window.deleteEscapeHandler = escapeHandler;
}

function closeDeleteModal() {
    const modal = document.getElementById('deleteModal');
    if (modal) {
        modal.remove();
    }
    if (window.deleteEscapeHandler) {
        document.removeEventListener('keydown', window.deleteEscapeHandler);
        delete window.deleteEscapeHandler;
    }
    window.deleteModalOpen = false;
}

function confirmDelete(type, id) {
    const url = type === 'item' ? '<?= APP_URL ?>/items/' + id + '/delete' : '<?= APP_URL ?>/coins/' + id + '/delete';
    window.location.href = url;
}

function showToast(message, type = 'info') {
    // Simple toast notification
    const toastHtml = `
        <div class="position-fixed top-0 end-0 p-3" style="z-index: 11">
            <div class="toast show" role="alert">
                <div class="toast-header bg-${type === 'success' ? 'success' : type === 'error' ? 'danger' : 'info'} text-white">
                    <strong class="me-auto">Wishlist</strong>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
                </div>
                <div class="toast-body">
                    ${message}
                </div>
            </div>
        </div>
    `;
    
    const toastElement = document.createElement('div');
    toastElement.innerHTML = toastHtml;
    document.body.appendChild(toastElement);
    
    setTimeout(() => {
        toastElement.remove();
    }, 3000);
}
</script>

<?php $extraJs = ['coins.js']; ?>
<?php require APP_ROOT . '/views/layouts/footer.php'; ?>
