<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit(0); }

require("dbconnect_mysqli.php");
require("functions.php");

// Auth (8 params as before)
$PHP_AUTH_USER = $_SERVER['PHP_AUTH_USER'] ?? '';
$PHP_AUTH_PW   = $_SERVER['PHP_AUTH_PW'] ?? '';
$ip            = $_SERVER['REMOTE_ADDR'] ?? '';
$db            = 'asterisk'; // Change to your DB if not 'asterisk'

$auth_message = user_authorization($PHP_AUTH_USER, $PHP_AUTH_PW, 'REPORTS', 1, 0, $ip, $db, '1');
if ($auth_message !== 'GOOD') {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// Get filters from GET params
$query_date    = $_GET['query_date']    ?? date('Y-m-d');
$end_date      = $_GET['end_date']      ?? date('Y-m-d');
$campaigns     = $_GET['campaigns']     ?? [];
$user_groups   = $_GET['user_group']    ?? [];
$shift         = $_GET['shift']         ?? 'ALL';

// (Build WHERE clauses as in your AST_agent_time_detail.php)

$results = []; // each agent row

// Example: iterate through each agent and append data
// Replace with your own SQL logic for agent stats!

$sql = "SELECT user, full_name FROM vicidial_users WHERE user_level > 0 ORDER BY user";
$rslt = mysql_to_mysqli($sql, $link);
while ($row = mysqli_fetch_assoc($rslt)) {
    $results[] = [
        'user_name'          => $row['full_name'],
        'id'                 => $row['user'],
        'calls'              => rand(1, 100), // <--- replace with real calculation
        'time_clock'         => '1:00:00',    // <--- replace with real value
        'login_time'         => '2:00:00',
        'wait'               => '0:30:00',
        'wait_percent'       => '25.00%',
        'talk'               => '0:45:00',
        'talk_time_percent'  => '40.00%',
        'dispo'              => '0:10:00',
        'dispo_time_percent' => '10.00%',
        'pause'              => '0:20:00',
        'pause_time_percent' => '15.00%',
        'dead'               => '0:05:00',
        'dead_time_percent'  => '5.00%',
        'customer'           => '0:30:00',
        'connected'          => '1:00:00',
        'login'              => '1:00:00',
        'lunch'              => '0:10:00',
        'precall'            => '0:05:00',
        'visible'            => '0:10:00',
        'hidden'             => '0:20:00'
    ];
}

// You should also calculate totals here as a separate array/object
$totals = [
    'calls' => 340,
    // ... other total fields
];

// Output as JSON
header('Content-Type: application/json');
echo json_encode([
    'range'   => [$query_date, $end_date],
    'results' => $results,
    'totals'  => $totals
], JSON_PRETTY_PRINT);
exit;
?>
