<?php
require_once __DIR__ . '/../../config/webrtc_config.php';
webrtc_require_login();

$db = webrtc_db();
ensureAddressAndCallQueueTables($db);
ensureWebRtcCallWorkflow($db);

$room = trim((string)($_POST['room_token'] ?? ''));
$duration = max(0, (int)($_POST['duration_seconds'] ?? 0));
$result = in_array(($_POST['result'] ?? 'ended'), ['connected','missed','cancelled','failed','ended'], true) ? $_POST['result'] : 'ended';

if ($room === '') {
    webrtc_json(['ok' => false, 'error' => 'Missing room token'], 400);
}

$stmt = $db->prepare('SELECT * FROM call_requests WHERE room_token = :room LIMIT 1');
$stmt->execute([':room' => $room]);
$call = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$call) {
    webrtc_json(['ok' => false, 'error' => 'Call not found'], 404);
}

if (webrtc_is_customer() && (int)$call['customer_id'] !== (int)($_SESSION['customer_id'] ?? 0)) {
    webrtc_json(['ok' => false, 'error' => 'Access denied'], 403);
}

if (webrtc_is_csr() && isset($_SESSION['csr_id']) && function_exists('canCsrAccessCallRequest')) {
    if (!canCsrAccessCallRequest($db, (int)$_SESSION['csr_id'], (int)$call['id'])) {
        webrtc_json(['ok' => false, 'error' => 'Access denied'], 403);
    }
}

$finalStatus = in_array($result, ['missed', 'cancelled'], true) ? $result : 'completed';
$csrId = (int)($call['accepted_by'] ?: ($_SESSION['csr_id'] ?? 0));

$update = $db->prepare("UPDATE call_requests
    SET status = :status,
        browser_call_status = 'ended',
        call_ended_at = COALESCE(call_ended_at, NOW()),
        completed_at = COALESCE(completed_at, NOW()),
        call_duration_seconds = CASE
            WHEN :dur1 > 0 THEN :dur2
            WHEN call_started_at IS NOT NULL THEN TIMESTAMPDIFF(SECOND, call_started_at, NOW())
            ELSE COALESCE(call_duration_seconds, 0)
        END
    WHERE id = :id");
$update->execute([
    ':status' => $finalStatus,
    ':dur1' => $duration,
    ':dur2' => $duration,
    ':id' => (int)$call['id'],
]);

try {
    $exists = $db->prepare('SELECT id FROM call_logs WHERE call_request_id = :call_id AND result IN ("connected","ended","missed","cancelled","failed") ORDER BY id DESC LIMIT 1');
    $exists->execute([':call_id' => (int)$call['id']]);
    $logId = (int)$exists->fetchColumn();

    $logResult = $result === 'connected' ? 'connected' : $result;

    if ($logId > 0) {
        $log = $db->prepare("UPDATE call_logs
            SET request_id = :request_id,
                customer_id = :customer_id,
                customer_email = :email,
                csr_id = :csr_id,
                result = :result,
                duration_seconds = :dur
            WHERE id = :id");
        $log->execute([
            ':request_id' => $call['request_id'] ?: null,
            ':customer_id' => $call['customer_id'] ?: null,
            ':email' => $call['customer_email'] ?: null,
            ':csr_id' => $csrId ?: null,
            ':result' => $logResult,
            ':dur' => $duration,
            ':id' => $logId,
        ]);
    } else {
        $log = $db->prepare("INSERT INTO call_logs (call_request_id, request_id, customer_id, customer_email, csr_id, result, duration_seconds, created_at)
            VALUES (:call_id, :request_id, :customer_id, :email, :csr_id, :result, :dur, NOW())");
        $log->execute([
            ':call_id' => (int)$call['id'],
            ':request_id' => $call['request_id'] ?: null,
            ':customer_id' => $call['customer_id'] ?: null,
            ':email' => $call['customer_email'] ?: null,
            ':csr_id' => $csrId ?: null,
            ':result' => $logResult,
            ':dur' => $duration,
        ]);
    }
} catch (Throwable $e) {
    // The call_requests row is the main call history source; do not block ending the call if call_logs fails.
}

webrtc_json(['ok' => true]);
