<?php
// src/Middleware/TenantMiddleware.php
namespace App\Middleware;

use App\Models\Tenant;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class TenantMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // Extract subdomain from the host
        $host = $request->getHeaderLine('Host');
        $subdomain = $this->extractSubdomain($host);
        
        // If no specific subdomain, assume the main site
        if (!$subdomain || $subdomain === 'localhost') {
            $subdomain = 'tsys'; // default tenant
        }
        
        // Find tenant by subdomain
        $tenantModel = new Tenant();
        $tenant = $tenantModel->findBySubdomain($subdomain);
        
        // If tenant not found, use default tenant for development
        if (!$tenant) {
            // Try to get the default tenant
            $tenant = $tenantModel->findBySubdomain('tsys');
        }
        
        if (!$tenant) {
            // Handle case where even default tenant doesn't exist
            $response = new \Slim\Psr7\Response();
            $response->getBody()->write(json_encode(['error' => 'Tenant not found']));
            return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
        }
        
        // Add tenant to request attributes for use in route handlers
        $request = $request->withAttribute('tenant', $tenant);
        
        return $handler->handle($request);
    }
    
    private function extractSubdomain(string $host): ?string
    {
        // Remove port if present
        $host = preg_replace('/:\d+$/', '', $host);
        
        // For localhost, return null to trigger default behavior
        if ($host === 'localhost') {
            return null;
        }
        
        $hostParts = explode('.', $host);
        
        // For IP addresses, return null to trigger default behavior
        if (filter_var($hostParts[0], FILTER_VALIDATE_IP)) {
            return null;
        }
        
        // Return the first part (subdomain) if we have multiple parts
        if (count($hostParts) > 1) {
            return $hostParts[0];
        }
        
        // For single part hosts, return null to trigger default behavior
        return null;
    }
}