<?php
declare(strict_types=1);

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

$companyId = (int) post('company_id', 0);
$url = trim((string) post('url', ''));

if ($url === '' || !filter_var($url, FILTER_VALIDATE_URL) || !preg_match('#^https?://#i', $url)) {
    Flash::add('error', t('link_url') . ': must be a valid http(s) address.');
    redirect('companies', 'view', ['id' => $companyId]);
}

$types = ['website', 'blog', 'linkedin', 'product', 'news', 'video', 'patent', 'document', 'other'];
$type = in_array(post('link_type'), $types, true) ? (string) post('link_type') : 'other';

$exists = Database::scalar(
    'SELECT 1 FROM links WHERE company_id = :c AND url = :u LIMIT 1',
    ['c' => $companyId, 'u' => $url]
);

if ($exists === null) {
    Database::run(
        'INSERT INTO links (company_id, link_type, url, label, added_by)
         VALUES (:c, :t, :u, :l, :by)',
        [
            'c'  => $companyId,
            't'  => $type,
            'u'  => $url,
            'l'  => trim((string) post('label', '')) ?: null,
            'by' => Auth::id(),
        ]
    );
    Audit::log('create', 'link', Database::lastId(), ['company_id' => $companyId, 'url' => $url]);
} else {
    Flash::add('warn', 'That link is already recorded.');
}

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