
<?php
require_once __DIR__ . '/../config/webrtc_config.php';
webrtc_require_login();
if (!webrtc_is_customer()) { http_response_code(403); exit('Customer access only.'); }

$db = webrtc_db();
ensureWebRtcCallWorkflow($db);
$customerId = (int)$_SESSION['customer_id'];
$requestId = (int)($_GET['request_id'] ?? $_POST['request_id'] ?? 0);
$reason = trim((string)($_POST['reason'] ?? $_GET['reason'] ?? 'Customer requested a web call'));

$customerStmt = $db->prepare('SELECT first_name, last_name, email, phone_number FROM customers WHERE id = :id LIMIT 1');
$customerStmt->execute([':id'=>$customerId]);
$customer = $customerStmt->fetch(PDO::FETCH_ASSOC);
if (!$customer) { http_response_code(404); exit('Customer not found.'); }

if ($requestId > 0 && !webrtc_customer_can_access_request($db, $requestId, $customerId)) {
    http_response_code(403); exit('You do not have access to this ticket.');
}

$roomToken = webrtc_room_token();
$route = routeCallRequestToTeam($db);
$name = trim(($customer['first_name'] ?? '') . ' ' . ($customer['last_name'] ?? '')) ?: 'Customer';
$phone = $customer['phone_number'] ?? '';
$email = $customer['email'] ?? '';

$stmt = $db->prepare("INSERT INTO call_requests (
    request_id, customer_id, customer_name, customer_email, phone_number, notes, call_reason, team_id, manager_id,
    status, provider, call_mode, room_token, browser_call_status, queued_at
) VALUES (
    :request_id, :customer_id, :customer_name, :customer_email, :phone_number, :notes, :call_reason, :team_id, :manager_id,
    'manager_queue', 'webrtc', 'webrtc', :room_token, 'ringing', NOW()
)");
$stmt->execute([
    ':request_id' => $requestId ?: null,
    ':customer_id' => $customerId,
    ':customer_name' => $name,
    ':customer_email' => $email,
    ':phone_number' => $phone,
    ':notes' => $reason,
    ':call_reason' => $reason,
    ':room_token' => $roomToken,
    ':team_id' => $route['team_id'],
    ':manager_id' => $route['manager_id'],
]);

header('Location: ../call_room.php?room=' . urlencode($roomToken));
exit;
