<?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']);

$page_title = 'Ürün Kartları';
$active_menu = 'products';
$user = current_user();
$types = product_type_options();
$materials = product_sample_materials();
$stores = product_stores();
$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 === 'create_product') {
            $category = $_POST['category'] ?? 'ring';
            if (!isset($types[$category])) { $category = 'other'; foreach ($types as $tk => $tv) { $category = $tk; break; } }
            $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);
            $sequence = product_next_sequence($category);
            $masterCode = product_master_code($category, $sequence);
            $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("INSERT INTO products (sequence_number, master_code, product_name, category, avg_gram, created_by) VALUES (?,?,?,?,?,?)");
            $stmt->execute([$sequence, $masterCode, $shortName, $category, $grams['gram_14k'], $user['id'] ?? null]);
            $productId = (int)$pdo->lastInsertId();
            $stmt = $pdo->prepare("INSERT INTO product_core_specs (product_id, 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) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            $stmt->execute([
                $productId,
                $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'] ?? '')),
            ]);
            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 : []);
            if (!empty($_FILES['product_image']['tmp_name']) && is_uploaded_file($_FILES['product_image']['tmp_name'])) {
                product_handle_image_upload($productId, $masterCode, $shortName, $_FILES['product_image'], $user['id'] ?? null);
            }
            $pdo->commit();
            product_audit('product_create', 'product', $productId, null, ['master_code'=>$masterCode,'short_name'=>$shortName,'grams'=>$grams], 'Ürün kartı oluşturuldu');
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Ürün kartı oluşturuldu: '.$masterCode];
            redirect('product_detail.php?id='.$productId);
        }
    } catch (Throwable $e) {
        if (db()->inTransaction()) db()->rollBack();
        $_SESSION['flash'] = ['type'=>'error','msg'=>'İşlem yapılamadı: '.$e->getMessage()];
    }
    redirect('products.php');
}

$q = trim((string)($_GET['q'] ?? ''));
$category = $_GET['category'] ?? '';
$params = [];
$sql = "
    SELECT p.*, s.short_name, s.gram_10k, s.gram_14k, s.gram_18k, s.sample_material_code, sm.material_name AS sample_material_name, s.sample_actual_gram,
           img.file_path AS primary_image_path,
           COUNT(DISTINCT sl.id) AS slot_count,
           COUNT(DISTINCT r.id) AS recipe_count,
           COUNT(DISTINCT sk.id) AS store_sku_count,
           COUNT(DISTINCT psu.id) AS usage_store_count
    FROM products p
    LEFT JOIN product_core_specs s ON s.product_id=p.id
    LEFT JOIN product_sample_materials sm ON sm.material_code=s.sample_material_code
    LEFT JOIN product_images img ON img.product_id=p.id AND img.is_primary=1
    LEFT JOIN product_stone_slots sl ON sl.product_id=p.id AND sl.is_active=1
    LEFT JOIN product_recipes r ON r.product_id=p.id AND r.is_active=1
    LEFT JOIN product_store_recipe_skus sk ON sk.product_id=p.id AND sk.is_active=1
    LEFT JOIN product_store_usage psu ON psu.product_id=p.id
    WHERE p.is_active=1
";
if ($q !== '') {
    $sql .= " AND (p.master_code LIKE :q OR p.product_name LIKE :q OR s.short_name LIKE :q)";
    $params['q'] = '%'.$q.'%';
}
if ($category !== '' && isset($types[$category])) {
    $sql .= " AND p.category = :category";
    $params['category'] = $category;
}
$sql .= " GROUP BY p.id ORDER BY p.category, p.sequence_number DESC, p.id DESC LIMIT 500";
$stmt = db()->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

include __DIR__ . '/includes/layout.php';
?>
<div class="ph">
  <div><h1>Ürün Kartları</h1><p>Ana ürün kartı, fotoğraf, teknik ölçüler, numune gramından otomatik 10K/14K/18K hesabı, mağaza kullanımı, taş slotları ve SKU reçeteleri.</p></div>
  <div style="display:flex;gap:10px"><a class="btn btn-secondary" href="product_types.php">Ürün Tipleri</a><a class="btn btn-secondary" href="stones.php">Taş Kartları</a></div>
</div>

