'use strict';
const express = require('express');
const path = require('path');
const fs = require('fs');
const multer = require('multer');
const { db, categoriesList, uniqueSlug, setSetting, getAllSettings, SIZE_TYPES, sizeOptions } = require('../db');
const { sign, requireAdmin } = require('../middleware/auth');

const router = express.Router();

const SIZE_TYPE_LABELS = { none: 'No sizes', clothing: 'Clothing', shoes: 'Shoes' };
function sizeTypeLabel(t) { return SIZE_TYPE_LABELS[t] || 'No sizes'; }

const PRODUCT_IMG_DIR = path.join(__dirname, '..', 'public', 'images', 'products');
const TEST_IMG_DIR = path.join(__dirname, '..', 'public', 'images', 'testimonials');
if (!fs.existsSync(TEST_IMG_DIR)) fs.mkdirSync(TEST_IMG_DIR, { recursive: true });

function slugifyName(text) {
  return String(text)
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, PRODUCT_IMG_DIR),
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname).toLowerCase().replace(/[^a-z0-9.]/g, '') || '.jpg';
    const base = slugifyName(path.basename(file.originalname, ext)).slice(0, 40) || 'image';
    cb(null, `${base}-${Date.now()}-${Math.floor(Math.random() * 9999)}${ext}`);
  },
});
const upload = multer({
  storage,
  limits: { fileSize: 10 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    if (/^image\//.test(file.mimetype)) cb(null, true);
    else cb(new Error('Only image files are allowed.'));
  },
});

const tesStorage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, TEST_IMG_DIR),
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname).toLowerCase().replace(/[^a-z0-9.]/g, '') || '.jpg';
    cb(null, `testimonial-${Date.now()}-${Math.floor(Math.random() * 9999)}${ext}`);
  },
});
const tesUpload = multer({
  storage: tesStorage,
  limits: { fileSize: 10 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    if (/^image\//.test(file.mimetype)) cb(null, true);
    else cb(new Error('Only image files are allowed.'));
  },
});

function money(n) {
  return 'R ' + Number(n || 0).toLocaleString('en-ZA', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

router.get('/login', (req, res) => {
  if (req.user && req.user.is_admin) return res.redirect('/admin');
  res.render('admin/login', { title: 'Admin login | TOUS CINO', error: null });
});

router.post('/login', (req, res) => {
  const { email, password } = req.body;
  const user = db.prepare('SELECT * FROM users WHERE email = ?').get(String(email || '').toLowerCase());
  const bcrypt = require('bcryptjs');
  if (!user || !user.is_admin || !bcrypt.compareSync(String(password || ''), user.password_hash)) {
    return res.render('admin/login', { title: 'Admin login | TOUS CINO', error: 'Access denied. Invalid admin credentials.' });
  }
  res.cookie('tc_token', sign(user), { httpOnly: true, sameSite: 'lax', maxAge: 30 * 24 * 3600 * 1000 });
  res.redirect('/admin');
});

router.get('/logout', (req, res) => {
  res.clearCookie('tc_token');
  res.redirect('/admin/login');
});

router.use(requireAdmin);

router.use((req, res, next) => {
  res.locals.adminPath = req.path;
  next();
});

router.get('/', (req, res) => {
  const stats = {
    products: db.prepare('SELECT COUNT(*) c FROM products').get().c,
    live: db.prepare("SELECT COUNT(*) c FROM products WHERE status='live'").get().c,
    lowStock: db.prepare('SELECT COUNT(*) c FROM products WHERE stock <= 5 AND status=\'live\'').get().c,
    orders: db.prepare('SELECT COUNT(*) c FROM orders').get().c,
    revenue: db.prepare("SELECT COALESCE(SUM(total),0) t FROM orders WHERE status NOT IN ('cancelled')").get().t,
    pending: db.prepare("SELECT COUNT(*) c FROM orders WHERE status='pending'").get().c,
    customers: db.prepare('SELECT COUNT(*) c FROM users').get().c,
    unreadMessages: db.prepare('SELECT COUNT(*) c FROM messages WHERE is_read = 0').get().c,
  };
  const recentOrders = db.prepare('SELECT * FROM orders ORDER BY created_at DESC LIMIT 8').all();
  const unassigned = db.prepare('SELECT COUNT(*) c FROM products WHERE category_id IS NULL').get().c;
  const noPrice = db.prepare('SELECT COUNT(*) c FROM products WHERE price IS NULL OR price <= 0').get().c;
  res.render('admin/dashboard', {
    title: 'Dashboard | TOUS CINO Admin',
    stats,
    recentOrders,
    money,
    unassigned,
    noPrice,
  });
});

/* ---------------- Products ---------------- */

router.get('/products', (req, res) => {
  const q = String(req.query.q || '').trim();
  const cat = req.query.cat ? Number(req.query.cat) : 0;
  const status = String(req.query.status || '');
  const st = String(req.query.st || '');
  let sql = 'SELECT p.*, c.name AS category_name FROM products p LEFT JOIN categories c ON c.id = p.category_id WHERE 1=1';
  const params = [];
  if (q) { sql += ' AND (p.name LIKE ? OR p.sku LIKE ?)'; params.push(`%${q}%`, `%${q}%`); }
  if (cat) { sql += ' AND p.category_id = ?'; params.push(cat); }
  if (status) { sql += ' AND p.status = ?'; params.push(status); }
  if (st) { sql += ' AND p.size_type = ?'; params.push(st); }
  sql += ' ORDER BY p.id';
  const products = db.prepare(sql).all(...params);
  res.render('admin/products', {
    title: 'Products | TOUS CINO Admin',
    products,
    categories: categoriesList(),
    q,
    cat,
    status,
    st,
    money,
    sizeTypeLabel,
  });
});

router.get('/products/new', (req, res) => {
  res.render('admin/product-form', {
    title: 'New product | TOUS CINO Admin',
    product: null,
    gallery: [],
    categories: categoriesList(),
    error: null,
    sizeTypes: SIZE_TYPES,
    clothingSizes: sizeOptions('clothing'),
    shoesSizes: sizeOptions('shoes'),
  });
});

router.post('/products', upload.single('image'), (req, res) => {
  const { name, description, category_id, price, compare_at_price, stock, sku, status, featured } = req.body;
  if (!name) {
    return res.render('admin/product-form', {
      title: 'New product | TOUS CINO Admin',
      product: null, gallery: [], categories: categoriesList(),
      error: 'Product name is required.',
    });
  }
  const sizeType = String(req.body.size_type || 'none');
  const sizesRaw = Array.isArray(req.body.sizes) ? req.body.sizes : String(req.body.sizes || '').split(/[\s,]+/);
  const sizesText = sizeType === 'none' ? '' : sizesRaw.map((s) => String(s).trim()).filter(Boolean).join(',');
  const image = req.file ? req.file.filename : '';
  const info = db
    .prepare(
      `INSERT INTO products (name, slug, description, category_id, price, compare_at_price, stock, sku, image, status, featured, sizes, size_type)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
    )
    .run(
      String(name).trim(),
      uniqueSlug(name),
      String(description || ''),
      category_id ? Number(category_id) : null,
      price === '' || price == null ? null : Number(price),
      compare_at_price === '' || compare_at_price == null ? null : Number(compare_at_price),
      Number(stock || 0),
      String(sku || ''),
      image,
      status || 'draft',
      featured ? 1 : 0,
      sizesText,
      sizeType
    );
  if (image) {
    db.prepare('INSERT INTO product_images (product_id, image, alt, sort_order) VALUES (?, ?, ?, 0)').run(
      info.lastInsertRowid, image, String(name).trim()
    );
  }
  res.redirect('/admin/products');
});

router.get('/products/:id', (req, res) => {
  const product = db.prepare('SELECT * FROM products WHERE id = ?').get(Number(req.params.id));
  if (!product) return res.redirect('/admin/products');
  const gallery = db.prepare('SELECT * FROM product_images WHERE product_id = ? ORDER BY sort_order').all(product.id);
  res.render('admin/product-form', {
    title: `Edit: ${product.name} | TOUS CINO Admin`,
    product, gallery, categories: categoriesList(), error: null,
    sizeTypes: SIZE_TYPES,
    clothingSizes: sizeOptions('clothing'),
    shoesSizes: sizeOptions('shoes'),
  });
});

router.post('/products/:id', upload.single('image'), (req, res) => {
  const id = Number(req.params.id);
  const product = db.prepare('SELECT * FROM products WHERE id = ?').get(id);
  if (!product) return res.redirect('/admin/products');
  const { name, description, category_id, price, compare_at_price, stock, sku, status, featured } = req.body;
  const sizeType = String(req.body.size_type || product.size_type || 'none');
  const sizesRaw = Array.isArray(req.body.sizes) ? req.body.sizes : String(req.body.sizes || '').split(/[\s,]+/);
  const sizesText = sizeType === 'none' ? '' : sizesRaw.map((s) => String(s).trim()).filter(Boolean).join(',');
  const image = req.file ? req.file.filename : product.image;
  db.prepare(
    `UPDATE products SET name=?, slug=?, description=?, category_id=?, price=?, compare_at_price=?, stock=?, sku=?, image=?, status=?, featured=?, sizes=?, size_type=?, updated_at=datetime('now') WHERE id=?`
  ).run(
    String(name || '').trim() || product.name,
    uniqueSlug(name || product.name, 'products', id),
    String(description || ''),
    category_id ? Number(category_id) : null,
    price === '' || price == null ? null : Number(price),
    compare_at_price === '' || compare_at_price == null ? null : Number(compare_at_price),
    Number(stock || 0),
    String(sku || ''),
    image,
    status || 'draft',
    featured ? 1 : 0,
    sizesText,
    sizeType,
    id
  );
  if (req.file) {
    db.prepare('INSERT INTO product_images (product_id, image, alt, sort_order) VALUES (?, ?, ?, 99)').run(
      id, req.file.filename, String(name || product.name).trim()
    );
  }
  res.redirect(`/admin/products/${id}?saved=1`);
});

router.post('/products/:id/delete', (req, res) => {
  const id = Number(req.params.id);
  const product = db.prepare('SELECT * FROM products WHERE id = ?').get(id);
  if (product && product.image) {
    const p = path.join(PRODUCT_IMG_DIR, product.image);
    if (fs.existsSync(p)) fs.unlinkSync(p);
  }
  const imgs = db.prepare('SELECT image FROM product_images WHERE product_id = ?').all(id);
  for (const im of imgs) {
    const p = path.join(PRODUCT_IMG_DIR, im.image);
    if (fs.existsSync(p)) fs.unlinkSync(p);
  }
  db.prepare('DELETE FROM products WHERE id = ?').run(id);
  res.redirect('/admin/products');
});

router.post('/products/:id/gallery', upload.array('images', 8), (req, res) => {
  const id = Number(req.params.id);
  if (req.files && req.files.length) {
    let count = db.prepare('SELECT COUNT(*) c FROM product_images WHERE product_id = ?').get(id).c;
    const stmt = db.prepare('INSERT INTO product_images (product_id, image, alt, sort_order) VALUES (?, ?, ?, ?)');
    req.files.forEach((file) => {
      stmt.run(id, file.filename, '', count++);
    });
  }
  res.redirect(`/admin/products/${id}?saved=1`);
});

router.post('/gallery/:id/primary', (req, res) => {
  const gid = Number(req.params.id);
  const img = db.prepare('SELECT * FROM product_images WHERE id = ?').get(gid);
  if (img) {
    db.prepare('UPDATE products SET image = ?, updated_at = datetime(\'now\') WHERE id = ?').run(img.image, img.product_id);
    res.redirect(`/admin/products/${img.product_id}?saved=1`);
  } else {
    res.redirect('/admin/products');
  }
});

router.post('/gallery/:id/delete', (req, res) => {
  const gid = Number(req.params.id);
  const img = db.prepare('SELECT * FROM product_images WHERE id = ?').get(gid);
  if (img) {
    const p = path.join(PRODUCT_IMG_DIR, img.image);
    if (fs.existsSync(p)) fs.unlinkSync(p);
    db.prepare('DELETE FROM product_images WHERE id = ?').run(gid);
    res.redirect(`/admin/products/${img.product_id}?saved=1`);
  } else {
    res.redirect('/admin/products');
  }
});

router.post('/products/bulk/category', (req, res) => {
  const { ids, category_id } = req.body;
  const list = Array.isArray(ids) ? ids : [];
  if (category_id && list.length) {
    const stmt = db.prepare('UPDATE products SET category_id = ? WHERE id = ?');
    for (const id of list) stmt.run(Number(category_id), Number(id));
  }
  res.redirect('/admin/products');
});

/* ---------------- Categories ---------------- */

router.get('/categories', (req, res) => {
  res.render('admin/categories', { title: 'Categories | TOUS CINO Admin', categories: categoriesList() });
});

router.post('/categories', (req, res) => {
  const { name, description, slug } = req.body;
  if (!name) return res.redirect('/admin/categories');
  db.prepare('INSERT INTO categories (slug, name, description, sort_order) VALUES (?, ?, ?, ?)').run(
    uniqueSlug(slug || name, 'categories'),
    String(name).trim(),
    String(description || ''),
    99
  );
  res.redirect('/admin/categories');
});

router.post('/categories/:id', (req, res) => {
  const id = Number(req.params.id);
  const { name, description, slug } = req.body;
  db.prepare('UPDATE categories SET name=?, slug=?, description=? WHERE id=?').run(
    String(name || '').trim() || 'Category',
    uniqueSlug(slug || name || 'category', 'categories', id),
    String(description || ''),
    id
  );
  res.redirect('/admin/categories');
});

router.post('/categories/:id/delete', (req, res) => {
  db.prepare('DELETE FROM categories WHERE id = ?').run(Number(req.params.id));
  res.redirect('/admin/categories');
});

/* ---------------- Orders ---------------- */

router.get('/orders', (req, res) => {
  const status = String(req.query.status || '');
  let sql = 'SELECT * FROM orders';
  const params = [];
  if (status) { sql += ' WHERE status = ?'; params.push(status); }
  sql += ' ORDER BY created_at DESC';
  const orders = db.prepare(sql).all(...params);
  res.render('admin/orders', { title: 'Orders | TOUS CINO Admin', orders, status, money });
});

router.get('/orders/:id', (req, res) => {
  const order = db.prepare('SELECT * FROM orders WHERE id = ?').get(Number(req.params.id));
  if (!order) return res.redirect('/admin/orders');
  const items = db.prepare('SELECT * FROM order_items WHERE order_id = ?').all(order.id);
  res.render('admin/order-detail', { title: `Order ${order.order_number}`, order, items, money });
});

router.post('/orders/:id', (req, res) => {
  const id = Number(req.params.id);
  const order = db.prepare('SELECT * FROM orders WHERE id = ?').get(id);
  if (!order) return res.redirect('/admin/orders');
  const { status, payment_status } = req.body;
  const newStatus = status || order.status || 'pending';
  db.prepare('UPDATE orders SET status = ?, payment_status = ? WHERE id = ?').run(
    newStatus, payment_status || order.payment_status || 'unpaid', id
  );
  if (['fulfilled', 'completed'].includes(newStatus) && !order.review_requested) {
    db.prepare('UPDATE orders SET review_requested = 1 WHERE id = ?').run(id);
    require('../lib/mail')
      .sendMail({
        to: order.email,
        subject: `How was your order, ${order.name}? Leave a review for TOUS CINO`,
        html: require('../lib/mail').reviewRequestEmailHtml(order),
        text: `Hi ${order.name},\n\nYour order ${order.order_number} has been fulfilled — thank you for shopping with TOUS CINO.\n\nWe'd love your feedback. Leave a review here: http://localhost:3000/?leave-review=1\n\nNo pressure if you'd rather not.`,
      })
      .then(() => {})
      .catch(() => {});
  }
  res.redirect(`/admin/orders/${id}?saved=1`);
});

/* ---------------- Customers ---------------- */

router.get('/customers', (req, res) => {
  const customers = db
    .prepare(
      `SELECT u.*, (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count,
              (SELECT COALESCE(SUM(o.total),0) FROM orders o WHERE o.user_id = u.id) AS spend
       FROM users u ORDER BY u.created_at DESC`
    )
    .all();
  res.render('admin/customers', { title: 'Customers | TOUS CINO Admin', customers, money });
});

/* ---------------- Coupons ---------------- */

router.get('/coupons', (req, res) => {
  const coupons = db.prepare('SELECT * FROM coupons ORDER BY id DESC').all();
  res.render('admin/coupons', { title: 'Discount codes | TOUS CINO Admin', coupons, money });
});

router.post('/coupons', (req, res) => {
  const { code, type, value, min_subtotal, usage_limit, expires_at } = req.body;
  if (!code) return res.redirect('/admin/coupons');
  db.prepare(
    'INSERT INTO coupons (code, type, value, min_subtotal, usage_limit, expires_at, active) VALUES (?, ?, ?, ?, ?, ?, 1)'
  ).run(
    String(code).trim().toUpperCase(),
    type === 'fixed' ? 'fixed' : 'percent',
    Number(value || 0),
    Number(min_subtotal || 0),
    Number(usage_limit || 0),
    expires_at || null
  );
  res.redirect('/admin/coupons');
});

router.post('/coupons/:id/toggle', (req, res) => {
  db.prepare('UPDATE coupons SET active = CASE WHEN active = 1 THEN 0 ELSE 1 END WHERE id = ?').run(Number(req.params.id));
  res.redirect('/admin/coupons');
});

router.post('/coupons/:id/delete', (req, res) => {
  db.prepare('DELETE FROM coupons WHERE id = ?').run(Number(req.params.id));
  res.redirect('/admin/coupons');
});

/* ---------------- Reviews ---------------- */

router.get('/reviews', (req, res) => {
  const reviews = db
    .prepare(
      `SELECT r.*, p.name AS product_name FROM reviews r
       LEFT JOIN products p ON p.id = r.product_id
       ORDER BY r.created_at DESC`
    )
    .all();
  const products = db.prepare('SELECT id, name FROM products ORDER BY name').all();
  res.render('admin/reviews', { title: 'Reviews | TOUS CINO Admin', reviews, products });
});

router.post('/reviews', (req, res) => {
  const { name, city, title, body, rating, product_id, approved } = req.body;
  if (!name || !body) return res.redirect('/admin/reviews');
  db.prepare(
    'INSERT INTO reviews (product_id, name, city, title, body, rating, approved) VALUES (?, ?, ?, ?, ?, ?, ?)'
  ).run(
    product_id ? Number(product_id) : null,
    String(name).trim(),
    String(city || '').trim(),
    String(title || '').trim(),
    String(body).trim(),
    Math.min(5, Math.max(1, Math.round(Number(rating) || 5))),
    approved ? 1 : 0
  );
  res.redirect('/admin/reviews');
});

router.post('/reviews/:id/approve', (req, res) => {
  db.prepare('UPDATE reviews SET approved = CASE WHEN approved = 1 THEN 0 ELSE 1 END WHERE id = ?').run(Number(req.params.id));
  res.redirect('/admin/reviews');
});

router.post('/reviews/:id/delete', (req, res) => {
  db.prepare('DELETE FROM reviews WHERE id = ?').run(Number(req.params.id));
  res.redirect('/admin/reviews');
});

/* ---------------- Testimonials ---------------- */

router.get('/testimonials', (req, res) => {
  const testimonials = db.prepare('SELECT * FROM testimonials ORDER BY sort_order, id DESC').all();
  res.render('admin/testimonials', { title: 'Testimonials | TOUS CINO Admin', testimonials, money });
});

router.post('/testimonials', tesUpload.single('photo'), (req, res) => {
  const { customer_name, location, product, text, rating, approved } = req.body;
  if (!customer_name || !text) return res.redirect('/admin/testimonials');
  const photo = req.file ? req.file.filename : '';
  db.prepare(
    'INSERT INTO testimonials (customer_name, location, product_name, text, rating, photo, approved, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, (SELECT COALESCE(MAX(sort_order),0)+1 FROM testimonials))'
  ).run(
    String(customer_name).trim(),
    String(location || '').trim(),
    String(product || '').trim(),
    String(text).trim(),
    Math.min(5, Math.max(1, Math.round(Number(rating) || 5))),
    photo,
    approved ? 1 : 0
  );
  res.redirect('/admin/testimonials');
});

router.post('/testimonials/:id', tesUpload.single('photo'), (req, res) => {
  const id = Number(req.params.id);
  const t = db.prepare('SELECT * FROM testimonials WHERE id = ?').get(id);
  if (!t) return res.redirect('/admin/testimonials');
  const { customer_name, location, product, text, rating, approved, sort_order } = req.body;
  const photo = req.file ? req.file.filename : t.photo;
  db.prepare(
    `UPDATE testimonials SET customer_name=?, location=?, product_name=?, text=?, rating=?, photo=?, approved=?, sort_order=? WHERE id=?`
  ).run(
    String(customer_name || '').trim() || t.customer_name,
    String(location || '').trim(),
    String(product || '').trim(),
    String(text || '').trim(),
    Math.min(5, Math.max(1, Math.round(Number(rating) || t.rating))),
    photo,
    approved !== undefined ? 1 : 0,
    sort_order === '' || sort_order == null ? t.sort_order : Number(sort_order),
    id
  );
  res.redirect('/admin/testimonials');
});

router.post('/testimonials/:id/toggle', (req, res) => {
  db.prepare('UPDATE testimonials SET approved = CASE WHEN approved = 1 THEN 0 ELSE 1 END WHERE id = ?').run(Number(req.params.id));
  res.redirect('/admin/testimonials');
});

router.post('/testimonials/:id/delete', (req, res) => {
  const t = db.prepare('SELECT * FROM testimonials WHERE id = ?').get(Number(req.params.id));
  if (t && t.photo) {
    const p = path.join(TEST_IMG_DIR, t.photo);
    if (fs.existsSync(p)) fs.unlinkSync(p);
  }
  db.prepare('DELETE FROM testimonials WHERE id = ?').run(Number(req.params.id));
  res.redirect('/admin/testimonials');
});

/* ---------------- Messages ---------------- */

router.get('/messages', (req, res) => {
  const messages = db.prepare('SELECT * FROM messages ORDER BY created_at DESC').all();
  res.render('admin/messages', { title: 'Messages | TOUS CINO Admin', messages });
});

router.post('/messages/:id/read', (req, res) => {
  db.prepare('UPDATE messages SET is_read = 1 WHERE id = ?').run(Number(req.params.id));
  res.redirect('/admin/messages');
});

router.post('/messages/:id/delete', (req, res) => {
  db.prepare('DELETE FROM messages WHERE id = ?').run(Number(req.params.id));
  res.redirect('/admin/messages');
});

/* ---------------- Settings ---------------- */

router.get('/settings', (req, res) => {
  res.render('admin/settings', {
    title: 'Settings | TOUS CINO Admin',
    s: getAllSettings(),
  });
});

router.post('/settings', (req, res) => {
  const allowed = [
    'store_name', 'slogan', 'tagline', 'address', 'phone', 'whatsapp', 'email', 'facebook', 'instagram',
    'business_hours', 'currency', 'shipping_fee', 'free_shipping_threshold', 'maps_url',
    'payfast_merchant_id', 'payfast_merchant_key', 'payfast_passphrase', 'payfast_sandbox',
    'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_secure', 'smtp_from',
  ];
  for (const key of allowed) {
    if (req.body[key] !== undefined) setSetting(key, req.body[key]);
  }
  res.redirect('/admin/settings?saved=1');
});

/* ---------------- Import images from folder ---------------- */

router.post('/import', (req, res) => {
  const files = fs
    .readdirSync(PRODUCT_IMG_DIR)
    .filter((f) => /\.(jpe?g|png|webp|gif)$/i.test(f));
  let added = 0;
  for (const f of files) {
    const exists = db.prepare('SELECT 1 FROM products WHERE image = ?').get(f);
    if (!exists) {
      const name = f.replace(/\.[^.]+$/, '').replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
      db.prepare('INSERT INTO products (name, slug, description, price, stock, sku, image, status) VALUES (?, ?, ?, NULL, 0, ?, ?, ?)').run(
        name.slice(0, 90) || 'New product',
        uniqueSlug(name || 'new-product'),
        'Uploaded image — finalise title, description and price in the editor.',
        '',
        f,
        'draft'
      );
      added++;
    }
  }
  res.redirect('/admin/products?imported=' + added);
});

module.exports = router;
