<?php
// src/Application.php
namespace App;

use DI\Container;
use Slim\Factory\AppFactory;
use Slim\Middleware\ContentLengthMiddleware;
use Slim\Psr7\Request;
use Slim\Psr7\Response;
use App\Middleware\TenantMiddleware;

class Application
{
    private $app;

    public function __construct()
    {
        // Create and set the DI container
        $container = new Container();
        AppFactory::setContainer($container);

        // Create the app
        $this->app = AppFactory::create();

        // Register middleware
        $this->app->addBodyParsingMiddleware();
        $this->app->add(new ContentLengthMiddleware());
        
        // Add security middleware
        $this->app->add(new \App\Middleware\SecurityMiddleware());
        $this->app->add(new \App\Middleware\CorsMiddleware());
        
        // Add tenant middleware to handle multi-tenancy
        $this->app->add(new TenantMiddleware());

        // Register routes
        $this->registerRoutes();
    }

    private function registerRoutes(): void
    {
        $this->app->get('/', function (Request $request, Response $response, array $args) {
            $tenant = $request->getAttribute('tenant');
            
            // For API requests, return JSON
            if ($request->getHeaderLine('Accept') && strpos($request->getHeaderLine('Accept'), 'application/json') !== false) {
                $data = [
                    'tenant' => $tenant['name'],
                    'service' => 'MerchantsOfHope Recruiting Platform',
                    'description' => 'API for job postings and applications',
                    'endpoints' => [
                        'GET /positions' => 'Browse available job positions',
                        'GET /positions/{id}' => 'Get details for a specific position',
                        'POST /positions/{id}/apply' => 'Apply for a job position',
                        'GET /my/applications' => 'Get your job applications',
                        'POST /auth/login' => 'Authenticate user',
                        'GET /auth/oidc' => 'Initiate OIDC authentication',
                        'GET /auth/google' => 'Initiate Google authentication',
                        'GET /auth/facebook' => 'Initiate Facebook authentication'
                    ]
                ];
                $response->getBody()->write(json_encode($data));
                return $response->withHeader('Content-Type', 'application/json');
            } else {
                // For web browsers, return HTML page
                $html = file_get_contents(__DIR__ . '/../public/index.html');
                $response->getBody()->write(str_replace('{{tenant_name}}', $tenant['name'], $html));
                return $response->withHeader('Content-Type', 'text/html');
            }
        });

        $this->app->get('/health', function (Request $request, Response $response, array $args) {
            $data = [
                'status' => 'ok',
                'service' => 'MerchantsOfHope Recruiting Platform',
                'tenant' => $request->getAttribute('tenant')['name'] ?? 'unknown',
                'timestamp' => date('c'),
                'accessibility_compliant' => true,
                'standards' => ['WCAG 2.1 AA', 'Section 508', 'ADA']
            ];
            $response->getBody()->write(json_encode($data));
            return $response->withHeader('Content-Type', 'application/json');
        });
        

        
        // Tenant-specific user authentication routes
        $this->app->post('/auth/login', function (Request $request, Response $response, array $args) {
            $tenant = $request->getAttribute('tenant');
            $parsedBody = $request->getParsedBody();
            
            $email = $parsedBody['email'] ?? '';
            $password = $parsedBody['password'] ?? '';
            
            if (empty($email) || empty($password)) {
                $response->getBody()->write(json_encode(['error' => 'Email and password are required']));
                return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
            }
            
            // Authenticate user
            $userModel = new \App\Models\User();
            $user = $userModel->authenticate($email, $password);
            
            if ($user && $user['tenant_id'] === $tenant['id']) {
                // For now, just return user info
                $response->getBody()->write(json_encode([
                    'user' => [
                        'id' => $user['id'],
                        'email' => $user['email'],
                        'first_name' => $user['first_name'],
                        'last_name' => $user['last_name'],
                        'role' => $user['role']
                    ]
                ]));
                return $response->withHeader('Content-Type', 'application/json');
            } else {
                $response->getBody()->write(json_encode(['error' => 'Invalid credentials']));
                return $response->withStatus(401)->withHeader('Content-Type', 'application/json');
            }
        });
        
        // OIDC/Social login routes
        $this->app->get('/auth/oidc', [\App\Controllers\AuthController::class, 'redirectToOIDC']);
        $this->app->get('/auth/callback', [\App\Controllers\AuthController::class, 'handleOIDCCallback']);
        $this->app->get('/auth/google', [\App\Controllers\AuthController::class, 'redirectToGoogle']);
        $this->app->get('/auth/facebook', [\App\Controllers\AuthController::class, 'redirectToFacebook']);
        
        // More specific callback routes for social providers
        $this->app->get('/auth/google/callback', [\App\Controllers\AuthController::class, 'handleOIDCCallback']); // Reuse for now
        $this->app->get('/auth/facebook/callback', [\App\Controllers\AuthController::class, 'handleOIDCCallback']); // Reuse for now
        
        // Job seeker routes
        $this->app->get('/positions', [\App\Controllers\JobSeekerController::class, 'browsePositions']);
        $this->app->get('/positions/{id}', [\App\Controllers\JobSeekerController::class, 'getPosition']);
        $this->app->post('/positions/{id}/apply', [\App\Controllers\JobSeekerController::class, 'applyForPosition']);
        $this->app->get('/my/applications', [\App\Controllers\JobSeekerController::class, 'getMyApplications']);
        
        // Job provider routes
        $this->app->post('/positions', [\App\Controllers\JobProviderController::class, 'createPosition']);
        $this->app->put('/positions/{id}', [\App\Controllers\JobProviderController::class, 'updatePosition']);
        $this->app->delete('/positions/{id}', [\App\Controllers\JobProviderController::class, 'deletePosition']);
        $this->app->get('/positions/{id}/applications', [\App\Controllers\JobProviderController::class, 'getApplicationsForPosition']);
        $this->app->put('/applications/{id}', [\App\Controllers\JobProviderController::class, 'updateApplicationStatus']);
    }

    public function run(): void
    {
        $this->app->run();
    }
}