
<?php
require_once __DIR__ . '/../../config/webrtc_config.php';
webrtc_require_login();
$db = webrtc_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']) webrtc_json(['ok'=>false,'error'=>'Access denied'],403);
$csrId = (int)($call['accepted_by'] ?: ($_SESSION['csr_id'] ?? 0));
$db->prepare("UPDATE call_requests SET status=CASE WHEN :result1 IN ('missed','cancelled') THEN :result2 ELSE 'completed' END, browser_call_status='ended', call_ended_at=NOW(), completed_at=NOW(), call_duration_seconds=:dur WHERE id=:id")
   ->execute([':result1'=>$result, ':result2'=>$result, ':dur'=>$duration, ':id'=>(int)$call['id']]);
$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())")
   ->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'=>$result, ':dur'=>$duration]);
webrtc_json(['ok'=>true]);
