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

router.get('/', async (req, res, next) => {
  try {
    const db = getDB();
    const { page = 1, limit = 10, status = '' } = req.query;
    let where = 'WHERE 1=1'; const params = [];
    if (status) { where += ' AND status = ?'; params.push(status); }
    const result = await paginate(`SELECT * FROM donasi ${where} ORDER BY created_at DESC`, params, +page, +limit);
    const [sR] = await db.query("SELECT COALESCE(SUM(nominal),0) as s FROM donasi WHERE status='Terkonfirmasi'");
    const [cR] = await db.query('SELECT COUNT(*) as c FROM donasi');
    const [cfR] = await db.query("SELECT COUNT(*) as c FROM donasi WHERE status='Terkonfirmasi'");
    const [pdR] = await db.query("SELECT COUNT(*) as c FROM donasi WHERE status='Pending'");
    const stats = { total: sR[0].s, count: cR[0].c, confirmed: cfR[0].c, pending: pdR[0].c };
    ok(res, { ...result, stats });
  } catch (e) { next(e); }
});

router.post('/', async (req, res, next) => {
  try {
    const db = getDB();
    const { nama, email, nominal, metode, pesan } = req.body;
    if (!nominal || nominal <= 0) return err(res, 'Nominal tidak valid');
    const [result] = await db.query('INSERT INTO donasi (nama, email, nominal, metode, pesan) VALUES (?,?,?,?,?)', [nama || 'Anonim', email || '', +nominal, metode || 'Transfer Bank', pesan || '']);
    ok(res, { id: result.insertId }, 'Donasi berhasil dicatat');
  } catch (e) { next(e); }
});

router.patch('/:id/status', auth(['Admin']), async (req, res, next) => {
  try {
    const db = getDB();
    const { status } = req.body;
    if (!['Pending', 'Terkonfirmasi', 'Ditolak'].includes(status)) return err(res, 'Status donasi tidak valid');
    await db.query('UPDATE donasi SET status = ? WHERE id = ?', [status, req.params.id]);
    ok(res, null, 'Status donasi diperbarui');
  } catch (e) { next(e); }
});

module.exports = router;
