<?php
declare(strict_types=1);

/** One-click "I looked, nothing new" from the review queue. */

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

$companyId = (int) post('company_id', 0);
$today = date('Y-m-d');

if (Database::scalar('SELECT 1 FROM companies WHERE id = :id', ['id' => $companyId]) === null) {
    Flash::add('warn', 'That company no longer exists.');
    redirect('visits', 'queue');
}

$already = Database::scalar(
    'SELECT 1 FROM visits WHERE company_id = :c AND visit_date = :d AND user_id = :u LIMIT 1',
    ['c' => $companyId, 'd' => $today, 'u' => Auth::id()]
);

if ($already === null) {
    Database::transaction(static function () use ($companyId, $today) {
        Database::run(
            "INSERT INTO visits (company_id, user_id, visit_date, found_change, significance, findings)
             VALUES (:c, :u, :d, 0, 'none', NULL)",
            ['c' => $companyId, 'u' => Auth::id(), 'd' => $today]
        );
        Database::run(
            'INSERT INTO watches (company_id, last_visit_date) VALUES (:c, :d)
             ON DUPLICATE KEY UPDATE last_visit_date = VALUES(last_visit_date)',
            ['c' => $companyId, 'd' => $today]
        );
    });
    Audit::log('create', 'visit', $companyId, ['date' => $today, 'quick' => true]);
}

Flash::add('ok', t('visit_saved'));

// Return to wherever the button was pressed, but only if that is our own app.
$back = (string) ($_SERVER['HTTP_REFERER'] ?? '');
$path = parse_url($back, PHP_URL_PATH);
$host = parse_url($back, PHP_URL_HOST);
if ($path !== null && ($host === null || $host === ($_SERVER['HTTP_HOST'] ?? ''))) {
    redirect_to($path . (parse_url($back, PHP_URL_QUERY) ? '?' . parse_url($back, PHP_URL_QUERY) : ''));
}
redirect('visits', 'queue');
