const express = require('express');
const router = express.Router();
const { getDB } = require('../config/database');
const { notifySubscribers } = require('../config/smtp');
const { auth } = require('../middleware/auth');
const { ok, err } = require('../helpers/response');

router.get('/', async (req, res, next) => {
  try {
    const db = getDB();
    const [data] = await db.query('SELECT id, nama, lokasi, tanggal, waktu, `desc_text` as `desc`, status, created_at FROM program ORDER BY tanggal ASC');
    ok(res, { data, total: data.length });
  } catch (e) { next(e); }
});

router.post('/', auth(['Admin', 'Editor']), async (req, res, next) => {
  try {
    const db = getDB();
    const { nama, lokasi, tanggal, waktu, desc, status } = req.body;
    if (!nama) return err(res, 'Nama program wajib diisi');
    const [result] = await db.query('INSERT INTO program (nama, lokasi, tanggal, waktu, `desc_text`, status) VALUES (?,?,?,?,?,?)', [nama, lokasi || '', tanggal || null, waktu || '', desc || '', status || 'Upcoming']);
    const [item] = await db.query('SELECT id, nama, lokasi, tanggal, waktu, `desc_text` as `desc`, status, created_at FROM program WHERE id = ?', [result.insertId]);
    const programDate = tanggal ? new Date(tanggal).toLocaleDateString('id-ID', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }) : '-';
    notifySubscribers(db, 'program', nama, `📅 ${programDate} ${waktu || ''}<br>📍 ${lokasi || '-'}${desc ? '<br>' + desc : ''}`);
    ok(res, item[0]);
  } catch (e) { next(e); }
});

router.put('/:id', auth(['Admin', 'Editor']), async (req, res, next) => {
  try {
    const db = getDB();
    const [eRows] = await db.query('SELECT * FROM program WHERE id = ?', [req.params.id]);
    if (eRows.length === 0) return err(res, 'Program tidak ditemukan', 404);
    const existing = eRows[0];
    const { nama, lokasi, tanggal, waktu, desc, status } = req.body;
    await db.query(
      'UPDATE program SET nama=?,lokasi=?,tanggal=?,waktu=?,`desc_text`=?,status=? WHERE id=?',
      [nama || existing.nama, lokasi || existing.lokasi, tanggal || existing.tanggal, waktu || existing.waktu, desc || existing.desc_text, status || existing.status, req.params.id]
    );
    const [item] = await db.query('SELECT id, nama, lokasi, tanggal, waktu, `desc_text` as `desc`, status, created_at FROM program WHERE id = ?', [req.params.id]);
    ok(res, item[0]);
  } catch (e) { next(e); }
});

router.delete('/:id', auth(['Admin']), async (req, res, next) => {
  try {
    const db = getDB();
    await db.query('DELETE FROM program WHERE id = ?', [req.params.id]);
    ok(res, null, 'Program dihapus');
  } catch (e) { next(e); }
});

router.post('/bulk-delete', auth(['Admin']), async (req, res, next) => {
  try {
    const db = getDB();
    const { ids } = req.body;
    if (!Array.isArray(ids) || ids.length === 0) return err(res, 'Tidak ada ID yang dipilih');
    await db.query('DELETE FROM program WHERE id IN (?)', [ids]);
    ok(res, null, `${ids.length} program berhasil dihapus`);
  } catch (e) { next(e); }
});

module.exports = router;
