<?php
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/product_core_common.php';
require_login();
require_role(['admin','production_manager']);

$user = current_user();
$productId = (int)($_GET['id'] ?? $_POST['product_id'] ?? 0);
if ($productId <= 0) {
    $_SESSION['flash'] = ['type'=>'error','msg'=>'Ürün ID bulunamadı.'];
    redirect('products.php');
}
product_ensure_specs($productId);
$product = product_find_by_id($productId);
if (!$product) {
    $_SESSION['flash'] = ['type'=>'error','msg'=>'Ürün kartı bulunamadı.'];
    redirect('products.php');
}
$page_title = 'Ürün Kartı';
$active_menu = 'products';
$options = product_stone_options();
$stores = product_stores();
$materials = product_sample_materials();
$sampleStatuses = product_sample_stock_options();
$sampleHelp = product_sample_stock_help();
$sampleColors = product_sample_colors();

if (is_post()) {
    verify_csrf();
    $action = $_POST['action'] ?? '';
    try {
        if ($action === 'update_master_code') {
            $newMaster = product_change_master_code($productId, (string)($_POST['new_master_code'] ?? ''));
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Ana SKU güncellendi: '.$newMaster.'. Bağlı kullanılmamış mağaza SKU’ları da güncellendi.'];
        }

        if ($action === 'update_specs') {
            $shortName = trim((string)($_POST['short_name'] ?? ''));
            if ($shortName === '') throw new RuntimeException('Kısa ürün adı zorunlu.');
            $sampleMaterial = trim((string)($_POST['sample_material_code'] ?? ''));
            $sampleGram = product_parse_decimal($_POST['sample_actual_gram'] ?? null);
            $grams = product_calculate_grams($sampleMaterial, $sampleGram);
            $sampleStatus = $_POST['sample_stock_status'] ?? 'atelier';
            if (!isset($sampleStatuses[$sampleStatus])) $sampleStatus = 'atelier';
            $physicalStoreId = (int)($_POST['sample_owner_store_id'] ?? 0);
            if ($sampleStatus !== 'store') $physicalStoreId = 0;
            $usageStoreIds = $_POST['usage_store_ids'] ?? [];
            $chargeStoreIds = $_POST['charge_store_ids'] ?? [];
            $chargeToStore = !empty($_POST['sample_charge_to_store']);
            if ($chargeToStore && !$chargeStoreIds) $chargeStoreIds = $usageStoreIds;
            $pdo = db();
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("UPDATE products SET product_name=?, avg_gram=?, updated_at=NOW() WHERE id=?");
            $stmt->execute([$shortName, $grams['gram_14k'], $productId]);
            $stmt = $pdo->prepare("UPDATE product_core_specs SET short_name=?, width_mm=?, length_mm=?, height_mm=?, band_width_mm=?, gram_10k=?, gram_14k=?, gram_18k=?, source_url=?, sample_material_code=?, sample_karat=?, sample_color=?, sample_actual_gram=?, sample_stock_status=?, sample_owner_store_id=?, sample_charge_to_store=?, sample_note=?, design_note=?, updated_at=NOW() WHERE product_id=?");
            $stmt->execute([
                $shortName,
                product_parse_decimal($_POST['width_mm'] ?? null),
                product_parse_decimal($_POST['length_mm'] ?? null),
                product_parse_decimal($_POST['height_mm'] ?? null),
                product_parse_decimal($_POST['band_width_mm'] ?? null),
                $grams['gram_10k'],
                $grams['gram_14k'],
                $grams['gram_18k'],
                trim((string)($_POST['source_url'] ?? '')),
                $sampleMaterial ?: null,
                '',
                trim((string)($_POST['sample_color'] ?? '')),
                $sampleGram,
                $sampleStatus,
                $physicalStoreId > 0 ? $physicalStoreId : null,
                $chargeToStore ? 1 : 0,
                trim((string)($_POST['sample_note'] ?? '')),
                trim((string)($_POST['design_note'] ?? '')),
                $productId,
            ]);
            product_replace_store_usage($pdo, $productId, is_array($usageStoreIds) ? $usageStoreIds : [], $user['id'] ?? null);
            product_replace_sample_charge_stores($pdo, $productId, $chargeToStore && is_array($chargeStoreIds) ? $chargeStoreIds : []);
            $pdo->commit();
            product_audit('product_update_specs', 'product', $productId, null, $_POST, 'Ürün teknik/numune bilgileri güncellendi');
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Ürün kartı güncellendi. Gramlar numune bilgisinden tekrar hesaplandı.'];
        }

        if ($action === 'upload_image') {
            $imageId = product_handle_image_upload($productId, (string)$product['master_code'], (string)$product['product_name'], $_FILES['product_image'] ?? [], $user['id'] ?? null);
            if (!$imageId) throw new RuntimeException('Fotoğraf seçilmedi.');
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Fotoğraf yüklendi.'];
        }

        if ($action === 'set_primary_image') {
            $imageId = (int)($_POST['image_id'] ?? 0);
            db()->beginTransaction();
            db()->prepare("UPDATE product_images SET is_primary=0 WHERE product_id=?")->execute([$productId]);
            db()->prepare("UPDATE product_images SET is_primary=1 WHERE product_id=? AND id=?")->execute([$productId, $imageId]);
            db()->commit();
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Kapak fotoğrafı güncellendi.'];
        }

        if ($action === 'add_slot') {
            if (product_active_recipe_exists($productId, 'V00')) {
                throw new RuntimeException('Bu ürün taşsız V00 reçeteli. Taş eklemek istiyorsan yeni model/ürün kartı açmalısın.');
            }
            $cutId = (int)($_POST['cut_id'] ?? 0);
            $sizeId = (int)($_POST['size_id'] ?? 0);
            $qty = (int)($_POST['qty_per_product'] ?? 0);
            if ($cutId <= 0 || $sizeId <= 0 || $qty <= 0) throw new RuntimeException('Kesim, ölçü ve adet zorunlu.');
            $slotNo = product_next_stone_slot_no($productId);
            $stmt = db()->prepare("INSERT INTO product_stone_slots (product_id, slot_no, cut_id, size_id, qty_per_product, slot_note) VALUES (?,?,?,?,?,?)");
            $stmt->execute([$productId, $slotNo, $cutId, $sizeId, $qty, trim((string)($_POST['slot_note'] ?? ''))]);
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Taş slotu eklendi. Bu ürün artık taşlı ürün mantığındadır; reçete V01’den başlar.'];
        }

        if ($action === 'delete_slot') {
            $slotId = (int)($_POST['slot_id'] ?? 0);
            $stmt = db()->prepare("UPDATE product_stone_slots SET is_active=0 WHERE product_id=? AND id=?");
            $stmt->execute([$productId, $slotId]);
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Taş slotu pasife alındı.'];
        }

        if ($action === 'create_v00') {
            if (product_active_slot_count($productId) > 0) {
                throw new RuntimeException('Taş slotu olan ürünlerde V00 oluşturulamaz. Taşsız versiyon ayrı model olmalı.');
            }
            $recipeId = product_create_or_update_recipe($productId, 'V00', 'Taşsız reçete', true, (int)$user['id']);
            db()->prepare("DELETE FROM product_recipe_stones WHERE recipe_id=?")->execute([$recipeId]);
            $_SESSION['flash'] = ['type'=>'success','msg'=>'V00 taşsız reçete oluşturuldu/güncellendi.'];
        }

        if ($action === 'create_stone_recipe') {
            $slots = product_stone_slots($productId, true);
            if (!$slots) throw new RuntimeException('Taşlı reçete için önce taş slotu eklemelisin. Taşsız üründe V00 kullanılır.');
            $recipeCode = strtoupper(trim((string)($_POST['recipe_code'] ?? '')));
            if ($recipeCode === '') $recipeCode = product_next_stone_recipe_code($productId);
            if ($recipeCode === 'V00') throw new RuntimeException('Taşlı ürünlerde V00 kullanılamaz; V01/V02 kullanılmalı.');
            $recipeName = trim((string)($_POST['recipe_name'] ?? ''));
            if ($recipeName === '') $recipeName = $recipeCode . ' taşlı reçete';
            $slotSpecies = $_POST['slot_species'] ?? [];
            $slotColors = $_POST['slot_color'] ?? [];
            $missing = [];
            $recipeLines = [];
            foreach ($slots as $slot) {
                $sid = (int)$slot['id'];
                $speciesId = (int)($slotSpecies[$sid] ?? 0);
                $colorId = (int)($slotColors[$sid] ?? 0);
                if ($speciesId <= 0 || $colorId <= 0) throw new RuntimeException('Her slot için taş cinsi ve renk seçmelisin.');
                $stone = product_lookup_stone_for_slot($speciesId, (int)$slot['cut_id'], (int)$slot['size_id'], $colorId);
                if (!$stone) {
                    $missing[] = '#'.$slot['slot_no'].' '.$slot['cut_name'].' '.$slot['size_label'];
                    continue;
                }
                $recipeLines[] = ['slot'=>$slot, 'stone'=>$stone];
            }
            if ($missing) {
                throw new RuntimeException('Bazı slotlar için taş kartı bulunamadı: '.implode(', ', $missing));
            }
            $pdo = db();
            $pdo->beginTransaction();
            $recipeId = product_create_or_update_recipe($productId, $recipeCode, $recipeName, false, (int)$user['id']);
            $pdo->prepare("DELETE FROM product_recipe_stones WHERE recipe_id=?")->execute([$recipeId]);
            $stmt = $pdo->prepare("INSERT INTO product_recipe_stones (recipe_id, product_stone_slot_id, stone_id, qty_per_product) VALUES (?,?,?,?)");
            foreach ($recipeLines as $line) {
                $stmt->execute([$recipeId, (int)$line['slot']['id'], (int)$line['stone']['id'], (int)$line['slot']['qty_per_product']]);
            }
            $pdo->commit();
            $_SESSION['flash'] = ['type'=>'success','msg'=>$recipeCode.' taşlı reçete oluşturuldu.'];
        }

        if ($action === 'assign_recipe_stores') {
            $recipeId = (int)($_POST['recipe_id'] ?? 0);
            $storeIds = array_map('intval', $_POST['store_ids'] ?? []);
            if ($recipeId <= 0 || !$storeIds) throw new RuntimeException('Reçete ve mağaza seçmelisin.');
            $created = [];
            foreach ($storeIds as $storeId) {
                $created[] = product_assign_recipe_to_store($productId, $recipeId, $storeId);
            }
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Mağaza SKU oluşturuldu: '.implode(', ', $created)];
        }


        if ($action === 'update_recipe') {
            $recipeId = (int)($_POST['recipe_id'] ?? 0);
            if ($recipeId <= 0) throw new RuntimeException('Reçete seçilmedi.');
            $code = product_update_existing_recipe(
                $productId,
                $recipeId,
                (string)($_POST['recipe_name'] ?? ''),
                $_POST['slot_species'] ?? [],
                $_POST['slot_color'] ?? []
            );
            product_audit('product_update_recipe', 'product_recipe', $recipeId, null, $_POST, 'Reçete güncellendi');
            $_SESSION['flash'] = ['type'=>'success','msg'=>$code.' reçetesi güncellendi.'];
        }

        if ($action === 'delete_recipe') {
            $recipeId = (int)($_POST['recipe_id'] ?? 0);
            if ($recipeId <= 0) throw new RuntimeException('Reçete seçilmedi.');
            $code = product_delete_unused_recipe($productId, $recipeId);
            product_audit('product_delete_unused_recipe', 'product_recipe', $recipeId, null, $_POST, 'Kullanılmamış reçete silindi');
            $_SESSION['flash'] = ['type'=>'success','msg'=>$code.' kullanılmamış reçetesi silindi.'];
        }

        if ($action === 'delete_store_sku') {
            $storeRecipeSkuId = (int)($_POST['store_recipe_sku_id'] ?? 0);
            if ($storeRecipeSkuId <= 0) throw new RuntimeException('Mağaza SKU seçilmedi.');
            $deletedSku = product_delete_unused_store_recipe_sku($storeRecipeSkuId);
            product_audit('product_delete_unused_store_sku', 'product_store_recipe_sku', $storeRecipeSkuId, null, $_POST, 'Kullanılmamış mağaza SKU silindi');
            $_SESSION['flash'] = ['type'=>'success','msg'=>$deletedSku.' kullanılmamış mağaza SKU kaydı silindi.'];
        }
    } catch (Throwable $e) {
        if (db()->inTransaction()) db()->rollBack();
        $_SESSION['flash'] = ['type'=>'error','msg'=>'İşlem yapılamadı: '.$e->getMessage()];
    }
    redirect('product_detail.php?id='.$productId);
}

