<?php
/**
 * Página de Equipe - MontaLoja SaaS
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/check-access.php';

$pdo = getDB();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

if (!$userId || !$storeId) {
    header('Location: /pages/login.php');
    exit;
}

$userStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$userStmt->execute([$userId]);
$user = $userStmt->fetch(PDO::FETCH_ASSOC);

$storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

// Processar ações
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $role = trim($_POST['role'] ?? 'barbeiro');
        
        if ($name) {
            $stmt = $pdo->prepare("INSERT INTO professionals (store_id, name, email, phone, role, is_active, created_at) VALUES (?, ?, ?, ?, ?, 1, NOW())");
            $stmt->execute([$storeId, $name, $email, $phone, $role]);
            $_SESSION['flash_message'] = 'Profissional adicionado com sucesso!';
            $_SESSION['flash_type'] = 'success';
        } else {
            $_SESSION['flash_message'] = 'O nome do profissional é obrigatório.';
            $_SESSION['flash_type'] = 'error';
        }
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    } elseif ($action === 'delete' && isset($_POST['id'])) {
        $stmt = $pdo->prepare("DELETE FROM professionals WHERE id = ? AND store_id = ?");
        $stmt->execute([$_POST['id'], $storeId]);
        $_SESSION['flash_message'] = 'Profissional removido com sucesso!';
        $_SESSION['flash_type'] = 'success';
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    } elseif ($action === 'toggle' && isset($_POST['id'])) {
        $stmt = $pdo->prepare("UPDATE professionals SET is_active = NOT is_active WHERE id = ? AND store_id = ?");
        $stmt->execute([$_POST['id'], $storeId]);
        $_SESSION['flash_message'] = 'Status do profissional atualizado!';
        $_SESSION['flash_type'] = 'success';
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
}

// Verificar mensagens flash
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    $messageType = $_SESSION['flash_type'] ?? 'success';
    unset($_SESSION['flash_message'], $_SESSION['flash_type']);
}

// Buscar profissionais
$profStmt = $pdo->prepare("SELECT * FROM professionals WHERE store_id = ? ORDER BY name ASC");
$profStmt->execute([$storeId]);
$professionals = $profStmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Equipe';
include __DIR__ . '/../includes/dashboard-header.php';
?>

    <main class="main-content">
        <div class="page-header" style="display: flex; justify-content: space-between; align-items: center;">
            <div>
                <h1><iconify-icon icon="solar:users-group-rounded-bold"></iconify-icon> Equipe</h1>
                <p>Gerencie os profissionais da sua barbearia</p>
            </div>
            <button class="btn btn-primary" onclick="document.getElementById('addModal').style.display='flex'">
                <iconify-icon icon="solar:user-plus-bold"></iconify-icon>
                Novo Profissional
            </button>
        </div>
        
        <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?>">
            <iconify-icon icon="<?php echo $messageType === 'success' ? 'solar:check-circle-bold' : 'solar:danger-circle-bold'; ?>"></iconify-icon>
            <?php echo $message; ?>
        </div>
        <?php endif; ?>
        
        <?php if (empty($professionals)): ?>
        <div class="empty-state">
            <iconify-icon icon="solar:users-group-rounded-bold"></iconify-icon>
            <h3>Nenhum profissional cadastrado</h3>
            <p>Adicione os barbeiros e profissionais da sua equipe.</p>
            <button class="btn btn-primary" onclick="document.getElementById('addModal').style.display='flex'" style="margin-top: 1rem;">
                <iconify-icon icon="solar:user-plus-bold"></iconify-icon>
                Adicionar Profissional
            </button>
        </div>
        <?php else: ?>
        <div class="grid grid-3">
            <?php foreach ($professionals as $prof): ?>
            <div class="card">
                <div style="display: flex; align-items: center; gap: 1rem; margin-bottom: 1rem;">
                    <div style="width: 60px; height: 60px; border-radius: 50%; background: var(--primary); display: flex; align-items: center; justify-content: center; font-size: 1.5rem; color: white; font-weight: bold;">
                        <?php echo strtoupper(substr($prof['name'], 0, 1)); ?>
                    </div>
                    <div>
                        <h3 style="font-size: 1.1rem; margin-bottom: 0.25rem;"><?php echo htmlspecialchars($prof['name']); ?></h3>
                        <span class="badge <?php echo $prof['is_active'] ? 'badge-success' : 'badge-error'; ?>">
                            <?php echo $prof['is_active'] ? 'Ativo' : 'Inativo'; ?>
                        </span>
                    </div>
                </div>
                
                <div style="color: var(--text-muted); font-size: 0.9rem; margin-bottom: 1rem;">
                    <div style="display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem;">
                        <iconify-icon icon="solar:briefcase-bold" style="color: var(--primary);"></iconify-icon>
                        <?php echo htmlspecialchars(ucfirst($prof['role'] ?? 'Barbeiro')); ?>
                    </div>
                    <?php if (!empty($prof['email'])): ?>
                    <div style="display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem;">
                        <iconify-icon icon="solar:letter-bold" style="color: var(--primary);"></iconify-icon>
                        <?php echo htmlspecialchars($prof['email']); ?>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($prof['phone'])): ?>
                    <div style="display: flex; align-items: center; gap: 0.5rem;">
                        <iconify-icon icon="solar:phone-bold" style="color: var(--primary);"></iconify-icon>
                        <?php echo htmlspecialchars($prof['phone']); ?>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div style="display: flex; gap: 0.5rem; border-top: 1px solid var(--border-color); padding-top: 1rem;">
                    <form method="POST" style="flex: 1;">
                        <input type="hidden" name="action" value="toggle">
                        <input type="hidden" name="id" value="<?php echo $prof['id']; ?>">
                        <button type="submit" class="btn btn-secondary btn-sm" style="width: 100%;">
                            <iconify-icon icon="<?php echo $prof['is_active'] ? 'solar:eye-closed-bold' : 'solar:eye-bold'; ?>"></iconify-icon>
                            <?php echo $prof['is_active'] ? 'Desativar' : 'Ativar'; ?>
                        </button>
                    </form>
                    <form method="POST" style="flex: 1;" onsubmit="return confirm('Tem certeza que deseja excluir este profissional?');">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?php echo $prof['id']; ?>">
                        <button type="submit" class="btn btn-secondary btn-sm" style="width: 100%; color: var(--error);">
                            <iconify-icon icon="solar:trash-bin-2-bold"></iconify-icon>
                            Excluir
                        </button>
                    </form>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </main>
    
    <!-- Modal Adicionar -->
    <div id="addModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); z-index: 1000; align-items: center; justify-content: center;">
        <div class="card" style="width: 100%; max-width: 500px; margin: 2rem;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                <h2 style="font-size: 1.25rem;">Novo Profissional</h2>
                <button onclick="document.getElementById('addModal').style.display='none'" style="background: none; border: none; color: var(--text-muted); cursor: pointer; font-size: 1.5rem;">
                    <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
                </button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="add">
                <div class="form-group">
                    <label class="form-label">Nome Completo *</label>
                    <input type="text" name="name" class="form-input" placeholder="Nome do profissional" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Função</label>
                    <select name="role" class="form-input">
                        <option value="barbeiro">Barbeiro</option>
                        <option value="cabeleireiro">Cabeleireiro</option>
                        <option value="esteticista">Esteticista</option>
                        <option value="recepcionista">Recepcionista</option>
                        <option value="gerente">Gerente</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">E-mail</label>
                    <input type="email" name="email" class="form-input" placeholder="email@exemplo.com">
                </div>
                <div class="form-group">
                    <label class="form-label">Telefone</label>
                    <input type="tel" name="phone" class="form-input" placeholder="(11) 99999-9999">
                </div>
                <div style="display: flex; gap: 1rem; justify-content: flex-end;">
                    <button type="button" class="btn btn-secondary" onclick="document.getElementById('addModal').style.display='none'">Cancelar</button>
                    <button type="submit" class="btn btn-primary">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                        Salvar
                    </button>
                </div>
            </form>
        </div>
    </div>

<?php include __DIR__ . '/../includes/dashboard-footer.php'; ?>