<div class="card"><div class="card-header"><span class="card-title">Yeni Ürün Kartı Aç</span></div><div class="card-body">
<form method="post" enctype="multipart/form-data" style="display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px;align-items:end">
<?= csrf_field() ?><input type="hidden" name="action" value="create_product">
<div><label class="form-label">Ürün Tipi</label><select class="form-control" name="category"><?php foreach($types as $k=>$t): ?><option value="<?= e($k) ?>"><?= e($t['label']) ?> — <?= e($t['letter']) ?></option><?php endforeach; ?></select></div>
<div><label class="form-label">Kısa Ürün Adı</label><input class="form-control" name="short_name" placeholder="Markiz yüzük" required></div>
<div style="grid-column:span 2"><label class="form-label">Kaynak Link</label><input class="form-control" name="source_url" placeholder="https://..."></div>
<div><label class="form-label">Ana Fotoğraf</label><input class="form-control" type="file" name="product_image" accept="image/*"></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']) ?>"><?= 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><?= 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" placeholder="örn 1,05"></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) ?>"><?= 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'] ?>"><?= 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'] ?>"> <?= 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"> Evet</label><?php foreach($stores as $s): ?><label><input type="checkbox" name="charge_store_ids[]" value="<?= (int)$s['id'] ?>"> <?= e($s['store_code']) ?></label><?php endforeach; ?></div></div>
<div><label class="form-label">Genişlik mm</label><input class="form-control" name="width_mm" placeholder="örn 5.2"></div>
<div><label class="form-label">Uzunluk mm</label><input class="form-control" name="length_mm"></div>
<div><label class="form-label">Yükseklik mm</label><input class="form-control" name="height_mm"></div>
<div><label class="form-label">Band Kalınlığı mm</label><input class="form-control" name="band_width_mm"></div>
<div style="grid-column:span 2"><label class="form-label">Not</label><input class="form-control" name="design_note" placeholder="Çizim/numune notu"></div>
<div style="grid-column:span 2"><label class="form-label">Numune Notu</label><input class="form-control" name="sample_note" placeholder="Numune üretim notu"></div>
<div><button class="btn btn-primary" type="submit">Ürün Kartını Aç</button></div>
</form>
<div class="flash flash-info" style="margin-top:14px">10K / 14K / 18K gramları manuel girilmeyecek; numune materyali + numune gerçek gramına göre sistem otomatik hesaplayacak. Numune fiziki durumu ürünün fiziksel numunesinin nerede olduğunu gösterir; ürünü kullanacak mağazalar ve maliyet yansıtılacak mağazalar ayrı seçilir.</div>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Filtrele</span></div><div class="card-body">
<form method="get" style="display:grid;grid-template-columns:2fr 1fr auto auto;gap:12px;align-items:end">
<div><label class="form-label">Arama</label><input class="form-control" name="q" value="<?= e($q) ?>" placeholder="SKU / kısa ad"></div>
<div><label class="form-label">Tip</label><select class="form-control" name="category"><option value="">Tümü</option><?php foreach($types as $k=>$t): ?><option value="<?= e($k) ?>" <?= $category===$k?'selected':'' ?>><?= e($t['label']) ?></option><?php endforeach; ?></select></div>
<div><button class="btn btn-secondary" type="submit">Ara</button></div><div><a class="btn btn-secondary" href="products.php">Temizle</a></div>
</form>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Ürün Listesi</span><span class="c-mt"><?= count($rows) ?> kayıt gösteriliyor</span></div><div class="table-wrap"><table><thead><tr><th>Foto</th><th>Ana SKU</th><th>Kısa Ad</th><th>Tip</th><th>Taş Durumu</th><th>Kullanan Mağaza</th><th>Numune</th><th>10K</th><th>14K</th><th>18K</th><th>Reçete</th><th>Mağaza SKU</th><th>İşlem</th></tr></thead><tbody>
<?php if (!$rows): ?><tr><td colspan="13" class="c-mt">Henüz ürün kartı yok.</td></tr><?php endif; ?>
<?php foreach($rows as $r): ?>
<tr>
<td><?php if($r['primary_image_path']): ?><img src="<?= e($r['primary_image_path']) ?>" style="width:50px;height:50px;object-fit:cover;border-radius:8px;border:1px solid var(--border)"><?php else: ?><span class="c-mt">-</span><?php endif; ?></td>
<td><strong><?= e($r['master_code']) ?></strong></td>
<td><?= e($r['short_name'] ?: $r['product_name']) ?></td>
<td><?= e(product_type_label($r['category'])) ?></td>
<td><?= (int)$r['slot_count'] > 0 ? 'Taşlı' : 'Taşsız' ?></td>
<td><?= (int)$r['usage_store_count'] ?></td>
<td><?= e(($r['sample_material_name'] ?: '-').' / '.($r['sample_actual_gram'] !== null ? number_format((float)$r['sample_actual_gram'],3).' gr' : '-')) ?></td>
<td><?= $r['gram_10k'] !== null ? e(number_format((float)$r['gram_10k'],3)) : '-' ?></td>
<td><?= $r['gram_14k'] !== null ? e(number_format((float)$r['gram_14k'],3)) : '-' ?></td>
<td><?= $r['gram_18k'] !== null ? e(number_format((float)$r['gram_18k'],3)) : '-' ?></td>
<td><?= (int)$r['recipe_count'] ?></td>
<td><?= (int)$r['store_sku_count'] ?></td>
<td><a class="btn btn-secondary" href="product_detail.php?id=<?= (int)$r['id'] ?>">Kart</a></td>
</tr>
<?php endforeach; ?>
</tbody></table></div></div>
<?php include __DIR__ . '/includes/layout_end.php'; ?>
