<?php
// ========================================
// ROUTES - call_logs_routes.php
// ========================================

require_once 'controllers/CallLogsController.php';
require_once 'helpers/auth_helper.php';
require_once 'helpers/audit_trail.php';
require_once 'helpers/response_helper.php';

$callLogsController = new CallLogsController();

// Create call log
if ($method === 'POST' && $uri === '/call-logs') {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_type = $decoded->user_type ?? null;
    $data = json_decode(file_get_contents('php://input'), true);
    $response = $callLogsController->createCallLog($data);
    logAndRespond($user_id, $user_type, '/call-logs', $response, 'POST', $data);
}

// Get call logs by invoice
if ($method === 'GET' && preg_match('/^\/call-logs\/invoice\/([a-f0-9\-]+)$/', $uri, $matches)) {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_type = $decoded->user_type ?? null;
    $invoiceId = $matches[1];
    $response = $callLogsController->getCallLogsByInvoice($invoiceId);
    logAndRespond($user_id, $user_type, '/call-logs/invoice/' . $invoiceId, $response, 'GET', []);
}

// Get call logs by caller (IPO)
if ($method === 'GET' && preg_match('/^\/call-logs\/caller\/([a-f0-9\-]+)$/', $uri, $matches)) {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_type = $decoded->user_type ?? null;
    $callerId = $matches[1];
    $limit = $_GET['limit'] ?? 50;
    $response = $callLogsController->getCallLogsByCaller($callerId, $limit);
    logAndRespond($user_id, $user_type, '/call-logs/caller/' . $callerId, $response, 'GET', []);
}

// Update call log
if ($method === 'PUT' && $uri === '/call-logs') {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_type = $decoded->user_type ?? null;
    $data = json_decode(file_get_contents('php://input'), true);
    $response = $callLogsController->updateCallLog($data);
    logAndRespond($user_id, $user_type, '/call-logs', $response, 'PUT', $data);
}

// Get call statistics
if ($method === 'GET' && $uri === '/call-logs/statistics') {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_type = $decoded->user_type ?? null;
    $days = $_GET['days'] ?? 30;
    $response = $callLogsController->getCallStatistics($days);
    logAndRespond($user_id, $user_type, '/call-logs/statistics', $response, 'GET', ['days' => $days]);
}

// Get daily call activity
if ($method === 'GET' && $uri === '/call-logs/daily-activity') {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_type = $decoded->user_type ?? null;
    $days = $_GET['days'] ?? 30;
    $response = $callLogsController->getDailyCallActivity($days);
    logAndRespond($user_id, $user_type, '/call-logs/daily-activity', $response, 'GET', ['days' => $days]);
}