const axios = require('axios');
const config = require('../config/config.js')

app.post('/register', async (req, res) => {
  const { first_name, surname, business_name, cac_registered, slot_option, email } = req.body;

  // Validate input
  if (!SLOT_PRICES[slot_option]) {
    return res.status(400).json({ error: 'Invalid slot option' });
  }

  const amount = SLOT_PRICES[slot_option] * 100; // Paystack uses kobo

  try {
    const response = await axios.post('https://api.paystack.co/transaction/initialize',
      {
        email,
        amount,
        metadata: {
          first_name,
          surname,
          business_name,
          cac_registered,
          slot_option
        }
      },
      {
        headers: {
          Authorization: `Bearer ${process.env.PAYSTACK_SECRET_KEY}`,
          'Content-Type': 'application/json'
        }
      }
    );

    res.json({
      authorization_url: response.data.data.authorization_url,
      reference: response.data.data.reference
    });
  } catch (error) {
    res.status(500).json({ error: 'Payment initialization failed' });
  }
});

app.post('/paystack/webhook', express.json({ verify: (req, res, buf) => {
    req.rawBody = buf.toString();
  } }), async (req, res) => {
    const hash = crypto.createHmac('sha512', process.env.PAYSTACK_SECRET_KEY)
                       .update(req.rawBody)
                       .digest('hex');
  
    if (hash !== req.headers['x-paystack-signature']) {
      return res.status(400).send('Invalid signature');
    }
  
    const event = req.body;
  
    if (event.event === 'charge.success') {
      const metadata = event.data.metadata;
  
      // Save registration to DB
      const query = `
        INSERT INTO registrations (first_name, surname, business_name, cac_registered, slot_option)
        VALUES (?, ?, ?, ?, ?)
      `;
      const values = [
        metadata.first_name,
        metadata.surname,
        metadata.business_name,
        metadata.cac_registered,
        metadata.slot_option
      ];
  
      // Use your db connection
      db.query(query, values, (err, result) => {
        if (err) console.error('DB error:', err);
      });
    }
  
    res.sendStatus(200);
  });
  