<?php
declare(strict_types=1);

Auth::requireRole('analyst');
Csrf::check();

$id = (int) post('id', 0);
$companyId = (int) post('company_id', 0);

$note = Database::one('SELECT id, company_id, user_id FROM notes WHERE id = :id', ['id' => $id]);

// Analysts remove their own notes; admins remove any.
if ($note !== null && ((int) $note['user_id'] === Auth::id() || Auth::isAdmin())) {
    Database::run('DELETE FROM notes WHERE id = :id', ['id' => $id]);
    Audit::log('delete', 'note', $id);
    $companyId = (int) $note['company_id'];
} else {
    Flash::add('error', t('not_permitted'));
}

redirect('companies', 'view', ['id' => $companyId]);
