<?hh // strict

namespace App\Controllers;

use App\Models\Application;
use App\Services\ApplicationService;
use PDO;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class ApplicationController
{
    private ApplicationService $applicationService;
    
    public function __construct()
    {
        // In a real application, this would be injected via DI container
        $this->applicationService = new ApplicationService($this->getDbConnection());
    }

    public function apply(Request $request, Response $response): Response
    {
        $params = $request->getParsedBody();
        
        // Validate required fields
        $required = ['job_id', 'user_id', 'resume_url'];
        foreach ($required as $field) {
            if (empty($params[$field])) {
                $response = $response->withStatus(400);
                $response->getBody()->write(json_encode(['error' => "Missing required field: {$field}"]));
                return $response->withHeader('Content-Type', 'application/json');
            }
        }
        
        // Get tenant from request attribute (set by middleware)
        $tenant = $request->getAttribute('tenant');
        $tenantId = $tenant ? $tenant->getId() : 'default';
        
        // Create application
        $application = new Application(
            id: 0, // Will be set by database
            jobId: (int)$params['job_id'],
            userId: (int)$params['user_id'],
            resumeUrl: $params['resume_url'],
            coverLetter: $params['cover_letter'] ?? '',
            status: 'pending', // Default status
            tenantId: $tenantId
        );
        
        $result = $this->applicationService->submitApplication($application);
        
        if ($result) {
            $response->getBody()->write(json_encode(['message' => 'Application submitted successfully']));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(201);
        } else {
            $response = $response->withStatus(500);
            $response->getBody()->write(json_encode(['error' => 'Failed to submit application']));
            return $response->withHeader('Content-Type', 'application/json');
        }
    }
    
    public function getApplicationsByUser(Request $request, Response $response): Response
    {
        // Get tenant from request attribute (set by middleware)
        $tenant = $request->getAttribute('tenant');
        
        // In a real application, you would get the authenticated user ID from the JWT token
        // For now, we'll use a placeholder user ID
        $userId = $request->getAttribute('user_id') ?? 1;
        
        $applications = $this->applicationService->getApplicationsByUser($userId, $tenant);
        
        $applicationsArray = [];
        foreach ($applications as $application) {
            $applicationsArray[] = [
                'id' => $application->getId(),
                'job_id' => $application->getJobId(),
                'user_id' => $application->getUserId(),
                'resume_url' => $application->getResumeUrl(),
                'cover_letter' => $application->getCoverLetter(),
                'status' => $application->getStatus(),
                'created_at' => $application->getCreatedAt()->format('Y-m-d H:i:s')
            ];
        }
        
        $response->getBody()->write(json_encode($applicationsArray));
        return $response->withHeader('Content-Type', 'application/json');
    }
    
    public function getApplicationsByJob(Request $request, Response $response, array $args): Response
    {
        $jobId = (int)$args['job_id'];
        
        // Get tenant from request attribute (set by middleware)
        $tenant = $request->getAttribute('tenant');
        
        $applications = $this->applicationService->getApplicationsByJob($jobId, $tenant);
        
        $applicationsArray = [];
        foreach ($applications as $application) {
            $applicationsArray[] = [
                'id' => $application->getId(),
                'job_id' => $application->getJobId(),
                'user_id' => $application->getUserId(),
                'resume_url' => $application->getResumeUrl(),
                'cover_letter' => $application->getCoverLetter(),
                'status' => $application->getStatus(),
                'created_at' => $application->getCreatedAt()->format('Y-m-d H:i:s')
            ];
        }
        
        $response->getBody()->write(json_encode($applicationsArray));
        return $response->withHeader('Content-Type', 'application/json');
    }
    
    private function getDbConnection(): PDO
    {
        // In a real application, this would be configured properly
        $host = $_ENV['DB_HOST'] ?? 'localhost';
        $dbname = $_ENV['DB_NAME'] ?? 'moh';
        $username = $_ENV['DB_USER'] ?? 'moh_user';
        $password = $_ENV['DB_PASS'] ?? 'moh_password';
        $port = $_ENV['DB_PORT'] ?? '5432';
        
        $dsn = "pgsql:host={$host};port={$port};dbname={$dbname};";
        return new PDO($dsn, $username, $password, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
    }
}