<?php
// src/Controllers/JobSeekerController.php
namespace App\Controllers;

use App\Models\JobPosition;
use App\Models\ApplicationModel;
use App\Models\User;
use App\Auth\AuthService;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Psr7\Response;

class JobSeekerController
{
    private $jobPositionModel;
    private $applicationModel;
    private $authService;

    public function __construct()
    {
        $this->jobPositionModel = new JobPosition();
        $this->applicationModel = new ApplicationModel();
        $this->authService = new AuthService();
    }

    public function browsePositions(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
    {
        $tenant = $request->getAttribute('tenant');
        
        // Get query parameters for filtering
        $queryParams = $request->getQueryParams();
        $location = $queryParams['location'] ?? null;
        $type = $queryParams['type'] ?? null;
        $search = $queryParams['search'] ?? null;
        
        // Get all published positions for this tenant
        $positions = $this->jobPositionModel->findByTenant($tenant['id'], 'published');
        
        // Apply filters if provided
        if ($location) {
            $positions = array_filter($positions, function($pos) use ($location) {
                return stripos($pos['location'], $location) !== false;
            });
        }
        
        if ($type) {
            $positions = array_filter($positions, function($pos) use ($type) {
                return stripos($pos['employment_type'], $type) !== false;
            });
        }
        
        if ($search) {
            $positions = array_filter($positions, function($pos) use ($search) {
                return stripos($pos['title'], $search) !== false || 
                       stripos($pos['description'], $search) !== false;
            });
        }
        
        $result = [
            'positions' => array_values($positions), // Re-index array after filtering
            'tenant' => $tenant['name'],
            'filters' => [
                'location' => $location,
                'type' => $type,
                'search' => $search
            ]
        ];
        
        $response->getBody()->write(json_encode($result));
        return $response->withHeader('Content-Type', 'application/json');
    }

    public function getPosition(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
    {
        $tenant = $request->getAttribute('tenant');
        $positionId = $args['id'] ?? null;
        
        if (!$positionId) {
            $response->getBody()->write(json_encode(['error' => 'Position ID is required']));
            return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
        }
        
        $position = $this->jobPositionModel->findById($positionId, $tenant['id']);
        
        if (!$position) {
            $response->getBody()->write(json_encode(['error' => 'Position not found']));
            return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
        }
        
        $result = [
            'position' => $position,
            'tenant' => $tenant['name']
        ];
        
        $response->getBody()->write(json_encode($result));
        return $response->withHeader('Content-Type', 'application/json');
    }

    public function applyForPosition(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
    {
        $tenant = $request->getAttribute('tenant');
        $positionId = $args['id'] ?? null;
        
        // For now, we'll assume the user is authenticated and get their ID from query params or headers
        // In a real app, this would be extracted from the JWT in an authentication middleware
        $userId = $_GET['user_id'] ?? null; // This is just for demo purposes
        
        if (!$positionId) {
            $response->getBody()->write(json_encode(['error' => 'Position ID is required']));
            return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
        }
        
        if (!$userId) {
            $response->getBody()->write(json_encode(['error' => 'User ID is required']));
            return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
        }
        
        // Verify that the position exists and belongs to the current tenant
        $position = $this->jobPositionModel->findById($positionId, $tenant['id']);
        
        if (!$position) {
            $response->getBody()->write(json_encode(['error' => 'Position not found or does not belong to this tenant']));
            return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
        }
        
        $parsedBody = $request->getParsedBody();
        $resumePath = $parsedBody['resume_path'] ?? '';
        $coverLetter = $parsedBody['cover_letter'] ?? '';
        
        // Create application
        $applicationData = [
            'job_position_id' => $positionId,
            'applicant_id' => $userId,
            'resume_path' => $resumePath,
            'cover_letter' => $coverLetter,
            'status' => 'submitted'
        ];
        
        $applicationId = $this->applicationModel->create($applicationData);
        
        $result = [
            'message' => 'Application submitted successfully',
            'application_id' => $applicationId,
            'position' => $position,
            'tenant' => $tenant['name']
        ];
        
        $response->getBody()->write(json_encode($result));
        return $response->withHeader('Content-Type', 'application/json');
    }

    public function getMyApplications(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
    {
        $tenant = $request->getAttribute('tenant');
        
        // For now, we'll assume the user is authenticated and get their ID from query params or headers
        // In a real app, this would be extracted from the JWT in an authentication middleware
        $userId = $_GET['user_id'] ?? null; // This is just for demo purposes
        
        if (!$userId) {
            $response->getBody()->write(json_encode(['error' => 'User ID is required']));
            return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
        }
        
        $applications = $this->applicationModel->findByApplicant($userId, $tenant['id']);
        
        $result = [
            'applications' => $applications,
            'tenant' => $tenant['name'],
            'applicant_id' => $userId
        ];
        
        $response->getBody()->write(json_encode($result));
        return $response->withHeader('Content-Type', 'application/json');
    }
}