$product = product_find_by_id($productId);
$images = product_images($productId);
$slots = product_stone_slots($productId, true);
$recipes = product_recipes($productId);
$storeSkus = product_store_skus($productId);
$usageRows = product_store_usage($productId);
$usageStoreIds = product_store_usage_ids($productId);
$chargeRows = product_sample_charge_stores($productId);
$chargeStoreIds = product_sample_charge_store_ids($productId);
$nextRecipeCode = product_next_stone_recipe_code($productId);
$slotCount = count($slots);
$isStoneProduct = $slotCount > 0;
$productOrderUsageCount = product_product_order_usage_count($productId);
$masterCodeSuggestions = product_available_master_code_suggestions((string)$product['category'], 20);

include __DIR__ . '/includes/layout.php';
?>
<div class="ph"><div><h1>Ürün Kartı</h1><p><strong><?= e($product['master_code']) ?></strong> — <?= e($product['short_name'] ?: $product['product_name']) ?></p></div><div><a class="btn btn-secondary" href="products.php">Listeye Dön</a></div></div>

<div class="grid" style="grid-template-columns:repeat(5,minmax(0,1fr));gap:14px;margin-bottom:16px">
  <div class="stat"><div class="stat-label">Ana SKU</div><div class="stat-value"><?= e($product['master_code']) ?></div></div>
  <div class="stat"><div class="stat-label">Ürün Tipi</div><div class="stat-value"><?= e(product_type_label($product['category'])) ?></div></div>
  <div class="stat"><div class="stat-label">Taş Durumu</div><div class="stat-value"><?= $isStoneProduct ? 'Taşlı' : 'Taşsız' ?></div></div>
  <div class="stat"><div class="stat-label">14K Hesap Gram</div><div class="stat-value"><?= $product['gram_14k'] !== null ? e(number_format((float)$product['gram_14k'],3)).' gr' : '-' ?></div></div>
  <div class="stat"><div class="stat-label">Numune</div><div class="stat-value"><?= e(product_sample_stock_label($product['sample_stock_status'] ?? 'atelier')) ?></div></div>
