<?php
declare(strict_types=1);

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

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

if ($name === '' || Database::scalar('SELECT 1 FROM companies WHERE id = :id', ['id' => $companyId]) === null) {
    Flash::add('error', t('product_name') . ': ' . t('required'));
    redirect('companies', 'view', ['id' => $companyId]);
}

$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]);
}

$statuses = ['unknown', 'concept', 'prototype', 'production', 'discontinued'];
$status = in_array(post('status'), $statuses, true) ? (string) post('status') : 'unknown';

$slug = unique_slug(slugify($name), 'products', null, $companyId);

Database::run(
    'INSERT INTO products (company_id, name, slug, status, url, description)
     VALUES (:c, :n, :s, :st, :u, :d)',
    [
        'c'  => $companyId,
        'n'  => $name,
        's'  => $slug,
        'st' => $status,
        'u'  => $url ?: null,
        'd'  => trim((string) post('description', '')) ?: null,
    ]
);

$productId = Database::lastId();

// A product inherits its company's keywords as a starting point.
Database::run(
    'INSERT IGNORE INTO product_tags (product_id, tag_id)
     SELECT :p, tag_id FROM company_tags WHERE company_id = :c',
    ['p' => $productId, 'c' => $companyId]
);

Audit::log('create', 'product', $productId, ['company_id' => $companyId, 'name' => $name]);
Flash::add('ok', t('company_saved'));
redirect('companies', 'view', ['id' => $companyId]);
