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

if (!isset($_SESSION['csr_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

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

    $csrId = (int)$_SESSION['csr_id'];
    $callId = (int)($_POST['call_id'] ?? 0);
    $status = $_POST['status'] ?? '';

    if (!in_array($status, ['missed', 'completed', 'cancelled'], true)) {
        echo json_encode(['success' => false, 'message' => 'Invalid status.']);
        exit;
    }

    if ($callId <= 0 || !canCsrAccessCallRequest($db, $csrId, $callId)) {
        echo json_encode(['success' => false, 'message' => 'Access denied.']);
        exit;
    }

    $stmt = $db->prepare("UPDATE call_requests
                          SET status = :status,
                              call_ended_at = NOW(),
                              completed_at = NOW(),
                              call_duration_seconds = CASE
                                  WHEN call_started_at IS NOT NULL THEN TIMESTAMPDIFF(SECOND, call_started_at, NOW())
                                  ELSE call_duration_seconds
                              END
                          WHERE id = :id");
    $stmt->execute([
        ':status' => $status,
        ':id' => $callId
    ]);

    echo json_encode(['success' => true, 'message' => 'Call request updated.']);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
