<?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. File path
$filename = "/var/www/html/Manual/Recordings/rec_".$agent."_".time().".wav";

// 3. AMI Redirect
$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");

// Set variable first
fputs($sock, "Action: Setvar\r\n");
fputs($sock, "Channel: $channel\r\n");
fputs($sock, "Variable: FILENAME\r\n");
fputs($sock, "Value: $filename\r\n\r\n");

usleep(200000);

// Then redirect
fputs($sock, "Action: Redirect\r\n");
fputs($sock, "Channel: $channel\r\n");
fputs($sock, "Context: record-control\r\n");
fputs($sock, "Exten: start\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,
    "file"=>$filename
]);

?>
