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

<div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <!-- Cabeçalho -->
        <div class="mb-8">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900">Controle de Ponto</h1>
                    <p class="mt-2 text-gray-600"><?= htmlspecialchars($employee['name']) ?> - <?= htmlspecialchars($employee['position']) ?></p>
                </div>
                <div class="text-right">
                    <div class="text-2xl font-bold text-gray-900" id="current-time"><?= date('H:i:s') ?></div>
                    <div class="text-sm text-gray-500"><?= date('d/m/Y') ?></div>
                </div>
            </div>
            <div class="mt-4">
                <a href="<?= BASE_URL ?>/src/views/rh/index.php" class="text-blue-600 hover:text-blue-800 font-medium">
                    ← Voltar para RH
                </a>
            </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; ?>

        <!-- Status atual -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
            <h2 class="text-lg font-medium text-gray-900 mb-4">Status Atual</h2>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <?php
                    $statusConfig = [
                        'not_clocked_in' => [
                            'text' => 'Não registrou entrada',
                            'class' => 'bg-red-100 text-red-800',
                            'icon' => 'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 0 0118 0z'
                        ],
                        'working' => [
                            'text' => 'Trabalhando',
                            'class' => 'bg-green-100 text-green-800',
                            'icon' => 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 0 0118 0z'
                        ],
                        'clocked_out' => [
                            'text' => 'Saiu',
                            'class' => 'bg-gray-100 text-gray-800',
                            'icon' => 'M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1'
                        ]
                    ];
                    $status = $statusConfig[$currentStatus] ?? $statusConfig['not_clocked_in'];
                    ?>
                    
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="<?= $status['icon'] ?>"></path>
                            </svg>
                        </div>
                        <div class="ml-4">
                            <span class="inline-flex px-3 py-1 text-sm font-semibold rounded-full <?= $status['class'] ?>">
                                <?= $status['text'] ?>
                            </span>
                        </div>
                    </div>
                </div>
                
                <?php if ($todayRecord): ?>
                    <div class="space-y-2">
                        <div class="flex justify-between">
                            <span class="text-sm text-gray-500">Entrada:</span>
                            <span class="text-sm font-medium"><?= TimeRecord::formatTime($todayRecord['entry_time'] ?? null) ?></span>
                        </div>
                        <?php if (!empty($todayRecord['exit_time'])): ?>
                            <div class="flex justify-between">
                                <span class="text-sm text-gray-500">Saída:</span>
                                <span class="text-sm font-medium"><?= TimeRecord::formatTime($todayRecord['exit_time']) ?></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-sm text-gray-500">Horas trabalhadas:</span>
                                <span class="text-sm font-medium"><?= isset($todayRecord['total_hours']) ? number_format((float)$todayRecord['total_hours'], 2) . 'h' : '-' ?></span>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Ações de ponto -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
            <h2 class="text-lg font-medium text-gray-900 mb-4">Ações</h2>
            
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <!-- Registrar Entrada -->
                <?php if ($currentStatus === 'not_clocked_in'): ?>
                    <button onclick="openActionModal('clock-in')" 
                            class="bg-green-600 hover:bg-green-700 text-white p-4 rounded-lg font-medium transition-colors">
                        <svg class="w-6 h-6 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"></path>
                        </svg>
                        Registrar Entrada
                    </button>
                <?php endif; ?>
                
                <!-- Registrar Saída -->
                <?php if ($currentStatus === 'working'): ?>
                    <button onclick="openActionModal('clock-out')" 
                            class="bg-red-600 hover:bg-red-700 text-white p-4 rounded-lg font-medium transition-colors">
                        <svg class="w-6 h-6 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path>
                        </svg>
                        Registrar Saída
                    </button>
                <?php endif; ?>

            </div>
        </div>

        <!-- Histórico recente -->
        <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">Últimos Registros</h3>
            </div>
            
            <?php if (empty($recentRecords)): ?>
                <div class="p-6 text-center">
                    <p class="text-gray-500">Nenhum registro encontrado</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">Data</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>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($recentRecords as $record): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                        <?= date('d/m/Y', strtotime($record['work_date'])) ?>
                                    </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>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Modal de ação -->
<div id="actionModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-lg shadow-xl max-w-md w-full">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 id="modalTitle" class="text-lg font-medium text-gray-900"></h3>
            </div>
            
            <form id="actionForm" method="POST">
                <div class="px-6 py-4">
                    <input type="hidden" name="employee_id" value="<?= $employee['id'] ?>">
                    <input type="hidden" name="redirect_url" value="<?= BASE_URL ?>/time-records/clock/<?= $employee['id'] ?>">
                    
                    <div class="mb-4">
                        <label for="notes" class="block text-sm font-medium text-gray-700 mb-2">Observações (opcional)</label>
                        <textarea id="notes" 
                                  name="notes" 
                                  rows="3" 
                                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                  placeholder="Digite observações sobre este registro..."></textarea>
                    </div>
                    
                    <div class="text-sm text-gray-500 mb-4">
                        <strong>Horário atual:</strong> <span id="modalCurrentTime"><?= date('H:i:s') ?></span>
                    </div>
                </div>
                
                <div class="px-6 py-4 bg-gray-50 flex justify-end space-x-3">
                    <button type="button" 
                            onclick="closeActionModal()" 
                            class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50">
                        Cancelar
                    </button>
                    <button type="submit" 
                            id="confirmButton"
                            class="px-4 py-2 text-sm font-medium text-white bg-blue-600 border border-transparent rounded-lg hover:bg-blue-700">
                        Confirmar
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
let currentAction = null;

const actionConfig = {
    'clock-in': {
        title: 'Registrar Entrada',
        action: '<?= BASE_URL ?>/time-records/clock-in',
        buttonText: 'Registrar Entrada',
        buttonClass: 'bg-green-600 hover:bg-green-700'
    },
    'clock-out': {
        title: 'Registrar Saída',
        action: '<?= BASE_URL ?>/time-records/clock-out',
        buttonText: 'Registrar Saída',
        buttonClass: 'bg-red-600 hover:bg-red-700'
    }
};

function openActionModal(action) {
    currentAction = action;
    const config = actionConfig[action];
    
    document.getElementById('modalTitle').textContent = config.title;
    document.getElementById('actionForm').action = config.action;
    document.getElementById('confirmButton').textContent = config.buttonText;
    document.getElementById('confirmButton').className = 'px-4 py-2 text-sm font-medium text-white border border-transparent rounded-lg ' + config.buttonClass;
    document.getElementById('notes').value = '';
    
    document.getElementById('actionModal').classList.remove('hidden');
}

function closeActionModal() {
    document.getElementById('actionModal').classList.add('hidden');
    currentAction = null;
}

// Atualizar horário em tempo real
function updateTime() {
    const now = new Date();
    const timeString = now.toLocaleTimeString('pt-BR');
    
    document.getElementById('current-time').textContent = timeString;
    document.getElementById('modalCurrentTime').textContent = timeString;
}

setInterval(updateTime, 1000);

// Fechar modal ao clicar fora
document.getElementById('actionModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeActionModal();
    }
});

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

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