<?php
// routes/contact-calls.php — call log for contact calls (browser → Twilio)
require_once 'controllers/ContactCallsController.php';
require_once 'helpers/auth_helper.php';
require_once 'helpers/audit_trail.php';
require_once 'helpers/response_helper.php';

$contactCallsController = new ContactCallsController();

// START — logged when a call is placed
if ($method === 'POST' && $uri === '/contact-call-start') {
    $decoded = authenticate();
    $user_id   = $decoded->user_id ?? null;
    $user_role = $decoded->user_type ?? null;

    $data = json_decode(file_get_contents('php://input'), true) ?? [];
    $response = $contactCallsController->start($data, $user_id);
    logAndRespond($user_id, $user_role, '/contact-call-start', $response, 'POST', $data);
}

// END — logged when the call ends / on Save & close (persists note + duration)
if ($method === 'POST' && $uri === '/contact-call-end') {
    $decoded = authenticate();
    $user_id   = $decoded->user_id ?? null;
    $user_role = $decoded->user_type ?? null;

    $data = json_decode(file_get_contents('php://input'), true) ?? [];
    $response = $contactCallsController->end($data);
    logAndRespond($user_id, $user_role, '/contact-call-end', $response, 'POST', $data);
}

// HISTORY — recent calls, optionally ?contact_id=
if ($method === 'GET' && $uri === '/contact-call-history') {
    $decoded = authenticate();
    $user_id   = $decoded->user_id ?? null;
    $user_role = $decoded->user_type ?? null;

    $response = $contactCallsController->history($_GET);
    logAndRespond($user_id, $user_role, '/contact-call-history', $response, 'GET', $_GET);
}
