<?php
session_start();
require_once '../../config/database.php';
require_once '../../includes/app_helpers.php';
header('Content-Type: application/json');

if (!isset($_SESSION['customer_id'])) {
    echo json_encode(['success'=>false,'message'=>'Please login first.']);
    exit;
}

try {
    $db = (new Database())->getConnection();
    ensureAddressAndCallQueueTables($db);
    ensureUnifiedTicketWorkflow($db);
    ensureWebRtcCallWorkflow($db);
    ensureCsrTeamTables($db);

    $customerId = (int)$_SESSION['customer_id'];
    $requestId = isset($_POST['request_id']) ? (int)$_POST['request_id'] : 0;

    if ($requestId <= 0) {
        echo json_encode(['success'=>false,'message'=>'Invalid request.']);
        exit;
    }

    $stmt = $db->prepare("SELECT sr.id, sr.request_number, sr.full_name, sr.phone_number, sr.customer_id, COALESCE(sr.customer_email, c.email) AS customer_email
                          FROM service_requests sr
                          LEFT JOIN customers c ON c.id = sr.customer_id
                          WHERE sr.id = :request_id AND sr.customer_id = :customer_id
                          LIMIT 1");
    $stmt->execute([':request_id'=>$requestId, ':customer_id'=>$customerId]);
    $request = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$request) {
        echo json_encode(['success'=>false,'message'=>'Request not found.']);
        exit;
    }

    $dup = $db->prepare("SELECT id, status, room_token FROM call_requests WHERE request_id = :request_id AND customer_id = :customer_id AND status IN ('manager_queue','assigned','accepted') ORDER BY id DESC LIMIT 1");
    $dup->execute([':request_id'=>$requestId, ':customer_id'=>$customerId]);
    $existing = $dup->fetch(PDO::FETCH_ASSOC);
    if ($existing) {
        echo json_encode(['success'=>true,'message'=>'Your web call request is already in the CSR queue.','call_id'=>(int)$existing['id'],'room_url'=>!empty($existing['room_token']) ? '../call_room.php?room='.urlencode($existing['room_token']) : null]);
        exit;
    }

    $roomToken = bin2hex(random_bytes(32));
    $route = routeCallRequestToTeam($db);
    $ins = $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)
                         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')");
    $ins->execute([
        ':request_id'=>$requestId,
        ':customer_id'=>$customerId,
        ':customer_name'=>$request['full_name'] ?: 'Customer',
        ':customer_email'=>$request['customer_email'] ?? '',
        ':phone_number'=>$request['phone_number'] ?: '',
        ':notes'=>'Customer requested a web call for request #'.$request['request_number'],
        ':call_reason'=>'Customer requested a web call for request #'.$request['request_number'],
        ':room_token'=>$roomToken,
        ':team_id'=>$route['team_id'],
        ':manager_id'=>$route['manager_id']
    ]);
    $callId = (int)$db->lastInsertId();

    $db->prepare("UPDATE service_requests SET call_request_id = :call_id, last_updated_at = NOW() WHERE id = :request_id")->execute([':call_id'=>$callId, ':request_id'=>$requestId]);

    echo json_encode(['success'=>true,'message'=>'Your web call request has been sent. Please join the call room and wait for CSR.','call_id'=>$callId,'team'=>$route['team_name'],'room_url'=>'../call_room.php?room='.urlencode($roomToken)]);
} catch (Exception $e) {
    echo json_encode(['success'=>false,'message'=>'Call request failed: '.$e->getMessage()]);
}
