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

if (!webrtc_is_csr()) {
    webrtc_json(['ok' => false, 'error' => 'CSR access only'], 403);
}

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

$csrId = (int)($_SESSION['csr_id'] ?? 0);
$room = trim((string)($_POST['room_token'] ?? ''));
$notes = trim((string)($_POST['notes'] ?? ''));

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 ($csrId > 0 && function_exists('canCsrAccessCallRequest') && !canCsrAccessCallRequest($db, $csrId, (int)$call['id'])) {
    webrtc_json(['ok' => false, 'error' => 'Access denied'], 403);
}

// Main source for notes shown in Calls pages.
$update = $db->prepare('UPDATE call_requests SET notes = :notes, updated_at = NOW() WHERE id = :id');
$update->execute([
    ':notes' => $notes,
    ':id' => (int)$call['id'],
]);

// Keep a call_logs note copy too, but do not create duplicates every time notes are saved.
try {
    $existing = $db->prepare('SELECT id FROM call_logs WHERE call_request_id = :call_id AND csr_id = :csr_id ORDER BY id DESC LIMIT 1');
    $existing->execute([
        ':call_id' => (int)$call['id'],
        ':csr_id' => $csrId ?: null,
    ]);
    $logId = (int)$existing->fetchColumn();

    if ($logId > 0) {
        $log = $db->prepare('UPDATE call_logs SET notes = :notes WHERE id = :id');
        $log->execute([
            ':notes' => $notes,
            ':id' => $logId,
        ]);
    } else {
        $log = $db->prepare("INSERT INTO call_logs (call_request_id, request_id, customer_id, customer_email, call_direction, csr_id, result, notes, created_at)
            VALUES (:call_id, :request_id, :customer_id, :email, :direction, :csr_id, 'ended', :notes, 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,
            ':direction' => $call['call_direction'] ?? 'inbound',
            ':csr_id' => $csrId ?: null,
            ':notes' => $notes,
        ]);
    }
} catch (Throwable $e) {
    // Notes are already saved in call_requests; do not fail the request if call_logs is older.
}

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