<?php

require_once __DIR__ . '/../helpers/AuthHelper.php';
require_once __DIR__ . '/../models/TimeRecord.php';
// Compat loader para modelo de colaboradores (Employee ou Employees)
$__employeeModelLoaded = false;
if (file_exists(__DIR__ . '/../models/Employees.php')) {
    require_once __DIR__ . '/../models/Employees.php';
    $__employeeModelLoaded = true;
}
if (file_exists(__DIR__ . '/../models/Employee.php')) {
    require_once __DIR__ . '/../models/Employee.php';
    $__employeeModelLoaded = true;
}
if (!$__employeeModelLoaded) {
    throw new Exception('Model Employees/Employee não encontrado em /models');
}

class TimeRecordsController {
    private $timeRecordModel;
    private $employeeModel;
    
    public function __construct() {
        $this->timeRecordModel = new TimeRecord();
        // Inicialização compatível com possíveis classes de modelo de colaboradores
        if (class_exists('\\Gabinete\\Models\\Employees')) {
            $this->employeeModel = new \Gabinete\Models\Employees();
        } elseif (class_exists('Employees')) {
            $this->employeeModel = new Employees();
        } elseif (class_exists('Employee')) {
            $this->employeeModel = new Employee();
        } else {
            throw new Exception('Classe de modelo de colaboradores não encontrada.');
        }
    }
    
    /**
     * Página principal do controle de ponto
     */
    public function index() {
        AuthHelper::check();
        
        $date = $_GET['date'] ?? date('Y-m-d');
        $employeeId = $_GET['employee_id'] ?? null;
        
        // Busca todos os colaboradores para o filtro
        $employeesRaw = $this->employeeModel->getAll();
        $employees = array_map(function($e) {
            return [
                'id' => $e['id'] ?? null,
                'name' => $e['name'] ?? ($e['full_name'] ?? ''),
                'position' => $e['position'] ?? ($e['job_title'] ?? ''),
                'email' => $e['email'] ?? '',
            ];
        }, $employeesRaw);
        
        // Busca registros do dia
        if ($employeeId) {
            $records = $this->timeRecordModel->getRecordsByPeriod($employeeId, $date, $date);
        } else {
            $records = $this->timeRecordModel->getAllRecordsByDate($date);
        }
        
        // Adiciona status atual para cada colaborador
        foreach ($records as &$record) {
            $record['current_status'] = $this->timeRecordModel->getCurrentStatus($record['employee_id']);
        }
        
        require_once __DIR__ . '/../views/time_records/index.php';
    }
    
    /**
     * Página de registro de ponto individual
     */
    public function clock($employeeId) {
        AuthHelper::check();
        
        $employee = $this->employeeModel->findById($employeeId);
        if (!$employee) {
            $_SESSION['error'] = 'Colaborador não encontrado';
            header('Location: ' . BASE_URL . '/time-records');
            exit;
        }
        
        $todayRecord = $this->timeRecordModel->getTodayRecord($employeeId);
        $currentStatus = $this->timeRecordModel->getCurrentStatus($employeeId);
        
        // Busca últimos registros
        $recentRecords = $this->timeRecordModel->getEmployeeRecords($employeeId, 10);
        
        require_once __DIR__ . '/../views/time_records/clock.php';
    }
    
    /**
     * Registra entrada
     */
    public function clockIn() {
        AuthHelper::check();
        
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $_SESSION['error'] = 'Método não permitido';
            header('Location: ' . BASE_URL . '/time-records');
            exit;
        }
        
        try {
            $employeeId = $_POST['employee_id'] ?? null;
            $notes = trim($_POST['notes'] ?? '');
            
            if (!$employeeId) {
                throw new Exception('ID do colaborador é obrigatório');
            }
            
            // Verifica se o colaborador existe
            $employee = $this->employeeModel->findById($employeeId);
            if (!$employee) {
                throw new Exception('Colaborador não encontrado');
            }
            
            $recordId = $this->timeRecordModel->clockIn($employeeId, $notes);
            
            $_SESSION['success'] = 'Entrada registrada com sucesso às ' . date('H:i');
            
        } catch (Exception $e) {
            $_SESSION['error'] = 'Erro ao registrar entrada: ' . $e->getMessage();
        }
        
