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

$page_title = 'Ürün Tipleri';
$active_menu = 'products';

if (is_post()) {
    verify_csrf();
    $action = $_POST['action'] ?? '';
    try {
        if ($action === 'save_type') {
            $code = strtolower(trim((string)($_POST['category_code'] ?? '')));
            $code = preg_replace('/[^a-z0-9_\-]/', '', $code);
            $label = trim((string)($_POST['type_label'] ?? ''));
            $prefix = strtoupper(trim((string)($_POST['sku_prefix'] ?? '')));
            $prefix = preg_replace('/[^A-Z0-9]/', '', $prefix);
            $sort = (int)($_POST['sort_order'] ?? 100);
            if ($code === '' || $label === '' || $prefix === '') throw new RuntimeException('Kod, ad ve SKU prefix zorunlu.');
            $stmt = db()->prepare("INSERT INTO product_types (category_code, type_label, sku_prefix, sort_order, is_active) VALUES (?,?,?,?,1) ON DUPLICATE KEY UPDATE type_label=VALUES(type_label), sku_prefix=VALUES(sku_prefix), sort_order=VALUES(sort_order), is_active=1, updated_at=NOW()");
            $stmt->execute([$code, $label, $prefix, $sort]);
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Ürün tipi kaydedildi.'];
        }
        if ($action === 'update_type') {
            $code = (string)($_POST['category_code'] ?? '');
            $label = trim((string)($_POST['type_label'] ?? ''));
            $prefix = strtoupper(trim((string)($_POST['sku_prefix'] ?? '')));
            $prefix = preg_replace('/[^A-Z0-9]/', '', $prefix);
            $sort = (int)($_POST['sort_order'] ?? 100);
            $active = !empty($_POST['is_active']) ? 1 : 0;
            if ($code === '' || $label === '' || $prefix === '') throw new RuntimeException('Eksik bilgi var.');
            $stmt = db()->prepare("UPDATE product_types SET type_label=?, sku_prefix=?, sort_order=?, is_active=?, updated_at=NOW() WHERE category_code=?");
            $stmt->execute([$label, $prefix, $sort, $active, $code]);
            $_SESSION['flash'] = ['type'=>'success','msg'=>'Ürün tipi güncellendi.'];
        }
    } catch (Throwable $e) {
        $_SESSION['flash'] = ['type'=>'error','msg'=>'İşlem yapılamadı: '.$e->getMessage()];
    }
    redirect('product_types.php');
}

$rows = product_type_rows(true);
include __DIR__ . '/includes/layout.php';
?>
<div class="ph"><div><h1>Ürün Tipleri</h1><p>SKU ana harfi/prefix’i buradan yönetilir. Örneğin Yüzük=R, Piercing=PI, Şahmeran=SH.</p></div><div><a class="btn btn-secondary" href="products.php">Ürün Kartları</a></div></div>

<div class="card"><div class="card-header"><span class="card-title">Yeni Ürün Tipi Ekle</span></div><div class="card-body">
<form method="post" style="display:grid;grid-template-columns:1fr 2fr 1fr 1fr auto;gap:12px;align-items:end">
<?= csrf_field() ?><input type="hidden" name="action" value="save_type">
<div><label class="form-label">Kod</label><input class="form-control" name="category_code" placeholder="piercing"></div>
<div><label class="form-label">Ad</label><input class="form-control" name="type_label" placeholder="Piercing"></div>
<div><label class="form-label">SKU Prefix</label><input class="form-control" name="sku_prefix" placeholder="PI"></div>
<div><label class="form-label">Sıra</label><input class="form-control" name="sort_order" value="100"></div>
<div><button class="btn btn-primary" type="submit">Ekle</button></div>
</form>
</div></div>

<div class="card"><div class="card-header"><span class="card-title">Tip Listesi</span><span class="c-mt"><?= count($rows) ?> kayıt</span></div><div class="table-wrap"><table><thead><tr><th>Kod</th><th>Ad</th><th>SKU Prefix</th><th>Sıra</th><th>Aktif</th><th>İşlem</th></tr></thead><tbody>
<?php foreach($rows as $r): ?>
<tr><form method="post">
<?= csrf_field() ?><input type="hidden" name="action" value="update_type"><input type="hidden" name="category_code" value="<?= e($r['category_code']) ?>">
<td><strong><?= e($r['category_code']) ?></strong></td>
<td><input class="form-control" name="type_label" value="<?= e($r['type_label']) ?>"></td>
<td><input class="form-control" name="sku_prefix" value="<?= e($r['sku_prefix']) ?>"></td>
<td><input class="form-control" name="sort_order" value="<?= (int)$r['sort_order'] ?>"></td>
<td><input type="checkbox" name="is_active" value="1" <?= (int)$r['is_active']?'checked':'' ?>></td>
<td><button class="btn btn-secondary" type="submit">Kaydet</button></td>
</form></tr>
<?php endforeach; ?>
</tbody></table></div></div>
<?php include __DIR__ . '/includes/layout_end.php'; ?>
