<?php
$admin_page = 'urunler';
$admin_title = 'Ürünler';
include 'admin_header.php';

$action = $_GET['action'] ?? 'list';
$id = (int)($_GET['id'] ?? 0);
$msg = ''; $msg_type = '';

// ── SAVE ──
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name       = trim($_POST['name'] ?? '');
    $cat_id     = (int)($_POST['category_id'] ?? 0);
    $short_desc = trim($_POST['short_desc'] ?? '');
    $description= trim($_POST['description'] ?? '');
    $status     = $_POST['status'] ?? 'active';
    $featured   = isset($_POST['featured']) ? 1 : 0;
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $slug       = slugify($name);

    // Specs
    $spec_keys = $_POST['spec_key'] ?? [];
    $spec_vals = $_POST['spec_val'] ?? [];
    $specs = [];
    foreach($spec_keys as $i => $k) {
        if (trim($k) && isset($spec_vals[$i])) $specs[trim($k)] = trim($spec_vals[$i]);
    }
    $specs_json = $specs ? json_encode($specs, JSON_UNESCAPED_UNICODE) : '';

    // Image upload
    $image = $_POST['existing_image'] ?? '';
    if (!empty($_FILES['image']['name'])) {
        $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg','jpeg','png','webp','gif'])) {
            $fname = uniqid('prod_').'.'.$ext;
            $dest = '../assets/uploads/'.$fname;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $dest)) {
                $image = $fname;
            }
        }
    }

    try {
        if ($_POST['edit_id'] ?? 0) {
            $eid = (int)$_POST['edit_id'];
            // Make slug unique if changed
            $existing = db()->prepare("SELECT slug FROM vs_products WHERE id=?");
            $existing->execute([$eid]);
            $old_slug = $existing->fetchColumn();
            if ($old_slug !== $slug) {
                $check = db()->prepare("SELECT id FROM vs_products WHERE slug=? AND id!=?");
                $check->execute([$slug, $eid]);
                if ($check->fetchColumn()) $slug .= '-'.$eid;
            }
            db()->prepare("UPDATE vs_products SET name=?,category_id=?,slug=?,short_desc=?,description=?,specs=?,image=?,status=?,featured=?,sort_order=?,updated_at=NOW() WHERE id=?")
                ->execute([$name,$cat_id?:null,$slug,$short_desc,$description,$specs_json,$image,$status,$featured,$sort_order,$eid]);
            $msg = 'Ürün güncellendi.'; $msg_type = 'success';
            $action = 'edit'; $id = $eid;
        } else {
            $check = db()->prepare("SELECT COUNT(*) FROM vs_products WHERE slug=?");
            $check->execute([$slug]);
            if ($check->fetchColumn()) $slug .= '-'.time();
            db()->prepare("INSERT INTO vs_products (name,category_id,slug,short_desc,description,specs,image,status,featured,sort_order) VALUES (?,?,?,?,?,?,?,?,?,?)")
                ->execute([$name,$cat_id?:null,$slug,$short_desc,$description,$specs_json,$image,$status,$featured,$sort_order]);
            $msg = 'Ürün eklendi.'; $msg_type = 'success';
            $action = 'list';
        }
    } catch(Exception $e) {
        $msg = 'Hata: '.$e->getMessage(); $msg_type = 'error';
    }
}

// ── DELETE ──
if ($action === 'delete' && $id) {
    try {
        db()->prepare("DELETE FROM vs_products WHERE id=?")->execute([$id]);
        $msg = 'Ürün silindi.'; $msg_type = 'success'; $action = 'list';
    } catch(Exception $e) { $msg = 'Silinemedi.'; $msg_type = 'error'; $action = 'list'; }
}

// ── LOAD EDIT ──
$edit_product = null;
if ($action === 'edit' && $id) {
    try {
        $edit_product = db()->prepare("SELECT * FROM vs_products WHERE id=?");
        $edit_product->execute([$id]);
        $edit_product = $edit_product->fetch(PDO::FETCH_ASSOC);
        if (!$edit_product) { $action = 'list'; }
    } catch(Exception $e) { $action = 'list'; }
}

// ── CATEGORIES ──
$cats = [];
try { $cats = db()->query("SELECT * FROM vs_categories ORDER BY sort_order")->fetchAll(PDO::FETCH_ASSOC); } catch(Exception $e) {}

// ── LIST ──
$products = [];
if ($action === 'list') {
    try { $products = db()->query("SELECT p.*,c.name as cat_name FROM vs_products p LEFT JOIN vs_categories c ON p.category_id=c.id ORDER BY p.sort_order,p.id DESC")->fetchAll(PDO::FETCH_ASSOC); } catch(Exception $e) {}
}
?>

<?php if ($msg): ?><div class="alert alert-<?= $msg_type ?>"><?= clean($msg) ?></div><?php endif; ?>

<?php if ($action === 'list'): ?>

