<?php
// Dışa aktarma
$export = get('disa', '');
if ($export === 'urunler') {
    csv_download('urunler-' . date('Y-m-d') . '.csv',
        ['id', 'ad', 'kategori', 'fiyat', 'eski_fiyat', 'stok', 'satis', 'durum', 'aciklama'],
        db_all('SELECT p.id, p.name, c.name, p.price, p.old_price, p.stock, p.sold, p.status, p.description FROM products p LEFT JOIN categories c ON c.id = p.category_id ORDER BY p.id'));
}
if ($export === 'siparisler') {
    csv_download('siparisler-' . date('Y-m-d') . '.csv',
        ['no', 'tarih', 'musteri', 'eposta', 'telefon', 'il', 'ilce', 'odeme', 'durum', 'ara_toplam', 'indirim', 'kargo', 'toplam'],
        db_all('SELECT order_no, created_at, name, email, phone, city, district, payment, status, subtotal, discount, shipping, total FROM orders ORDER BY id DESC'));
}
if ($export === 'musteriler') {
    csv_download('musteriler-' . date('Y-m-d') . '.csv',
        ['ad', 'eposta', 'telefon', 'kayit', 'siparis_sayisi', 'harcama'],
        db_all("SELECT c.name, c.email, c.phone, c.created_at, COUNT(o.id), COALESCE(SUM(CASE WHEN o.status != 'iptal' THEN o.total END), 0) FROM customers c LEFT JOIN orders o ON o.customer_id = c.id GROUP BY c.id ORDER BY c.id"));
}

if (is_post()) {
    csrf_check();

    // Toplu fiyat güncelleme
    if (post('action') === 'prices') {
        $percent = (float) str_replace(',', '.', post('percent', '0'));
        if ($percent == 0 || $percent < -90 || $percent > 500) {
            reply(false, 'Geçerli bir yüzde girin (-90 ile 500 arası, 0 hariç).');
        }
        $where = 'status IN (0, 1)';
        $params = [];
        if (post_int('category_id')) {
            $ids = category_children_ids(post_int('category_id'), false);
            $where .= ' AND category_id IN (' . db_in($ids) . ')';
            $params = $ids;
        }
        $factor = 1 + $percent / 100;
        $round = post('round', 'none');
        $count = 0;
        foreach (db_all("SELECT id, price, old_price FROM products WHERE $where", $params) as $product) {
            $price = price_round($product['price'] * $factor, $round);
            $data = ['price' => max(0, $price)];
            if (checked('old_price') && $product['old_price']) {
                $data['old_price'] = price_round($product['old_price'] * $factor, $round);
            }
            db_update('products', $data, $product['id']);
            db_query('UPDATE product_variants SET price = ROUND(price * ?, 2) WHERE product_id = ? AND price IS NOT NULL', [$factor, $product['id']]);
            $count++;
        }
        log_action('Toplu fiyat güncelledi', ($percent > 0 ? '+' : '') . $percent . '% · ' . $count . ' ürün');
        finish($count . ' ürünün fiyatı güncellendi.', admin_url('araclar'));
    }

    // CSV'den ürün içe aktarma
    if (post('action') === 'import') {
        $file = uploaded('csv');
        if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
            reply(false, 'CSV dosyası seçin.');
        }
        $rows = csv_read($file['tmp_name']);
        $created = $updated = 0;
        foreach ($rows as $row) {
            $name = trim($row['ad'] ?? $row['name'] ?? '');
            if ($name === '') {
                continue;
            }
            $category_name = trim($row['kategori'] ?? $row['category'] ?? '');
            $category_id = null;
            if ($category_name !== '') {
                $category = db_one('SELECT id FROM categories WHERE name = ?', [$category_name]);
                $category_id = $category['id'] ?? db_insert('categories', ['name' => $category_name, 'slug' => unique_slug('categories', $category_name)]);
            }
            $data = array_filter([
                'name'        => $name,
                'category_id' => $category_id,
                'price'       => to_decimal($row['fiyat'] ?? $row['price'] ?? ''),
                'old_price'   => to_decimal($row['eski_fiyat'] ?? $row['old_price'] ?? ''),
                'stock'       => isset($row['stok']) || isset($row['stock']) ? (int) ($row['stok'] ?? $row['stock']) : null,
                'status'      => isset($row['durum']) ? ((int) $row['durum'] ? 1 : 0) : null,
                'description' => $row['aciklama'] ?? $row['description'] ?? null,
            ], fn($value) => $value !== null && $value !== '');

            $existing = !empty($row['id']) ? db_find('products', (int) $row['id']) : db_one('SELECT * FROM products WHERE name = ?', [$name]);
            if ($existing) {
                db_update('products', $data, $existing['id']);
                $updated++;
            } else {
                db_insert('products', $data + ['slug' => unique_slug('products', $name), 'price' => $data['price'] ?? 0]);
                $created++;
            }
        }
        log_action('CSV ile ürün aktardı', "$created yeni, $updated güncel");
        finish("İçe aktarma tamamlandı: $created yeni ürün, $updated güncellendi.", admin_url('araclar'));
    }
}

