<?php
// Fails: get_companies.php
// VERSIJA 7: Atlasa visas kolonnas (alga, veselība, lokācija)

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');

$companies = [];

try {
    $db_file = __DIR__ . '/katalogs.sqlite';
    if (!file_exists($db_file)) {
        throw new Exception("Datubāzes fails katalogs.sqlite netika atrasts.");
    }
    
    $pdo = new PDO('sqlite:' . $db_file);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

    $kods = $_GET['kods'] ?? '';
    if (empty($kods)) {
        throw new Exception("Nav norādīts NACE kods.");
    }

    $kods = preg_replace('/[^A-Z0-9\.]/i', '', $kods);

    // --- MODIFIKĀCIJA: Atlasām pareizās kolonnas ---
    $sql_columns = "SELECT regcode, name, turnover, turnover_change, employees, employees_change, profit, profit_change, avg_net_salary, salary_change, financial_health_string, location ";

    if ($kods === 'UNDEFINED') {
        
        $sql = $sql_columns . 
               "FROM companies 
                WHERE nace_code_np = 'UNDEFINED'
                ORDER BY name ASC";
        
        $stmt_companies = $pdo->prepare($sql);
        $stmt_companies->execute();
        $companies = $stmt_companies->fetchAll();

    } else {
        $kods_bez_punktiem = str_replace('.', '', $kods);
        $like_pattern = $kods_bez_punktiem . '%';

        $sql = $sql_columns .
               "FROM companies 
                WHERE nace_code_np LIKE ?
                ORDER BY name ASC";
        
        $stmt_companies = $pdo->prepare($sql);
        $stmt_companies->execute([$like_pattern]);
        $companies = $stmt_companies->fetchAll();
    }
    // --- MODIFIKĀCIJAS BEIGAS ---

    echo json_encode($companies, JSON_NUMERIC_CHECK); 

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Servera kļūda datu atlasē: ' . $e->getMessage()]);
    exit;
}
?>