<?php

$agent = $_GET['agent'] ;

// 1. Get active channel
$output = shell_exec("/usr/sbin/asterisk -rx 'core show channels concise'");
$lines = explode("\n", $output);

$channel = "";

foreach ($lines as $line) {
    $line = trim($line);
    if ($line == "") continue;

    if (preg_match("/^SIP\/$agent-/", $line)) {
        $parts = explode("!", $line);
        $channel = $parts[0];
        break;
    }
}

if (!$channel) {
    die(json_encode(["status"=>"error","msg"=>"No active call"]));
}

// 2. AMI Redirect (STOP)
$sock = fsockopen("127.0.0.1", 5038);

fputs($sock, "Action: Login\r\n");
fputs($sock, "Username: cron\r\n");
fputs($sock, "Secret: 1234\r\n\r\n");

usleep(200000);

fputs($sock, "Action: Redirect\r\n");
fputs($sock, "Channel: $channel\r\n");
fputs($sock, "Context: record-control\r\n");
fputs($sock, "Exten: stop\r\n");
fputs($sock, "Priority: 1\r\n\r\n");

usleep(200000);

fputs($sock, "Action: Logoff\r\n\r\n");

fclose($sock);

echo json_encode([
    "status"=>"success",
    "channel"=>$channel
]);

?>