<div class="page-header">
    <div><h1>Ürünler</h1><p><?= count($products) ?> ürün</p></div>
    <a href="?action=add" class="btn btn-primary">
        <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>
        Yeni Ürün
    </a>
</div>

<div class="admin-card">
    <table>
        <thead><tr><th>Görsel</th><th>Ürün Adı</th><th>Kategori</th><th>Öne Çıkan</th><th>Durum</th><th>İşlemler</th></tr></thead>
        <tbody>
        <?php if (empty($products)): ?>
        <tr><td colspan="6" style="text-align:center;color:var(--gray);padding:48px;">Henüz ürün yok. <a href="?action=add" style="color:var(--red);">Ekle</a></td></tr>
        <?php else: ?>
        <?php foreach($products as $p): ?>
        <tr>
            <td>
                <?php if ($p['image']): ?>
                <img src="/volker/assets/uploads/<?= clean($p['image']) ?>" class="img-preview" alt="">
                <?php else: ?>
                <div class="img-preview" style="display:flex;align-items:center;justify-content:center;">
                    <svg width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24" style="opacity:0.3;"><rect x="3" y="3" width="18" height="18" rx="2"/></svg>
                </div>
                <?php endif; ?>
            </td>
            <td>
                <strong><?= clean($p['name']) ?></strong><br>
                <small style="color:var(--gray);"><?= clean(mb_substr($p['short_desc'] ?? '', 0, 50)) ?></small>
            </td>
            <td style="color:var(--gray);"><?= clean($p['cat_name'] ?? '—') ?></td>
            <td><?= $p['featured'] ? '<span class="badge badge-green">Evet</span>' : '<span class="badge badge-gray">Hayır</span>' ?></td>
            <td><span class="badge <?= $p['status']=='active'?'badge-green':'badge-gray' ?>"><?= $p['status']=='active'?'Aktif':'Taslak' ?></span></td>
            <td>
                <div style="display:flex;gap:8px;">
                    <a href="?action=edit&id=<?= $p['id'] ?>" class="btn btn-outline btn-sm">Düzenle</a>
                    <a href="/volker/urun.php?slug=<?= clean($p['slug']) ?>" target="_blank" class="btn btn-outline btn-sm">Gör</a>
                    <a href="?action=delete&id=<?= $p['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Bu ürünü silmek istediğinize emin misiniz?')">Sil</a>
                </div>
            </td>
        </tr>
        <?php endforeach; ?>
        <?php endif; ?>
        </tbody>
    </table>
</div>

<?php else: /* ADD / EDIT FORM */ ?>

<?php
$p = $edit_product ?? [];
$p_specs = [];
if (!empty($p['specs'])) { $decoded = json_decode($p['specs'],true); if(is_array($decoded)) $p_specs = $decoded; }
?>

<div class="page-header">
    <div>
        <h1><?= $action==='edit' ? 'Ürünü Düzenle' : 'Yeni Ürün Ekle' ?></h1>
        <p><a href="?action=list" style="color:var(--gray);">← Ürün Listesi</a></p>
    </div>
    <?php if ($action==='edit' && !empty($p['slug'])): ?>
    <a href="/volker/urun.php?slug=<?= clean($p['slug']) ?>" target="_blank" class="btn btn-outline btn-sm">Siteye Gör</a>
    <?php endif; ?>
</div>

