<?php
class Location extends Model {
    protected static string $table = 'locations';

    public static function active(): array {
        $stmt = db()->prepare("SELECT * FROM locations WHERE tenant_id=? AND is_active=1 ORDER BY name");
        $stmt->execute([static::tenantId()]);
        return $stmt->fetchAll();
    }

    public static function withStockSummary(): array {
        $tid = static::tenantId();
        $stmt = db()->prepare(
            "SELECT l.*, COUNT(DISTINCT s.product_id) as product_count,
                    COALESCE(SUM(s.quantity),0) as total_stock
             FROM locations l
             LEFT JOIN stock s ON s.location_id=l.id AND s.tenant_id=l.tenant_id
             WHERE l.tenant_id=? AND l.is_active=1
             GROUP BY l.id ORDER BY l.name"
        );
        $stmt->execute([$tid]);
        return $stmt->fetchAll();
    }

    public static function shopLocations(): array {
        $stmt = db()->prepare("SELECT * FROM locations WHERE tenant_id=? AND is_active=1 AND type IN ('store', 'outlet') ORDER BY name");
        $stmt->execute([static::tenantId()]);
        return $stmt->fetchAll();
    }

    public static function warehouseLocations(): array {
        $stmt = db()->prepare("SELECT * FROM locations WHERE tenant_id=? AND is_active=1 AND type = 'warehouse' ORDER BY name");
        $stmt->execute([static::tenantId()]);
        return $stmt->fetchAll();
    }

    public static function findById(int $id): ?array {
        $stmt = db()->prepare("SELECT * FROM locations WHERE id=? AND tenant_id=?");
        $stmt->execute([$id, static::tenantId()]);
        return $stmt->fetch() ?: null;
    }
}
