<?php

require_once __DIR__ . '/../models/Employee.php';
require_once __DIR__ . '/../models/TimeRecord.php';
require_once __DIR__ . '/../models/Payroll.php';
require_once __DIR__ . '/../helpers/AuthHelper.php';
require_once __DIR__ . '/../helpers/PermissionHelper.php';

class RhController {
    private $employeeModel;
    private $timeRecordModel;
    private $payrollModel;
    
    public function __construct() {
        $this->employeeModel = new Employee();
        $this->timeRecordModel = new TimeRecord();
        $this->payrollModel = new Payroll();
    }
    
    /**
     * Página principal do RH - Dashboard
     */
    public function index() {
        AuthHelper::check();
        PermissionHelper::redirecionarSeNaoTemPermissao('rh', 'visualizar');
        
        try {
            // Buscar estatísticas básicas
            $stats = $this->getStats();
            
            require_once __DIR__ . '/../views/rh/index.php';
        } catch (Exception $e) {
            $_SESSION['error'] = 'Erro ao carregar dashboard RH: ' . $e->getMessage();
            header('Location: ' . BASE_URL);
            exit;
        }
    }
    
    /**
     * API para buscar estatísticas do RH
     */
    public function stats() {
        AuthHelper::check();
        
        header('Content-Type: application/json');
        
        try {
            $stats = $this->getStats();
            echo json_encode([
                'status' => 'success',
                'data' => $stats
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'status' => 'error',
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Buscar estatísticas do RH
     */
    private function getStats() {
        try {
            // Total de colaboradores ativos
            $allEmployees = $this->employeeModel->getAll();
            $activeEmployees = array_filter($allEmployees, function($emp) {
                return $emp['status'] === 'active';
            });
            $totalEmployees = count($activeEmployees);
            
            // Valores básicos para demonstração
            $presentToday = 0;
            $payrollsThisMonth = 0;
            $hoursToday = '0h';
            
            return [
                'total_employees' => $totalEmployees,
                'present_today' => $presentToday,
                'payrolls_month' => $payrollsThisMonth,
                'hours_today' => $hoursToday
            ];
        } catch (Exception $e) {
            // Retorna valores padrão em caso de erro
            return [
                'total_employees' => 0,
                'present_today' => 0,
                'payrolls_month' => 0,
                'hours_today' => '0h'
            ];
        }
    }
}