<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_admin.php';

apply_cors();
require_admin();
$pdo = getDbConnection();

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    send_error('Method not allowed.', 405);
}

// ---- Summary breakdown by call_type / status / channel ----
$byType = $pdo->query(
    'SELECT call_type, COUNT(*) AS total FROM call_logs GROUP BY call_type'
)->fetchAll();

$byStatus = $pdo->query(
    'SELECT status, COUNT(*) AS total FROM call_logs GROUP BY status'
)->fetchAll();

$byChannel = $pdo->query(
    'SELECT channel_used, COUNT(*) AS total FROM call_logs GROUP BY channel_used'
)->fetchAll();

// ---- Filterable log list ----
[$page, $perPage, $offset] = paginate_params();
$search = clean_str($_GET['search'] ?? '');
$status = clean_str($_GET['status'] ?? '');
$userEmail = clean_str($_GET['user_email'] ?? '');

$where = ['1=1'];
$params = [];
if ($search !== '') {
    $where[] = '(phone_number LIKE :search OR caller_name LIKE :search2)';
    $params[':search'] = "%$search%";
    $params[':search2'] = "%$search%";
}
if ($status !== '') { $where[] = 'status = :status'; $params[':status'] = $status; }
if ($userEmail !== '') { $where[] = 'user_email = :user_email'; $params[':user_email'] = $userEmail; }
$whereSql = implode(' AND ', $where);

$count = $pdo->prepare("SELECT COUNT(*) FROM call_logs WHERE $whereSql");
$count->execute($params);
$total = (int) $count->fetchColumn();

$stmt = $pdo->prepare(
    "SELECT * FROM call_logs WHERE $whereSql ORDER BY created_at DESC LIMIT :limit OFFSET :offset"
);
foreach ($params as $k => $v) $stmt->bindValue($k, $v);
$stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();

send_success([
    'summary' => [
        'by_type'    => $byType,
        'by_status'  => $byStatus,
        'by_channel' => $byChannel,
    ],
    'logs' => $stmt->fetchAll(),
    'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
]);