admin_header('Araçlar');
?>

<div class="grid gap-6 xl:grid-cols-2">
    <div class="card p-6">
        <h2 class="flex items-center gap-2 font-semibold"><?= icon('document', 'size-5') ?>Dışa aktar</h2>
        <p class="mt-1 text-sm text-zinc-500">Excel ile açılabilen CSV dosyaları.</p>
        <div class="mt-5 grid gap-2 sm:grid-cols-3">
            <?php foreach (['urunler' => ['Ürünler', 'cube'], 'siparisler' => ['Siparişler', 'cart'], 'musteriler' => ['Müşteriler', 'users']] as $key => [$label, $name]): ?>
                <a href="<?= admin_url('araclar?disa=' . $key) ?>" data-no-pjax class="flex items-center gap-3 rounded-xl border border-zinc-200 p-4 text-sm font-medium transition hover:border-ink"><?= icon($name, 'size-5 text-zinc-400') ?><?= $label ?></a>
            <?php endforeach ?>
        </div>
    </div>

    <form method="post" enctype="multipart/form-data" class="card space-y-4 p-6">
        <?= csrf_field() ?>
        <h2 class="flex items-center gap-2 font-semibold"><?= icon('refresh', 'size-5') ?>Ürünleri CSV'den içe aktar</h2>
        <p class="text-sm leading-6 text-zinc-500">Sütunlar: <code class="rounded bg-zinc-100 px-1.5 py-0.5 text-xs">id, ad, kategori, fiyat, eski_fiyat, stok, durum, aciklama</code>. Aynı id ya da ada sahip ürün varsa güncellenir, yoksa eklenir. Olmayan kategoriler oluşturulur. Dışa aktarılan dosyayı düzenleyip geri yükleyebilirsiniz.</p>
        <input type="file" name="csv" accept=".csv,text/csv" required class="block w-full text-sm text-zinc-600 file:mr-3 file:rounded-lg file:border-0 file:bg-ink file:px-4 file:py-2 file:text-sm file:font-semibold file:text-white">
        <button name="action" value="import" class="btn-primary" data-confirm="Ürünler içe aktarılsın mı?">İçe aktar</button>
    </form>

    <form method="post" class="card space-y-5 p-6 xl:col-span-2">
        <?= csrf_field() ?>
        <h2 class="flex items-center gap-2 font-semibold"><?= icon('tag', 'size-5') ?>Toplu fiyat güncelleme</h2>
        <div class="grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
            <div>
                <label class="label">Kategori</label>
                <select name="category_id" class="input">
                    <option value="">Tüm ürünler</option>
                    <?php foreach (category_tree() as $category): ?>
                        <option value="<?= $category['id'] ?>"><?= str_repeat('— ', $category['depth']) . e($category['name']) ?></option>
                    <?php endforeach ?>
                </select>
            </div>
            <div>
                <label class="label">Değişim (%)</label>
                <input name="percent" inputmode="decimal" class="input" placeholder="Zam için 10, indirim için -10" required>
            </div>
            <div>
                <label class="label">Yuvarlama</label>
                <select name="round" class="input">
                    <option value="none">Yuvarlama yok</option>
                    <option value="int">Tam sayıya (149,00)</option>
                    <option value="90">,90 ile bitir (149,90)</option>
                    <option value="99">,99 ile bitir (149,99)</option>
                </select>
            </div>
            <label class="flex items-center gap-3 self-end rounded-xl border border-zinc-200 px-4 py-3 text-sm font-medium">
                <input type="checkbox" name="old_price" value="1" class="size-4 rounded accent-ink" checked> Eski fiyatları da güncelle
            </label>
        </div>
        <p class="text-xs text-zinc-500">Varyantlara özel fiyatlar da aynı oranda değişir. Bu işlem geri alınamaz, önce ürünleri dışa aktarmanız önerilir.</p>
        <button name="action" value="prices" class="btn-primary" data-confirm="Fiyatlar toplu olarak güncellensin mi? Bu işlem geri alınamaz.">Fiyatları güncelle</button>
    </form>
</div>

<?php admin_footer() ?>
