<?php
declare(strict_types=1);

$user = Auth::requireRole('analyst');
Csrf::check();

$id = post('id') !== null && post('id') !== '' ? (int) post('id') : null;

/**
 * The watch panel on the profile page posts here too, with only_watch=1.
 * In that case leave the company fields alone and update the schedule only.
 */
$onlyWatch = post('only_watch') === '1';

$assignedUser  = post('assigned_user_id') !== '' ? (int) post('assigned_user_id') : null;
$frequencyDays = post('frequency_days') !== '' && post('frequency_days') !== null
    ? max(1, min(3650, (int) post('frequency_days')))
    : null;
$lastVisit     = post('last_visit_date') ?: null;
$isPaused      = post('is_paused') === '1' ? 1 : 0;

if ($lastVisit !== null) {
    $d = DateTimeImmutable::createFromFormat('Y-m-d', (string) $lastVisit);
    if ($d === false || $d->format('Y-m-d') !== $lastVisit) {
        Flash::add('error', 'That date is not valid.');
        redirect('companies', 'view', ['id' => $id]);
    }
}

if ($onlyWatch) {
    if ($id === null) {
        redirect('companies', 'list');
    }
    save_watch($id, $assignedUser, $frequencyDays, $lastVisit, $isPaused, false);
    Audit::log('update', 'watch', $id, ['frequency_days' => $frequencyDays, 'paused' => $isPaused]);
    Flash::add('ok', t('company_saved'));
    redirect('companies', 'view', ['id' => $id]);
}

// ---------------------------------------------------------------- validate
$name = trim((string) post('name', ''));
if ($name === '') {
    Flash::add('error', t('name') . ': ' . t('required'));
    redirect('companies', 'form', $id === null ? [] : ['id' => $id]);
}

$website = trim((string) post('website', ''));
if ($website !== '' && (!filter_var($website, FILTER_VALIDATE_URL) || !preg_match('#^https?://#i', $website))) {
    Flash::add('error', t('website') . ': must be a valid http(s) address.');
    redirect('companies', 'form', $id === null ? [] : ['id' => $id]);
}

$parentId = post('parent_company_id') !== '' ? (int) post('parent_company_id') : null;
if ($parentId !== null && $id !== null && $parentId === $id) {
    Flash::add('error', 'A company cannot be its own parent.');
    redirect('companies', 'form', ['id' => $id]);
}

$statuses = ['unknown', 'active', 'acquired', 'merged', 'inactive'];
$status   = in_array(post('status'), $statuses, true) ? (string) post('status') : 'unknown';

$threat = post('threat_level') !== '' ? (int) post('threat_level') : null;
if ($threat !== null && ($threat < 1 || $threat > 5)) {
    $threat = null;
}

$fields = [
    'name'              => $name,
    'aka'               => trim((string) post('aka', '')) ?: null,
    'country_code'      => post('country_code') ? strtoupper((string) post('country_code')) : null,
    'parent_company_id' => $parentId,
    'website'           => $website ?: null,
    'status'            => $status,
    'threat_level'      => $threat,
    'summary'           => trim((string) post('summary', '')) ?: null,
];

$tagIds = array_map('intval', (array) ($_POST['tags'] ?? []));
$rels   = array_values(array_intersect(
    (array) ($_POST['relationships'] ?? []),
    ['competitor', 'partner', 'customer', 'distributor', 'supplier', 'watchlist']
));

// ---------------------------------------------------------------- persist
$before = $id === null ? [] : (Database::one('SELECT * FROM companies WHERE id = :id', ['id' => $id]) ?? []);

$savedId = Database::transaction(function () use ($id, $fields, $tagIds, $rels, $user,
    $assignedUser, $frequencyDays, $lastVisit, $isPaused) {

    if ($id === null) {
        $slug = unique_slug(slugify($fields['name']), 'companies');
        Database::run(
            'INSERT INTO companies (name, slug, aka, country_code, parent_company_id, website,
                                    status, threat_level, summary, created_by)
             VALUES (:name, :slug, :aka, :country_code, :parent_company_id, :website,
                     :status, :threat_level, :summary, :created_by)',
            $fields + ['slug' => $slug, 'created_by' => $user['id']]
        );
        $companyId = Database::lastId();
    } else {
        $companyId = $id;
        $fields['slug'] = unique_slug(slugify($fields['name']), 'companies', $companyId);
        Database::run(
            'UPDATE companies SET name = :name, slug = :slug, aka = :aka, country_code = :country_code,
                    parent_company_id = :parent_company_id, website = :website, status = :status,
                    threat_level = :threat_level, summary = :summary
              WHERE id = :id',
            $fields + ['id' => $companyId]
        );
    }

    // Keywords - replace the whole set
    Database::run('DELETE FROM company_tags WHERE company_id = :id', ['id' => $companyId]);
    if ($tagIds) {
        $st = Database::pdo()->prepare(
            'INSERT IGNORE INTO company_tags (company_id, tag_id) VALUES (:c, :t)'
        );
        foreach ($tagIds as $tagId) {
            $st->execute(['c' => $companyId, 't' => $tagId]);
        }
    }

    // Relationships - replace, defaulting to competitor so nothing is left roleless
    Database::run('DELETE FROM company_relationships WHERE company_id = :id', ['id' => $companyId]);
    $st = Database::pdo()->prepare(
        'INSERT IGNORE INTO company_relationships (company_id, rel_type) VALUES (:c, :r)'
    );
    foreach ($rels ?: ['competitor'] as $rel) {
        $st->execute(['c' => $companyId, 'r' => $rel]);
    }

    // A website field should also exist as a checkable link
    if (!empty($fields['website'])) {
        $exists = Database::scalar(
            'SELECT 1 FROM links WHERE company_id = :c AND url = :u LIMIT 1',
            ['c' => $companyId, 'u' => $fields['website']]
        );
        if ($exists === null) {
            Database::run(
                'INSERT INTO links (company_id, link_type, url, is_primary) VALUES (:c, :t, :u, 1)',
                ['c' => $companyId, 't' => 'website', 'u' => $fields['website']]
            );
        }
    }

    save_watch($companyId, $assignedUser, $frequencyDays, $lastVisit, $isPaused, true);

    return $companyId;
});

$after = Database::one('SELECT * FROM companies WHERE id = :id', ['id' => $savedId]) ?? [];

Audit::log($id === null ? 'create' : 'update', 'company', $savedId,
    $id === null ? ['name' => $name] : Audit::diff($before, $after));

Flash::add('ok', t('company_saved'));
redirect('companies', 'view', ['id' => $savedId]);