</div>

<div class="card"><div class="card-header"><span class="card-title">Ana SKU Yönetimi</span><span class="c-mt">Ana SKU mağazadan bağımsızdır. Örnek: R0036. BLG/LUW/VOQ/Jolene prefix’i mağaza SKU oluştururken otomatik eklenir.</span></div><div class="card-body">
<form method="post" style="display:grid;grid-template-columns:1fr 2fr auto;gap:12px;align-items:end">
<?= csrf_field() ?><input type="hidden" name="action" value="update_master_code"><input type="hidden" name="product_id" value="<?= (int)$productId ?>">
<div><label class="form-label">Mevcut Ana SKU</label><input class="form-control" value="<?= e($product['master_code']) ?>" readonly></div>
<div><label class="form-label">Yeni Ana SKU</label><input class="form-control" name="new_master_code" value="<?= e($product['master_code']) ?>" placeholder="örn R0036"><div class="c-mt" style="font-size:12px;margin-top:4px">Mağaza prefix’i yazma: BR0036 değil, R0036 yaz. Sistem mağaza SKU’larını otomatik BR0036V01 gibi günceller.</div></div>
<div><button class="btn btn-primary" type="submit" <?= $productOrderUsageCount>0?'disabled':'' ?>>Ana SKU’yu Güncelle</button></div>
</form>
<div class="flash <?= $productOrderUsageCount>0?'flash-error':'flash-info' ?>" style="margin-top:12px">
<?php if ($productOrderUsageCount>0): ?>Bu ürün/SKU siparişte kullanılmış görünüyor. Ana SKU artık değiştirilemez.<?php else: ?>Henüz sipariş kullanımı yoksa ana SKU değiştirilebilir; bağlı mağaza SKU’ları da otomatik yeniden yazılır.<?php endif; ?>
</div>
<?php if (!empty($masterCodeSuggestions)): ?><div style="margin-top:10px"><span class="c-mt">Boş / önerilen kodlar: </span><?php foreach($masterCodeSuggestions as $code): ?><button type="button" class="btn btn-secondary suggested-master-code" data-code="<?= e($code) ?>" style="padding:6px 10px;margin:3px"><?= e($code) ?></button><?php endforeach; ?></div><?php endif; ?>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Teknik / Numune Bilgileri</span><span class="c-mt">10K/14K/18K otomatik hesaplanır. Numune konumu ve mağaza kullanımı ayrı takip edilir.</span></div><div class="card-body">
<form method="post" style="display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px;align-items:end">
<?= csrf_field() ?><input type="hidden" name="action" value="update_specs"><input type="hidden" name="product_id" value="<?= (int)$productId ?>">
<div><label class="form-label">Kısa Ürün Adı</label><input class="form-control" name="short_name" value="<?= e($product['short_name'] ?: $product['product_name']) ?>" required></div>
<div><label class="form-label">Genişlik mm</label><input class="form-control" name="width_mm" value="<?= e($product['width_mm']) ?>"></div>
<div><label class="form-label">Uzunluk mm</label><input class="form-control" name="length_mm" value="<?= e($product['length_mm']) ?>"></div>
<div><label class="form-label">Yükseklik mm</label><input class="form-control" name="height_mm" value="<?= e($product['height_mm']) ?>"></div>
<div><label class="form-label">Band Kalınlığı mm</label><input class="form-control" name="band_width_mm" value="<?= e($product['band_width_mm']) ?>"></div>
<div style="grid-column:span 2"><label class="form-label">Kaynak Link</label><input class="form-control" name="source_url" value="<?= e($product['source_url']) ?>"></div>
<div><label class="form-label">Numune Materyali</label><select class="form-control" name="sample_material_code"><option value="">Seç</option><?php foreach($materials as $m): ?><option value="<?= e($m['material_code']) ?>" <?= $product['sample_material_code']===$m['material_code']?'selected':'' ?>><?= e(product_sample_material_display($m)) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Numune Renk</label><select class="form-control" name="sample_color"><option value="">Seç</option><?php foreach($sampleColors as $v): ?><option <?= $product['sample_color']===$v?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Numune Gerçek Gram</label><input class="form-control" name="sample_actual_gram" value="<?= e($product['sample_actual_gram']) ?>"></div>
<div><label class="form-label">Numune Fiziki Durumu</label><select class="form-control" name="sample_stock_status"><?php foreach($sampleStatuses as $k=>$v): ?><option value="<?= e($k) ?>" <?= ($product['sample_stock_status'] ?: 'atelier')===$k?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Fiziki Konum Mağazası</label><select class="form-control" name="sample_owner_store_id"><option value="">Yok / Atölye</option><?php foreach($stores as $s): ?><option value="<?= (int)$s['id'] ?>" <?= (int)$product['sample_owner_store_id']===(int)$s['id']?'selected':'' ?>><?= e($s['store_code'].' — '.$s['store_name']) ?></option><?php endforeach; ?></select></div>
<div style="grid-column:span 2"><label class="form-label">Ürünü Kullanacak Mağazalar</label><div style="display:flex;gap:14px;flex-wrap:wrap;padding:10px 0"><?php foreach($stores as $s): ?><label><input type="checkbox" name="usage_store_ids[]" value="<?= (int)$s['id'] ?>" <?= in_array((int)$s['id'], $usageStoreIds, true)?'checked':'' ?>> <?= e($s['store_code']) ?></label><?php endforeach; ?></div></div>
<div style="grid-column:span 3"><label class="form-label">Numune Maliyetini Mağazalara Yansıt</label><div style="display:flex;gap:14px;flex-wrap:wrap;align-items:center;padding:10px 0"><label><input type="checkbox" name="sample_charge_to_store" value="1" <?= (int)$product['sample_charge_to_store']?'checked':'' ?>> Evet</label><?php foreach($stores as $s): ?><label><input type="checkbox" name="charge_store_ids[]" value="<?= (int)$s['id'] ?>" <?= in_array((int)$s['id'], $chargeStoreIds, true)?'checked':'' ?>> <?= e($s['store_code']) ?></label><?php endforeach; ?></div></div>
<div><label class="form-label">Hesap 10K</label><input class="form-control" value="<?= $product['gram_10k'] !== null ? e(number_format((float)$product['gram_10k'],3)).' gr' : '-' ?>" readonly></div>
<div><label class="form-label">Hesap 14K</label><input class="form-control" value="<?= $product['gram_14k'] !== null ? e(number_format((float)$product['gram_14k'],3)).' gr' : '-' ?>" readonly></div>
<div><label class="form-label">Hesap 18K</label><input class="form-control" value="<?= $product['gram_18k'] !== null ? e(number_format((float)$product['gram_18k'],3)).' gr' : '-' ?>" readonly></div>
<div style="grid-column:span 2"><label class="form-label">Numune Notu</label><input class="form-control" name="sample_note" value="<?= e($product['sample_note']) ?>"></div>
<div style="grid-column:1/-1"><label class="form-label">Tasarım / Üretim Notu</label><input class="form-control" name="design_note" value="<?= e($product['design_note']) ?>"></div>
<div style="grid-column:1/-1"><button class="btn btn-primary" type="submit">Kartı Güncelle ve Gramları Hesapla</button></div>
</form>
<div class="flash flash-info" style="margin-top:14px">
<strong>Numune fiziki durumu:</strong>
<?php foreach($sampleHelp as $k=>$v): ?><span style="display:inline-block;margin-right:14px"><strong><?= e($sampleStatuses[$k]) ?>:</strong> <?= e($v) ?></span><?php endforeach; ?>
</div>
<?php if ($product['sample_material_code'] && $product['sample_actual_gram']): ?><div class="flash flash-info" style="margin-top:10px">Gramlar sistemin iç yoğunluk tablosuyla hesaplanır; kullanıcı ekranında yoğunluk değerleri gösterilmez.</div><?php endif; ?>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Mağaza Kullanımı / Numune Maliyet Payı</span></div><div class="card-body" style="display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px">
<div class="stat"><div class="stat-label">Ürünü Kullanacak Mağazalar</div><div class="stat-value" style="font-size:20px"><?= e(product_store_codes_summary($usageRows)) ?></div></div>
<div class="stat"><div class="stat-label">Numune Maliyeti Yansıtılacak</div><div class="stat-value" style="font-size:20px"><?= e(product_store_codes_summary($chargeRows)) ?></div></div>
<div class="stat"><div class="stat-label">Fiziki Numune</div><div class="stat-value" style="font-size:20px"><?= e(product_sample_stock_label($product['sample_stock_status'] ?? 'atelier')) ?><?= $product['sample_owner_store_code'] ? ' / '.e($product['sample_owner_store_code']) : '' ?></div></div>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Fotoğraf</span></div><div class="card-body">
<form method="post" enctype="multipart/form-data" style="display:flex;gap:12px;align-items:end;margin-bottom:12px">
<?= csrf_field() ?><input type="hidden" name="action" value="upload_image"><input type="hidden" name="product_id" value="<?= (int)$productId ?>">
<div style="flex:1"><label class="form-label">Ürün Fotoğrafı</label><input class="form-control product-image-input" type="file" name="product_image" accept="image/*" data-max-bytes="<?= product_image_max_bytes() ?>"><div class="c-mt" style="font-size:12px;margin-top:4px">Maksimum <?= e(product_image_max_mb_label()) ?>. Büyük iPhone/WhatsApp görsellerini önce küçült.</div></div>
<button class="btn btn-primary" type="submit">Fotoğraf Yükle</button>
</form>
<?php if (!$images): ?><div class="c-mt">Henüz fotoğraf yok.</div><?php endif; ?>
<?php if ($images): ?><div style="display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px">
<?php foreach($images as $img): ?><div class="card" style="margin:0"><div class="card-body"><img src="<?= e($img['file_path']) ?>" alt="" style="width:100%;height:140px;object-fit:cover;border-radius:10px;border:1px solid var(--border)"><div style="margin-top:8px;display:flex;justify-content:space-between;align-items:center"><span class="c-mt"><?= (int)$img['is_primary'] ? 'Kapak' : 'Foto' ?></span><?php if(!(int)$img['is_primary']): ?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="set_primary_image"><input type="hidden" name="image_id" value="<?= (int)$img['id'] ?>"><button class="btn btn-secondary" type="submit">Kapak Yap</button></form><?php endif; ?></div></div></div><?php endforeach; ?>
</div><?php endif; ?>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Taş Slotları</span><span class="c-mt">Ürünün geometrik taş yuvaları. Taş slotu eklersen ürün taşlı ürün olur ve reçete V01’den başlar.</span></div><div class="card-body">
<?php if (product_active_recipe_exists($productId, 'V00')): ?><div class="flash flash-info">Bu ürün taşsız V00 reçeteli. Taşlı yapılacaksa yeni ana ürün kartı açılmalı.</div><?php else: ?>
<form method="post" style="display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px;align-items:end;margin-bottom:16px">
<?= csrf_field() ?><input type="hidden" name="action" value="add_slot"><input type="hidden" name="product_id" value="<?= (int)$productId ?>">
<div><label class="form-label">Kesim</label><select class="form-control" name="cut_id" id="slotCut"><option value="">Seç</option><?php foreach($options['cuts'] as $o): ?><option value="<?= (int)$o['id'] ?>"><?= e($o['cut_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Ölçü</label><select class="form-control" name="size_id" id="slotSize"><option value="">Önce kesim seç</option><?php foreach($options['sizes'] as $o): ?><option data-cut="<?= (int)$o['cut_id'] ?>" value="<?= (int)$o['id'] ?>"><?= e($o['cut_name'].' — '.$o['size_label']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Birim Adet</label><input class="form-control" name="qty_per_product" placeholder="örn 5"></div>
<div><label class="form-label">Slot Notu</label><input class="form-control" name="slot_note" placeholder="yan taş / merkez taş"></div>
<div><button class="btn btn-primary" type="submit">Slot Ekle</button></div>
</form>
<?php endif; ?>
<div class="table-wrap"><table><thead><tr><th>Slot</th><th>Kesim</th><th>Ölçü</th><th>Birim Adet</th><th>1 Adet Ct</th><th>Not</th><th>İşlem</th></tr></thead><tbody>
<?php if (!$slots): ?><tr><td colspan="7" class="c-mt">Taş slotu yok. Bu ürün taşsız ise V00 oluştur.</td></tr><?php endif; ?>
<?php foreach($slots as $slot): ?><tr><td>#<?= (int)$slot['slot_no'] ?></td><td><?= e($slot['cut_name']) ?></td><td><?= e($slot['size_label']) ?></td><td><?= (int)$slot['qty_per_product'] ?></td><td><?= $slot['carat_each'] !== null ? e(number_format((float)$slot['carat_each'],5)) : '-' ?></td><td><?= e($slot['slot_note']) ?></td><td><form method="post" onsubmit="return confirm('Bu slot pasife alınsın mı?')"><?= csrf_field() ?><input type="hidden" name="action" value="delete_slot"><input type="hidden" name="slot_id" value="<?= (int)$slot['id'] ?>"><button class="btn btn-danger" type="submit">Pasifleştir</button></form></td></tr><?php endforeach; ?>
</tbody></table></div>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Reçeteler</span><span class="c-mt">Taşsız ürün = V00. Taşlı ürün = V01/V02/V03.</span></div><div class="card-body">
<div style="display:grid;grid-template-columns:1fr 2fr;gap:16px;align-items:start">
<div class="card" style="margin:0"><div class="card-header"><span class="card-title">Taşsız Reçete</span></div><div class="card-body">
<?php if ($isStoneProduct): ?><div class="flash flash-info">Bu üründe taş slotu var. Taşlı ürünlerde V00 oluşturulmaz. Taşsız istenirse ayrı ana ürün kartı açılır.</div><?php else: ?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="create_v00"><button class="btn btn-primary" type="submit">V00 Taşsız Reçete Oluştur</button></form><p class="c-mt" style="margin-top:10px">Tasarımcı taş bilgisi girmezse kesin V00 kullanılır.</p><?php endif; ?>
</div></div>
<div class="card" style="margin:0"><div class="card-header"><span class="card-title">Taşlı Reçete Oluştur</span></div><div class="card-body">
<?php if (!$isStoneProduct): ?><div class="flash flash-info">Taşlı reçete için önce taş slotu eklenmeli. Taşsız ürünlerde sadece V00 kullanılır.</div><?php else: ?>
<form method="post">
<?= csrf_field() ?><input type="hidden" name="action" value="create_stone_recipe">
<div style="display:grid;grid-template-columns:1fr 2fr;gap:12px;margin-bottom:12px"><div><label class="form-label">Reçete Kodu</label><input class="form-control" name="recipe_code" value="<?= e($nextRecipeCode) ?>"></div><div><label class="form-label">Reçete Adı</label><input class="form-control" name="recipe_name" placeholder="Zirkon colorless / moissanite / karışık taş"></div></div>
<?php foreach($slots as $slot): ?>
<div style="display:grid;grid-template-columns:1.2fr 1fr 1fr 0.8fr;gap:8px;align-items:end;margin-bottom:8px;padding-bottom:8px;border-bottom:1px solid var(--border)">
<div><strong>Slot #<?= (int)$slot['slot_no'] ?></strong><br><span class="c-mt"><?= e($slot['cut_name'].' / '.$slot['size_label'].' / '.$slot['qty_per_product'].' adet') ?></span></div>
<div><label class="form-label">Taş Cinsi</label><select class="form-control" name="slot_species[<?= (int)$slot['id'] ?>]"><option value="">Seç</option><?php foreach($options['species'] as $o): ?><option value="<?= (int)$o['id'] ?>"><?= e($o['species_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Renk</label><select class="form-control" name="slot_color[<?= (int)$slot['id'] ?>]"><option value="">Seç</option><?php foreach($options['colors'] as $o): ?><option value="<?= (int)$o['id'] ?>"><?= e($o['color_name']) ?></option><?php endforeach; ?></select></div>
<div class="c-mt">Sistem bu slotun kesim/ölçüsünde taş arar.</div>
</div>
<?php endforeach; ?>
<button class="btn btn-primary" type="submit">Taşlı Reçeteyi Oluştur</button>
</form>
<?php endif; ?>
</div></div>
</div>
<div class="table-wrap" style="margin-top:16px"><table><thead><tr><th>Kod</th><th>Ad</th><th>Tip</th><th>Taş Satırı</th><th>Toplam Taş</th><th>Kısa Taş Özeti</th><th>İşlem</th></tr></thead><tbody>
<?php if (!$recipes): ?><tr><td colspan="7" class="c-mt">Henüz reçete yok.</td></tr><?php endif; ?>
<?php foreach($recipes as $rec):
  $lines = product_recipe_stones((int)$rec['id']);
  $lineMap = [];
  foreach ($lines as $ln) { $lineMap[(int)$ln['product_stone_slot_id']] = $ln; }
  $linkedSkuCount = product_recipe_store_sku_count((int)$rec['id']);
  $summaryParts = [];
  foreach ($lines as $ln) { $summaryParts[] = '#'.$ln['slot_no'].' '.$ln['species_name'].' '.$ln['size_label'].' '.$ln['color_name'].' ×'.$ln['qty_per_product']; }
?>
<tr>
  <td><strong><?= e($rec['recipe_code']) ?></strong></td>
  <td><?= e($rec['recipe_name']) ?></td>
  <td><?= (int)$rec['is_stone_free'] ? 'Taşsız' : 'Taşlı' ?></td>
  <td><?= (int)$rec['stone_line_count'] ?></td>
  <td><?= (int)$rec['total_stone_qty'] ?></td>
  <td><?= $summaryParts ? e(implode(' | ', $summaryParts)) : '-' ?></td>
  <td><span class="badge"><?= $linkedSkuCount ?> mağaza SKU</span></td>
</tr>
<tr>
  <td colspan="7" style="background:rgba(255,255,255,.015);padding:0 12px 12px">
    <details class="recipe-detail-box">
      <summary style="cursor:pointer;padding:12px 0;font-weight:700;color:var(--gold)">Detay / Düzelt / Sil</summary>
      <div style="display:grid;grid-template-columns:2fr 1fr;gap:16px;align-items:start">
        <form method="post" style="display:grid;grid-template-columns:1fr 1fr;gap:10px;align-items:end">
          <?= csrf_field() ?>
          <input type="hidden" name="action" value="update_recipe">
          <input type="hidden" name="product_id" value="<?= (int)$productId ?>">
          <input type="hidden" name="recipe_id" value="<?= (int)$rec['id'] ?>">
          <div><label class="form-label">Reçete Adı</label><input class="form-control" name="recipe_name" value="<?= e($rec['recipe_name']) ?>"></div>
          <div class="c-mt">Yanlış V02/V03 taş seçimi yaptıysan burada aynı reçeteyi güncelle.</div>
          <?php if ((int)$rec['is_stone_free'] === 0): ?>
            <?php foreach($slots as $slot): $cur = $lineMap[(int)$slot['id']] ?? null; ?>
              <div style="grid-column:1/-1;display:grid;grid-template-columns:1.3fr 1fr 1fr;gap:8px;align-items:end;border-top:1px solid var(--border);padding-top:8px">
                <div><strong>Slot #<?= (int)$slot['slot_no'] ?></strong><br><span class="c-mt"><?= e($slot['cut_name'].' / '.$slot['size_label'].' / '.$slot['qty_per_product'].' adet') ?></span></div>
                <div><label class="form-label">Taş Cinsi</label><select class="form-control" name="slot_species[<?= (int)$slot['id'] ?>]"><option value="">Seç</option><?php foreach($options['species'] as $o): ?><option value="<?= (int)$o['id'] ?>" <?= $cur && (int)$cur['species_id']===(int)$o['id']?'selected':'' ?>><?= e($o['species_name']) ?></option><?php endforeach; ?></select></div>
                <div><label class="form-label">Renk</label><select class="form-control" name="slot_color[<?= (int)$slot['id'] ?>]"><option value="">Seç</option><?php foreach($options['colors'] as $o): ?><option value="<?= (int)$o['id'] ?>" <?= $cur && (int)$cur['color_id']===(int)$o['id']?'selected':'' ?>><?= e($o['color_name']) ?></option><?php endforeach; ?></select></div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
          <div style="grid-column:1/-1"><button class="btn btn-secondary" type="submit">Reçeteyi Güncelle</button></div>
        </form>
        <form method="post" onsubmit="return confirm('Bu reçete kullanılmamışsa silinecek. Bağlı mağaza SKU varsa önce onu silmelisin. Devam?')" style="border-left:1px solid var(--border);padding-left:14px">
          <?= csrf_field() ?>
          <input type="hidden" name="action" value="delete_recipe">
          <input type="hidden" name="product_id" value="<?= (int)$productId ?>">
          <input type="hidden" name="recipe_id" value="<?= (int)$rec['id'] ?>">
          <p class="c-mt" style="margin-top:0">Reçete hiç kullanılmadıysa ve bağlı mağaza SKU yoksa silebilirsin.</p>
          <button class="btn btn-danger" type="submit">Kullanılmamış Reçeteyi Sil</button>
        </form>
      </div>
    </details>
  </td>
</tr>
<?php endforeach; ?>
</tbody></table></div>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Mağaza SKU’ları</span><span class="c-mt">Reçeteyi mağazaya açınca Etsy’de kullanılacak SKU oluşur.</span></div><div class="card-body">
<form method="post" style="display:grid;grid-template-columns:1fr 2fr auto;gap:12px;align-items:end;margin-bottom:16px">
<?= csrf_field() ?><input type="hidden" name="action" value="assign_recipe_stores">
<div><label class="form-label">Reçete</label><select class="form-control" name="recipe_id"><option value="">Seç</option><?php foreach($recipes as $r): ?><option value="<?= (int)$r['id'] ?>"><?= e($r['recipe_code'].' — '.$r['recipe_name']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Mağazalar</label><div style="display:flex;gap:16px;flex-wrap:wrap;padding:10px 0"><?php foreach($stores as $s): ?><label><input type="checkbox" name="store_ids[]" value="<?= (int)$s['id'] ?>"> <?= e($s['store_code']) ?></label><?php endforeach; ?></div></div>
<div><button class="btn btn-primary" type="submit" <?= !$recipes?'disabled':'' ?>>SKU Oluştur</button></div>
</form>
<div class="table-wrap"><table><thead><tr><th>Mağaza</th><th>Reçete</th><th>Satış SKU</th><th>Durum</th><th>İşlem</th></tr></thead><tbody>
<?php if(!$storeSkus): ?><tr><td colspan="5" class="c-mt">Henüz mağaza SKU yok.</td></tr><?php endif; ?>
<?php foreach($storeSkus as $sku): $skuOrders = product_store_recipe_sku_order_count((string)$sku['sales_sku']); ?>
<tr>
  <td><?= e($sku['store_code'].' — '.$sku['store_name']) ?></td>
  <td><?= e($sku['recipe_code'].' — '.$sku['recipe_name']) ?></td>
  <td><strong><?= e($sku['sales_sku']) ?></strong></td>
  <td><?= (int)$sku['is_active'] ? 'Aktif' : 'Pasif' ?><?= $skuOrders>0 ? ' / '.$skuOrders.' sipariş' : '' ?></td>
  <td>
    <form method="post" onsubmit="return confirm('Bu mağaza SKU hiç kullanılmadıysa silinecek. Devam?')">
      <?= csrf_field() ?>
      <input type="hidden" name="action" value="delete_store_sku">
      <input type="hidden" name="product_id" value="<?= (int)$productId ?>">
      <input type="hidden" name="store_recipe_sku_id" value="<?= (int)$sku['id'] ?>">
      <button class="btn btn-danger" type="submit" <?= $skuOrders>0?'disabled':'' ?>>Kullanılmamış SKU’yu Sil</button>
    </form>
  </td>
</tr>
<?php endforeach; ?>
</tbody></table></div>
</div></div>

<script>
(function(){
  document.querySelectorAll('.suggested-master-code').forEach(btn => {
    btn.addEventListener('click', () => {
      const input = document.querySelector('input[name="new_master_code"]');
      if (input) input.value = btn.getAttribute('data-code') || btn.textContent.trim();
    });
  });
})();
</script>
<script>
(function(){
  const cut = document.getElementById('slotCut');
  const size = document.getElementById('slotSize');
  if (!cut || !size) return;
  const all = Array.from(size.querySelectorAll('option'));
  function filterSizes(){
    const v = cut.value;
    size.innerHTML = '';
    all.forEach(o => {
      if (!o.value) {
        const c = o.cloneNode(true); c.textContent = v ? 'Ölçü seç' : 'Önce kesim seç'; size.appendChild(c);
      } else if (o.getAttribute('data-cut') === v) {
        size.appendChild(o.cloneNode(true));
      }
    });
  }
  cut.addEventListener('change', filterSizes);
  filterSizes();
})();
</script>
<?php include __DIR__ . '/includes/layout_end.php'; ?>
