<?php
function getCompany($conn, $company_id = null) {
    if ($company_id === null) {
        $company_id = $_SESSION['active_company_id'] ?? 0;
    }
    $company_id = (int)$company_id;

    if ($company_id <= 0) {
        // Fallback: use default company
        $company = $conn->query("SELECT * FROM company_master WHERE is_default = 1 LIMIT 1")->fetch_assoc();
    } else {
        $company = $conn->query("SELECT * FROM company_master WHERE id = $company_id LIMIT 1")->fetch_assoc();
    }

    if ($company) {
        $cid = (int)$company['id'];

        // Check if bank_accounts table exists and fetch accounts for this company
        $tableCheck = $conn->query("SHOW TABLES LIKE 'company_bank_accounts'");
        $company['bank_accounts'] = [];
        if ($tableCheck && $tableCheck->num_rows > 0) {
            $banks = $conn->query(
                "SELECT * FROM company_bank_accounts
                 WHERE company_id = $cid AND display_on_invoice = 1
                 ORDER BY is_primary DESC, sort_order ASC, id ASC"
            );
            if ($banks) {
                while ($b = $banks->fetch_assoc()) {
                    $company['bank_accounts'][] = $b;
                }
            }
        }

        // Fallback: use legacy single bank from company_master if no bank accounts table entries
        if (empty($company['bank_accounts']) && !empty($company['bank_name'])) {
            $company['bank_accounts'][] = [
                'bank_name'      => $company['bank_name'],
                'account_holder' => $company['company_name'],
                'account_no'     => $company['account_no'],
                'ifsc'           => $company['ifsc'],
                'branch'         => $company['branch'] ?? '',
                'account_type'   => 'Savings',
                'upi_id'         => $company['upi_id'] ?? '',
                'upi_name'       => $company['upi_name'] ?? '',
                'is_primary'     => 1,
            ];
        }
    }
    return $company;
}
