<?php
declare(strict_types=1);

/**
 * Acting on a detected change. "Log as check" is the important one: it closes
 * the loop, so a page the crawler flagged and an analyst actually read counts
 * as that company having been checked, and the watch schedule moves on.
 */

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

$id     = (int) post('id', 0);
$action = (string) post('action', '');
$return = in_array(post('return'), ['new', 'reviewed', 'ignored'], true)
    ? (string) post('return') : 'new';

$change = Database::one(
    'SELECT ch.*, l.url FROM link_changes ch JOIN links l ON l.id = ch.link_id WHERE ch.id = :id',
    ['id' => $id]
);

if ($change === null) {
    Flash::add('warn', t('signal_gone'));
    redirect('signals', 'index', ['status' => $return]);
}

$companyId = (int) $change['company_id'];
$findings  = trim((string) post('findings', ''));

if ($action === 'ignored') {
    Database::run(
        "UPDATE link_changes SET status = 'ignored', reviewed_by = :u, reviewed_at = NOW()
          WHERE id = :id",
        ['u' => Auth::id(), 'id' => $id]
    );
    Audit::log('update', 'link_change', $id, ['status' => 'ignored']);
    Flash::add('ok', t('signal_ignored_done'));
    redirect('signals', 'index', ['status' => $return]);
}

if ($action === 'log') {
    // Default text, so a check is never logged with nothing in it.
    if ($findings === '') {
        $findings = t('signal_default_finding', [
            'added'   => (int) $change['words_added'],
            'removed' => (int) $change['words_removed'],
            'url'     => $change['url'],
        ]);
    }

    Database::transaction(static function () use ($companyId, $findings, $change, $id) {
        Database::run(
            'INSERT INTO visits (company_id, user_id, visit_date, found_change, significance, findings)
             VALUES (:c, :u, CURDATE(), 1, :s, :f)',
            [
                'c' => $companyId,
                'u' => Auth::id(),
                // A large move on the page is worth flagging as major.
                's' => ((float) $change['change_ratio'] >= 0.08) ? 'major' : 'minor',
                'f' => $findings,
            ]
        );

        Database::run(
            'INSERT INTO watches (company_id, last_visit_date) VALUES (:c, CURDATE())
             ON DUPLICATE KEY UPDATE last_visit_date = CURDATE()',
            ['c' => $companyId]
        );

        Database::run(
            "UPDATE link_changes SET status = 'reviewed', reviewed_by = :u, reviewed_at = NOW()
              WHERE id = :id",
            ['u' => Auth::id(), 'id' => $id]
        );
    });

    Audit::log('create', 'visit', $companyId, ['from_signal' => $id]);
    Flash::add('ok', t('visit_saved'));
    redirect('signals', 'index', ['status' => $return]);
}

/**
 * Plain "reviewed": record that someone looked at the alert, and keep their
 * comment as a note - but do not claim the company itself was checked.
 */
Database::transaction(static function () use ($id, $companyId, $findings) {
    Database::run(
        "UPDATE link_changes SET status = 'reviewed', reviewed_by = :u, reviewed_at = NOW()
          WHERE id = :id",
        ['u' => Auth::id(), 'id' => $id]
    );

    if ($findings !== '') {
        Database::run(
            'INSERT INTO notes (company_id, user_id, note_date, body) VALUES (:c, :u, CURDATE(), :b)',
            ['c' => $companyId, 'u' => Auth::id(), 'b' => $findings]
        );
    }
});

Audit::log('update', 'link_change', $id, ['status' => 'reviewed']);
Flash::add('ok', t('signal_reviewed_done'));
redirect('signals', 'index', ['status' => $return]);
