<?php
class TaxGroup extends Model {
    protected static string $table = 'tax_groups';
    
    public static function getActive(): array {
        $tid = static::tenantId();
        $stmt = db()->prepare("
            SELECT tg.*, COUNT(p.id) as product_count
            FROM tax_groups tg
            LEFT JOIN products p ON p.tax_group_id = tg.id AND p.tenant_id = ?
            WHERE tg.tenant_id = ? AND tg.is_active = 1
            GROUP BY tg.id
            ORDER BY tg.name ASC
        ");
        $stmt->execute([$tid, $tid]);
        return $stmt->fetchAll();
    }
    
    public static function calculateTax(float $amount, ?int $taxGroupId = null): float {
        if (!$taxGroupId) {
            // Use default tax rate from settings
            $rate = (float)setting('tax_rate', 0);
            return $amount * ($rate / 100);
        }
        
        $tid = static::tenantId();
        $stmt = db()->prepare("
            SELECT rate, type FROM tax_groups 
            WHERE id = ? AND tenant_id = ? AND is_active = 1
        ");
        $stmt->execute([$taxGroupId, $tid]);
        $taxGroup = $stmt->fetch();
        
        if (!$taxGroup) {
            return 0;
        }
        
        if ($taxGroup['type'] === 'fixed') {
            return (float)$taxGroup['rate'];
        }
        
        return $amount * ((float)$taxGroup['rate'] / 100);
    }
}
