<?php require_once __DIR__ . '/../partials/header.php'; ?>

<?php
// Fallback: auto-suficiente ao acesso direto
if (!isset($employees) || !is_array($employees)) {
    $employeesList = [];
    $empModel = null;
    $empModelPath = dirname(__DIR__, 2) . '/models/Employees.php';
    if (file_exists($empModelPath)) {
        require_once $empModelPath;
        if (class_exists('\\Gabinete\\Models\\Employees')) {
            $empModel = new \Gabinete\Models\Employees();
            try {
                $employeesList = $empModel->getAll();
            } catch (Throwable $e) {
                $employeesList = [];
            }
        }
    }
    $employees = array_map(function($e) {
        return [
            'id' => $e['id'] ?? null,
            'name' => $e['name'] ?? ($e['full_name'] ?? ''),
            'position' => $e['position'] ?? ($e['job_title'] ?? ''),
        ];
    }, $employeesList);
}

if (!isset($records) || !is_array($records)) {
    $trModelPath = dirname(__DIR__, 2) . '/models/TimeRecord.php';
    if (file_exists($trModelPath)) {
        require_once $trModelPath;
        if (class_exists('TimeRecord')) {
            $tr = new TimeRecord();
            $date = $_GET['date'] ?? date('Y-m-d');
            $employeeId = $_GET['employee_id'] ?? null;
            try {
                if ($employeeId) {
                    $records = $tr->getRecordsByPeriod($employeeId, $date, $date);
                } else {
                    $records = $tr->getAllRecordsByDate($date);
                }
                foreach ($records as &$record) {
                    try {
                        $record['current_status'] = $tr->getCurrentStatus($record['employee_id']);
                    } catch (Throwable $e) {
                        $record['current_status'] = 'not_clocked_in';
                    }
                    if (!isset($record['position'])) {
                        $record['position'] = '';
                    }
                }
                unset($record);
            } catch (Throwable $e) {
                $records = [];
                $_SESSION['error'] = 'Erro ao carregar registros de ponto: ' . $e->getMessage();
            }
        }
    }
}
?>
<style>
/* Oculta o ícone da navbar apenas nesta página de Controle de Ponto */
.navbar-brand .bi { display: none !important; }
</style>
<div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <!-- Cabeçalho -->
        <div class="mb-8">
            <div class="flex justify-between items-center">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900">Controle de Ponto</h1>
                    <p class="mt-2 text-gray-600">Gerencie os registros de entrada e saída dos colaboradores</p>
                    <a href="<?= BASE_URL ?>/src/views/rh/index.php" 
                       class="inline-flex items-center mt-3 bg-gray-600 hover:bg-gray-700 text-white px-3 py-2 rounded-lg font-medium transition-colors">
                        ← Voltar
                    </a>
                </div>
                <div class="flex space-x-3">
                    <a href="<?= BASE_URL ?>/src/views/rh/index.php" 
                       class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg font-medium transition-colors">
                        ← Voltar
                    </a>
                    <a href="<?= BASE_URL ?>/time-records/report" 
                       class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg font-medium transition-colors">
                        Relatórios
                    </a>
                </div>
            </div>
        </div>

        <!-- Mensagens -->
        <?php if (isset($_SESSION['success'])): ?>
            <div class="mb-6 bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded">
                <?= htmlspecialchars($_SESSION['success']) ?>
                <?php unset($_SESSION['success']); ?>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error'])): ?>
            <div class="mb-6 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
                <?= htmlspecialchars($_SESSION['error']) ?>
                <?php unset($_SESSION['error']); ?>
            </div>
        <?php endif; ?>

        <!-- Filtros -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
            <form method="GET" class="flex flex-wrap gap-4 items-end">
                <div class="flex-1 min-w-48">
                    <label for="date" class="block text-sm font-medium text-gray-700 mb-2">Data</label>
                    <input type="date" 
                           id="date" 
                           name="date" 
                           value="<?= htmlspecialchars($_GET['date'] ?? date('Y-m-d')) ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                </div>
                
                <div class="flex-1 min-w-48">
                    <label for="employee_id" class="block text-sm font-medium text-gray-700 mb-2">Colaborador</label>
                    <select id="employee_id" 
                            name="employee_id" 
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        <option value="">Todos os colaboradores</option>
                        <?php foreach ($employees as $employee): ?>
                            <option value="<?= $employee['id'] ?>" 
                                    <?= (isset($_GET['employee_id']) && $_GET['employee_id'] == $employee['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($employee['name']) ?> - <?= htmlspecialchars($employee['position']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="flex space-x-2">
                    <button type="submit" 
                            class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg font-medium transition-colors">
                        Filtrar
                    </button>
                    <a href="<?= BASE_URL ?>/time-records" 
                       class="bg-gray-500 hover:bg-gray-600 text-white px-6 py-2 rounded-lg font-medium transition-colors">
                        Limpar
                    </a>
                </div>
            </form>
        </div>

        <!-- Resumo do dia -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
            <?php
            $totalPresent = 0;
            $totalWorking = 0;
            $totalOut = 0;
            
            foreach ($records as $record) {
                $totalPresent++;
                switch ($record['current_status']) {
                    case 'working':
                        $totalWorking++;
                        break;
                    case 'clocked_out':
                        $totalOut++;
                        break;
                }
            }
            ?>
            
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <div class="flex items-center">

                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-500">Total Presente</p>
                        <p class="text-2xl font-bold text-gray-900"><?= $totalPresent ?></p>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <div class="flex items-center">

                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-500">Trabalhando</p>
                        <p class="text-2xl font-bold text-gray-900"><?= $totalWorking ?></p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <div class="flex items-center">

                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-500">Saíram</p>
                        <p class="text-2xl font-bold text-gray-900"><?= $totalOut ?></p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Lista de registros -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-medium text-gray-900">
                    Registros de <?= date('d/m/Y', strtotime($_GET['date'] ?? date('Y-m-d'))) ?>
                </h3>
            </div>
            
            <?php if (empty($records)): ?>
                <div class="p-6 text-center">

                    <h3 class="mt-2 text-sm font-medium text-gray-900">Nenhum registro encontrado</h3>
                    <p class="mt-1 text-sm text-gray-500">Não há registros de ponto para os filtros selecionados.</p>
                </div>
            <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Colaborador</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Entrada</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Saída</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Horas</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Ações</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($records as $record): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="flex items-center">
                                            <div class="flex-shrink-0 h-10 w-10">
                                                <div class="h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center">
                                                    <span class="text-sm font-medium text-gray-700">
                                                        <?= strtoupper(substr($record['employee_name'], 0, 2)) ?>
                                                    </span>
                                                </div>
                                            </div>
                                            <div class="ml-4">
                                                <div class="text-sm font-medium text-gray-900">
                                                    <?= htmlspecialchars($record['employee_name']) ?>
                                                </div>
                                                <div class="text-sm text-gray-500">
                                                    <?= htmlspecialchars($record['position'] ?? '') ?>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <?php
                                        $statusConfig = [
                                            'working' => ['text' => 'Trabalhando', 'class' => 'bg-green-100 text-green-800'],
                                            'clocked_out' => ['text' => 'Saiu', 'class' => 'bg-gray-100 text-gray-800'],
                                            'not_clocked_in' => ['text' => 'Não Entrou', 'class' => 'bg-red-100 text-red-800']
                                        ];
                                        $status = $statusConfig[$record['current_status']] ?? $statusConfig['not_clocked_in'];
                                        ?>
                                        <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full <?= $status['class'] ?>">
                                            <?= $status['text'] ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                        <?= TimeRecord::formatTime($record['entry_time'] ?? null) ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                        <?= TimeRecord::formatTime($record['exit_time'] ?? null) ?>
                                    </td>

                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                        <?= isset($record['total_hours']) && $record['total_hours'] !== null ? number_format((float)$record['total_hours'], 2) . 'h' : '-' ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                        <a href="<?= BASE_URL ?>/time-records/clock/<?= $record['employee_id'] ?>" 
                                           class="text-blue-600 hover:text-blue-900 mr-3">
                                            Gerenciar
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// Auto-refresh da página a cada 30 segundos
setTimeout(function() {
    location.reload();
}, 30000);

// Atualiza a hora atual
function updateCurrentTime() {
    const now = new Date();
    const timeString = now.toLocaleTimeString('pt-BR');
    document.title = 'Controle de Ponto - ' + timeString;
}

setInterval(updateCurrentTime, 1000);
updateCurrentTime();
</script>

<?php require_once __DIR__ . '/../partials/footer.php'; ?>