<form method="POST" enctype="multipart/form-data">
    <?php if ($action==='edit'): ?><input type="hidden" name="edit_id" value="<?= (int)$p['id'] ?>"><?php endif; ?>

    <div style="display:grid;grid-template-columns:2fr 1fr;gap:24px;align-items:start;">
        <!-- Main Column -->
        <div style="display:flex;flex-direction:column;gap:20px;">
            <div class="admin-card" style="padding:24px;">
                <h3 style="font-size:14px;font-weight:700;margin-bottom:20px;padding-bottom:12px;border-bottom:1px solid rgba(255,255,255,0.06);">Temel Bilgiler</h3>
                <div style="display:flex;flex-direction:column;gap:16px;">
                    <div class="admin-form-group">
                        <label>Ürün Adı *</label>
                        <input type="text" name="name" required value="<?= clean($p['name'] ?? '') ?>">
                    </div>
                    <div class="admin-form-group">
                        <label>Kısa Açıklama</label>
                        <input type="text" name="short_desc" value="<?= clean($p['short_desc'] ?? '') ?>" placeholder="Ürün listesinde görünecek kısa açıklama">
                    </div>
                    <div class="admin-form-group">
                        <label>Detaylı Açıklama</label>
                        <textarea name="description" rows="6"><?= clean($p['description'] ?? '') ?></textarea>
                    </div>
                </div>
            </div>

            <!-- Specs -->
            <div class="admin-card" style="padding:24px;">
                <h3 style="font-size:14px;font-weight:700;margin-bottom:20px;padding-bottom:12px;border-bottom:1px solid rgba(255,255,255,0.06);">Teknik Özellikler</h3>
                <div id="specRows" style="display:flex;flex-direction:column;gap:10px;margin-bottom:16px;">
                    <?php
                    if (!empty($p_specs)) {
                        foreach($p_specs as $k => $v): ?>
                    <div class="spec-row" style="display:grid;grid-template-columns:1fr 1fr auto;gap:8px;align-items:center;">
                        <input type="text" name="spec_key[]" value="<?= clean($k) ?>" placeholder="Özellik adı (örn: Ağırlık)">
                        <input type="text" name="spec_val[]" value="<?= clean($v) ?>" placeholder="Değer (örn: 2.5 kg)">
                        <button type="button" onclick="this.closest('.spec-row').remove()" class="btn btn-danger btn-sm">×</button>
                    </div>
                    <?php endforeach;
                    } else { ?>
                    <div class="spec-row" style="display:grid;grid-template-columns:1fr 1fr auto;gap:8px;align-items:center;">
                        <input type="text" name="spec_key[]" placeholder="Özellik adı (örn: Ağırlık)">
                        <input type="text" name="spec_val[]" placeholder="Değer (örn: 2.5 kg)">
                        <button type="button" onclick="this.closest('.spec-row').remove()" class="btn btn-danger btn-sm">×</button>
                    </div>
                    <?php } ?>
                </div>
                <button type="button" onclick="addSpec()" class="btn btn-outline btn-sm">+ Özellik Ekle</button>
            </div>
        </div>

        <!-- Side Column -->
        <div style="display:flex;flex-direction:column;gap:20px;">
            <div class="admin-card" style="padding:24px;">
                <h3 style="font-size:14px;font-weight:700;margin-bottom:20px;padding-bottom:12px;border-bottom:1px solid rgba(255,255,255,0.06);">Yayın Ayarları</h3>
                <div style="display:flex;flex-direction:column;gap:16px;">
                    <div class="admin-form-group">
                        <label>Durum</label>
                        <select name="status">
                            <option value="active" <?= ($p['status']??'active')==='active'?'selected':'' ?>>Aktif</option>
                            <option value="draft"  <?= ($p['status']??'')==='draft'?'selected':'' ?>>Taslak</option>
                        </select>
                    </div>
                    <div class="admin-form-group">
                        <label>Kategori</label>
                        <select name="category_id">
                            <option value="">Kategori seç</option>
                            <?php foreach($cats as $c): ?>
                            <option value="<?= $c['id'] ?>" <?= ($p['category_id']??'')==$c['id']?'selected':'' ?>><?= clean($c['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="admin-form-group">
                        <label>Sıralama</label>
                        <input type="number" name="sort_order" value="<?= (int)($p['sort_order'] ?? 0) ?>">
                    </div>
                    <div style="display:flex;align-items:center;gap:10px;">
                        <input type="checkbox" name="featured" id="featured" value="1" <?= !empty($p['featured'])?'checked':'' ?> style="width:16px;height:16px;accent-color:var(--red);">
                        <label for="featured" style="font-size:13px;cursor:pointer;">Öne Çıkan Ürün</label>
                    </div>
                </div>
                <div style="margin-top:24px;padding-top:16px;border-top:1px solid rgba(255,255,255,0.06);">
                    <button type="submit" class="btn btn-primary" style="width:100%;">
                        <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
                        <?= $action==='edit' ? 'Güncelle' : 'Kaydet' ?>
                    </button>
                </div>
            </div>

            <!-- Image -->
            <div class="admin-card" style="padding:24px;">
                <h3 style="font-size:14px;font-weight:700;margin-bottom:16px;">Ana Görsel</h3>
                <?php if (!empty($p['image'])): ?>
                <img src="/volker/assets/uploads/<?= clean($p['image']) ?>" style="width:100%;border-radius:4px;margin-bottom:12px;">
                <input type="hidden" name="existing_image" value="<?= clean($p['image']) ?>">
                <?php endif; ?>
                <div class="admin-form-group">
                    <label>Yeni Görsel Yükle</label>
                    <input type="file" name="image" accept="image/*" onchange="previewImg(this)">
                </div>
                <img id="imgPreview" style="width:100%;border-radius:4px;margin-top:8px;display:none;">
            </div>
        </div>
    </div>
</form>

<script>
function addSpec() {
    const row = document.createElement('div');
    row.className = 'spec-row';
    row.style.cssText = 'display:grid;grid-template-columns:1fr 1fr auto;gap:8px;align-items:center;';
    row.innerHTML = '<input type="text" name="spec_key[]" placeholder="Özellik adı"><input type="text" name="spec_val[]" placeholder="Değer"><button type="button" onclick="this.closest(\'.spec-row\').remove()" class="btn btn-danger btn-sm">×</button>';
    document.getElementById('specRows').appendChild(row);
}
function previewImg(input) {
    const preview = document.getElementById('imgPreview');
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = e => { preview.src = e.target.result; preview.style.display = 'block'; };
        reader.readAsDataURL(input.files[0]);
    }
}
</script>

<?php endif; ?>

<?php include 'admin_footer.php'; ?>