        $redirectUrl = $_POST['redirect_url'] ?? BASE_URL . '/time-records';
        header('Location: ' . $redirectUrl);
    }
    
    /**
     * Registra saída
     */
    public function clockOut() {
        AuthHelper::check();
        
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $_SESSION['error'] = 'Método não permitido';
            header('Location: ' . BASE_URL . '/time-records');
            exit;
        }
        
        try {
            $employeeId = $_POST['employee_id'] ?? null;
            $notes = trim($_POST['notes'] ?? '');
            
            if (!$employeeId) {
                throw new Exception('ID do colaborador é obrigatório');
            }
            
            $recordId = $this->timeRecordModel->clockOut($employeeId, $notes);
            
            $_SESSION['success'] = 'Saída registrada com sucesso às ' . date('H:i');
            
        } catch (Exception $e) {
            $_SESSION['error'] = 'Erro ao registrar saída: ' . $e->getMessage();
        }
        
        $redirectUrl = $_POST['redirect_url'] ?? BASE_URL . '/time-records';
        header('Location: ' . $redirectUrl);
    }
    
    /**
     * Inicia pausa
     */
    public function startBreak() {
        AuthHelper::check();
        
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $_SESSION['error'] = 'Método não permitido';
            header('Location: ' . BASE_URL . '/time-records');
            exit;
        }
        
        try {
            $employeeId = $_POST['employee_id'] ?? null;
            $notes = trim($_POST['notes'] ?? '');
            
            if (!$employeeId) {
                throw new Exception('ID do colaborador é obrigatório');
            }
            
            $recordId = $this->timeRecordModel->startBreak($employeeId, $notes);
            
            $_SESSION['success'] = 'Pausa iniciada às ' . date('H:i');
            
        } catch (Exception $e) {
            $_SESSION['error'] = 'Erro ao iniciar pausa: ' . $e->getMessage();
        }
        
        $redirectUrl = $_POST['redirect_url'] ?? BASE_URL . '/time-records';
        header('Location: ' . $redirectUrl);
    }
    
    /**
     * Finaliza pausa
     */
    public function endBreak() {
        AuthHelper::check();
        
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $_SESSION['error'] = 'Método não permitido';
            header('Location: ' . BASE_URL . '/time-records');
            exit;
        }
        
        try {
            $employeeId = $_POST['employee_id'] ?? null;
            $notes = trim($_POST['notes'] ?? '');
            
            if (!$employeeId) {
                throw new Exception('ID do colaborador é obrigatório');
            }
            
            $recordId = $this->timeRecordModel->endBreak($employeeId, $notes);
            
            $_SESSION['success'] = 'Pausa finalizada às ' . date('H:i');
            
        } catch (Exception $e) {
            $_SESSION['error'] = 'Erro ao finalizar pausa: ' . $e->getMessage();
        }
        
        $redirectUrl = $_POST['redirect_url'] ?? BASE_URL . '/time-records';
        header('Location: ' . $redirectUrl);
    }
    
    /**
     * Relatório de horas trabalhadas
     */
    public function report() {
        AuthHelper::check();
        
        $employeeId = $_GET['employee_id'] ?? null;
        $month = $_GET['month'] ?? date('m');
        $year = $_GET['year'] ?? date('Y');
        
        // Busca todos os colaboradores para o filtro
        $employees = $this->employeeModel->getAll();
        
        $reports = [];
        
        $selectedEmployee = $employeeId ? (int)$employeeId : null;
        $selectedMonth = (int)$month;
        $selectedYear = (int)$year;
        $reportData = [];
        
        if ($employeeId) {
            // Relatório de um colaborador específico
            $employee = $this->employeeModel->findById($employeeId);
            if ($employee) {
                $emp = [
                    'id' => $employee['id'] ?? null,
                    'name' => $employee['name'] ?? ($employee['full_name'] ?? ''),
                    'position' => $employee['position'] ?? ($employee['job_title'] ?? ''),
                    'email' => $employee['email'] ?? '',
                ];
                $report = $this->timeRecordModel->getHoursReport($emp['id'], $selectedMonth, $selectedYear) ?: [];
                $reportData[] = [
                    'id' => $emp['id'],
                    'name' => $emp['name'],
                    'position' => $emp['position'],
                    'email' => $emp['email'],
                    'days_worked' => (int)($report['total_days'] ?? 0),
                    'total_hours' => (float)($report['total_hours'] ?? 0),
                    'total_break_time' => (int)($report['total_break_minutes'] ?? 0),
                ];
                
                // Registros detalhados do mês (opcional)
                $startDate = $selectedYear . '-' . str_pad((string)$selectedMonth, 2, '0', STR_PAD_LEFT) . '-01';
                $endDate = date('Y-m-t', strtotime($startDate));
                $detailedRecords = $this->timeRecordModel->getRecordsByPeriod($emp['id'], $startDate, $endDate);
            } else {
                $detailedRecords = [];
            }
        } else {
            // Relatório de todos os colaboradores
            foreach ($employees as $emp) {
                $report = $this->timeRecordModel->getHoursReport($emp['id'], $selectedMonth, $selectedYear) ?: [];
                $reportData[] = [
                    'id' => $emp['id'],
                    'name' => $emp['name'],
                    'position' => $emp['position'],
                    'email' => $emp['email'],
                    'days_worked' => (int)($report['total_days'] ?? 0),
                    'total_hours' => (float)($report['total_hours'] ?? 0),
                    'total_break_time' => (int)($report['total_break_minutes'] ?? 0),
                ];
            }
            $detailedRecords = [];
        }
        
        require_once __DIR__ . '/../views/time_records/report.php';
    }
    
    /**
     * API para buscar status atual (AJAX)
     */
    public function getStatus() {
        AuthHelper::check();
        
        header('Content-Type: application/json');
        
        try {
            $employeeId = $_GET['employee_id'] ?? null;
            
            if (!$employeeId) {
                throw new Exception('ID do colaborador é obrigatório');
            }
            
            $status = $this->timeRecordModel->getCurrentStatus($employeeId);
            $todayRecord = $this->timeRecordModel->getTodayRecord($employeeId);
            
            $response = [
                'success' => true,
                'status' => $status,
                'record' => $todayRecord,
                'current_time' => date('H:i:s')
            ];
            
            echo json_encode($response);
            
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Exporta relatório em CSV
     */
    public function exportCsv() {
        AuthHelper::check();
        
        try {
            $employeeId = $_GET['employee_id'] ?? null;
            $startDate = $_GET['start_date'] ?? date('Y-m-01');
            $endDate = $_GET['end_date'] ?? date('Y-m-t');
            
            if ($employeeId) {
                $records = $this->timeRecordModel->getRecordsByPeriod($employeeId, $startDate, $endDate);
                $employee = $this->employeeModel->findById($employeeId);
                $filename = 'ponto_' . ($employee['name'] ?? 'colaborador') . '_' . $startDate . '_' . $endDate . '.csv';
            } else {
                // Busca todos os registros do período
                $records = [];
                $employees = $this->employeeModel->getAll();
                foreach ($employees as $emp) {
                    $empRecords = $this->timeRecordModel->getRecordsByPeriod($emp['id'], $startDate, $endDate);
                    $records = array_merge($records, $empRecords);
                }
                $filename = 'ponto_todos_colaboradores_' . $startDate . '_' . $endDate . '.csv';
            }
            
            // Headers para download
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            header('Cache-Control: no-cache, must-revalidate');
            
            // Abre output stream
            $output = fopen('php://output', 'w');
            
            // BOM para UTF-8
            fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
            
            // Cabeçalho do CSV
            fputcsv($output, [
                'Colaborador',
                'Data',
                'Entrada',
                'Saída',
                'Horas Trabalhadas',
                'Observações'
            ], ';');
            
            // Dados
            foreach ($records as $record) {
                fputcsv($output, [
                    $record['full_name'] ?? ($record['employee_name'] ?? ($record['name'] ?? 'N/A')),
                    date('d/m/Y', strtotime($record['work_date'] ?? $record['date'] ?? 'now')),
                    TimeRecord::formatTime($record['entry_time'] ?? null),
                    TimeRecord::formatTime($record['exit_time'] ?? null),
                    isset($record['total_hours']) ? number_format((float)$record['total_hours'], 2) : '0',
                    $record['notes'] ?? ''
                ], ';');
            }
            
            fclose($output);
            exit;
            
        } catch (Exception $e) {
            $_SESSION['error'] = 'Erro ao exportar relatório: ' . $e->getMessage();
            header('Location: ' . BASE_URL . '/time-records/report');
        }
    }
}