<?php
declare(strict_types=1);

Auth::requireLogin();
require_once __DIR__ . '/_query.php';

[$whereSql, $params, $orderSql] = companies_filter();

$rows = Database::all(
    "SELECT v.name, v.country_name, v.tags, v.relationships, v.website, v.status,
            v.threat_level, v.last_visit_date, v.next_due_date, v.frequency_days,
            v.assigned_to, v.product_count, v.link_count, v.visit_count
       FROM v_company_overview v
       JOIN companies c ON c.id = v.id
       LEFT JOIN watches w ON w.company_id = c.id
     {$whereSql}
     {$orderSql}",
    $params
);

Audit::log('export', 'company', null, ['rows' => count($rows)]);

$filename = 'competitors-' . date('Y-m-d') . '.csv';

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-store');

$out = fopen('php://output', 'wb');

// BOM so Excel opens the UTF-8 correctly on Windows.
fwrite($out, "\xEF\xBB\xBF");

fputcsv($out, [
    'Company', 'Country', 'Keywords', 'Relationship', 'Website', 'Status',
    'Threat', 'Last check', 'Next due', 'Check every (days)', 'Assigned to',
    'Products', 'Links', 'Checks logged',
]);

foreach ($rows as $r) {
    fputcsv($out, [
        $r['name'],
        $r['country_name'],
        $r['tags'],
        $r['relationships'],
        $r['website'],
        $r['status'],
        $r['threat_level'],
        $r['last_visit_date'],
        $r['next_due_date'],
        $r['frequency_days'],
        $r['assigned_to'],
        $r['product_count'],
        $r['link_count'],
        $r['visit_count'],
    ]);
}

fclose($out);
exit;
