// routes/users.js
const express = require("express");
const router = express.Router();
const path = require("path");
const fs = require("fs");

router.post("/trigger", global.apiAuth, (req, res) => {

	console.log('Triggering call with data:', req.body, {username: req.session ? req.session.user.fullname || 'Unknown' : 'Unknown'});
	global.exec(`/usr/sbin/asterisk -x "confbridge kick rsc_page all"`, (error, stdout, stderr) => {
		if (error) {
			console.error(`Error stopping page: ${error}`);
			return res.status(500).send('Error stopping page');
		}
		console.log(`Page stopped: ${stdout}`);
		setTimeout(() => {
			global.trigCall(req.body.pageType, req.body.phone, {username: req.session ? req.session.user.fullname || 'Unknown' : 'Unknown'});
		}, 1000);
		if (stderr) {
			console.error(`stderr: ${stderr}`);
		}
	});
	res.status(200).send('Call triggered');
});

router.post("/stop", global.apiAuth, (req, res) => {
	console.log('Stopping all calls');
	global.exec(`/usr/sbin/asterisk -x "confbridge kick rsc_page all"`, (error, stdout, stderr) => {
		if (error) {
			console.error(`Error stopping page: ${error}`);
			return res.status(500).send('Error stopping page');
		}
		console.log(`Page stopped: ${stdout}`);
	});

	res.status(200).send('Stop request received');
});
module.exports = router;
