<?php
// src/Controllers/JobProviderController.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 JobProviderController
{
    private $jobPositionModel;
    private $applicationModel;
    private $userModel;
    private $authService;

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

    public function createPosition(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');
        }
        
        // Verify the user exists and is part of the tenant
        $user = $this->userModel->findById($userId);
        
        if (!$user || $user['tenant_id'] !== $tenant['id']) {
            $response->getBody()->write(json_encode(['error' => 'User not found or does not belong to this tenant']));
            return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
        }
        
        $parsedBody = $request->getParsedBody();
        
        // Validate required fields
        $requiredFields = ['title', 'description'];
        foreach ($requiredFields as $field) {
            if (empty($parsedBody[$field])) {
                $response->getBody()->write(json_encode(['error' => "$field is required"]));
                return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
            }
        }
        
        $positionData = [
            'tenant_id' => $tenant['id'],
            'title' => $parsedBody['title'],
            'description' => $parsedBody['description'],
            'location' => $parsedBody['location'] ?? '',
            'employment_type' => $parsedBody['employment_type'] ?? 'full_time',
            'salary_min' => $parsedBody['salary_min'] ?? null,
            'salary_max' => $parsedBody['salary_max'] ?? null,
            'posted_by' => $userId,
            'status' => $parsedBody['status'] ?? 'draft' // Default to draft, can be published later
        ];
        
        $positionId = $this->jobPositionModel->create($positionData);
        
        $result = [
            'message' => 'Job position created successfully',
            'position_id' => $positionId,
            'position' => $positionData,
            'tenant' => $tenant['name']
        ];
        
        $response->getBody()->write(json_encode($result));
        return $response->withHeader('Content-Type', 'application/json');
    }

    public function updatePosition(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');
        }
        
        // Verify the position belongs to this 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();
        
        // For this demo, we'll just update the status
        if (isset($parsedBody['status'])) {
            $validStatuses = ['draft', 'published', 'closed'];
            if (!in_array($parsedBody['status'], $validStatuses)) {
                $response->getBody()->write(json_encode(['error' => 'Invalid status value']));
                return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
            }
            
            $updated = $this->jobPositionModel->updateStatus($positionId, $parsedBody['status'], $tenant['id']);
            
            if (!$updated) {
                $response->getBody()->write(json_encode(['error' => 'Failed to update position status']));
                return $response->withStatus(500)->withHeader('Content-Type', 'application/json');
            }
            
            $result = [
                'message' => 'Position status updated successfully',
                'position_id' => $positionId,
                'new_status' => $parsedBody['status'],
                'tenant' => $tenant['name']
            ];
        } else {
            $result = [
                'message' => 'Nothing to update',
                'position_id' => $positionId,
                'tenant' => $tenant['name']
            ];
        }
        
        $response->getBody()->write(json_encode($result));
        return $response->withHeader('Content-Type', 'application/json');
    }

    public function deletePosition(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');
        }
        
        // In a real implementation, we would delete the position
        // For this demo, we'll just mark it as 'closed'
        $updated = $this->jobPositionModel->updateStatus($positionId, 'closed', $tenant['id']);
        
        if (!$updated) {
            $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');
        }
        
        $result = [
            'message' => 'Position closed successfully',
            'position_id' => $positionId,
            'tenant' => $tenant['name']
        ];
        
        $response->getBody()->write(json_encode($result));
        return $response->withHeader('Content-Type', 'application/json');
    }

    public function getApplicationsForPosition(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');
        }
        
        // Verify the position belongs to this 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');
        }
        
        $applications = $this->applicationModel->findByJobPosition($positionId, $tenant['id']);
        
        $result = [
            'applications' => $applications,
            'position' => $position,
            'tenant' => $tenant['name']
        ];
        
        $response->getBody()->write(json_encode($result));
        return $response->withHeader('Content-Type', 'application/json');
    }

    public function updateApplicationStatus(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
    {
        $tenant = $request->getAttribute('tenant');
        $applicationId = $args['id'] ?? null;
        
        if (!$applicationId) {
            $response->getBody()->write(json_encode(['error' => 'Application ID is required']));
            return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
        }
        
        $parsedBody = $request->getParsedBody();
        
        if (!isset($parsedBody['status'])) {
            $response->getBody()->write(json_encode(['error' => 'Status is required']));
            return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
        }
        
        $validStatuses = ['submitted', 'under_review', 'accepted', 'rejected'];
        if (!in_array($parsedBody['status'], $validStatuses)) {
            $response->getBody()->write(json_encode(['error' => 'Invalid status value']));
            return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
        }
        
        $updated = $this->applicationModel->updateStatus($applicationId, $parsedBody['status'], $tenant['id']);
        
        if (!$updated) {
            $response->getBody()->write(json_encode(['error' => 'Application not found or does not belong to this tenant']));
            return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
        }
        
        $result = [
            'message' => 'Application status updated successfully',
            'application_id' => $applicationId,
            'new_status' => $parsedBody['status'],
            'tenant' => $tenant['name']
        ];
        
        $response->getBody()->write(json_encode($result));
        return $response->withHeader('Content-Type', 'application/json');
    }
}