<?php
/**
 * Editar Usuário - Super Admin
 */
require_once __DIR__ . '/../../../includes/config.php';

if (!isSuperAdmin()) {
    header('Location: /pages/login.php');
    exit;
}

$superAdmin = getSuperAdmin();
$pdo = getDB();

$userId = $_GET['id'] ?? null;

if (empty($userId)) {
    $_SESSION['flash_error'] = 'ID do usuário não informado';
    header('Location: index.php');
    exit;
}

// Buscar usuário
$stmt = $pdo->prepare("
    SELECT u.*, s.name as store_name, s.subdomain as store_subdomain
    FROM users u
    LEFT JOIN stores s ON u.store_id = s.id
    WHERE u.id = ?
");
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    $_SESSION['flash_error'] = 'Usuário não encontrado';
    header('Location: index.php');
    exit;
}

// Buscar lojas para select
$stores = $pdo->query("SELECT id, name, subdomain FROM stores ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);

// Processar formulário
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $role = $_POST['role'] ?? 'customer';
        $storeId = !empty($_POST['store_id']) ? intval($_POST['store_id']) : null;
        $isActive = isset($_POST['is_active']) ? 1 : 0;
        $newPassword = trim($_POST['new_password'] ?? '');

        if (empty($name)) {
            throw new Exception('Nome é obrigatório');
        }

        if (empty($email)) {
            throw new Exception('Email é obrigatório');
        }

        // Verificar se email já existe (exceto o próprio usuário)
        $check = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
        $check->execute([$email, $userId]);
        if ($check->fetch()) {
            throw new Exception('Já existe outro usuário com este email');
        }

        // Atualizar usuário
        if (!empty($newPassword)) {
            $passwordHash = password_hash($newPassword, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("
                UPDATE users SET
                    name = ?, email = ?, phone = ?, role = ?, store_id = ?, 
                    is_active = ?, password_hash = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$name, $email, $phone, $role, $storeId, $isActive, $passwordHash, $userId]);
        } else {
            $stmt = $pdo->prepare("
                UPDATE users SET
                    name = ?, email = ?, phone = ?, role = ?, store_id = ?, 
                    is_active = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$name, $email, $phone, $role, $storeId, $isActive, $userId]);
        }

        $_SESSION['flash_success'] = 'Usuário atualizado com sucesso!';
        header('Location: index.php');
        exit;

    } catch (Exception $e) {
        $_SESSION['flash_error'] = $e->getMessage();
    }
}

$pageTitle = 'Editar Usuário';
$currentPage = 'users';

include __DIR__ . '/../includes/header.php';
?>


<div class="app-container">
    <?php include __DIR__ . '/../includes/sidebar.php'; ?>

    <main class="main-content">
        <?php include __DIR__ . '/../includes/topbar.php'; ?>

        <div class="content-area">
            <div class="edit-container">
                <!-- Page Header -->
                <div class="page-header">
                    <div>
                        <div class="flex items-center gap-3" style="margin-bottom: 0.5rem;">
                            <a href="index.php" class="btn btn-secondary btn-sm">
                                <iconify-icon icon="solar:arrow-left-bold"></iconify-icon>
                            </a>
                            <h2 style="margin: 0;">Editar Usuário</h2>
                        </div>
                        <p>Altere as informações do usuário</p>
                    </div>
                </div>

                <form method="POST">
                    <!-- Info do Usuário -->
                    <div class="user-avatar-section">
                        <img src="https://ui-avatars.com/api/?name=<?= urlencode($user['name'] ?? 'U') ?>&background=CCA43B&color=1A1A1A&size=160" 
                             alt="Avatar" class="user-avatar">
                        <div class="user-meta">
                            <h4><?= htmlspecialchars($user['name']) ?></h4>
                            <p><?= htmlspecialchars($user['email']) ?></p>
                            <p style="margin-top: 0.5rem;">
                                <span class="text-muted">Cadastrado em:</span> 
                                <?= date('d/m/Y H:i', strtotime($user['created_at'])) ?>
                            </p>
                            <?php if ($user['store_name']): ?>
                            <p>
                                <span class="text-muted">Loja:</span> 
                                <span class="text-gold"><?= htmlspecialchars($user['store_name']) ?></span>
                                <?php if ($user['store_subdomain']): ?>
                                <span class="text-muted">(<?= $user['store_subdomain'] ?>.duolead.com.br)</span>
                                <?php endif; ?>
                            </p>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Informações Básicas -->
                    <div class="panel">
                        <div class="panel-header">
                            <div class="panel-icon blue">
                                <iconify-icon icon="solar:user-bold"></iconify-icon>
                            </div>
                            <div>
                                <h3>Informações Básicas</h3>
                                <span class="panel-subtitle">Dados pessoais do usuário</span>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label">
                                    <iconify-icon icon="solar:user-bold"></iconify-icon>
                                    Nome Completo *
                                </label>
                                <input type="text" name="name" class="form-input" required
                                       value="<?= htmlspecialchars($user['name'] ?? '') ?>">
                            </div>
                            <div class="form-group">
                                <label class="form-label">
                                    <iconify-icon icon="solar:letter-bold"></iconify-icon>
                                    Email *
                                </label>
                                <input type="email" name="email" class="form-input" required
                                       value="<?= htmlspecialchars($user['email'] ?? '') ?>">
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label">
                                    <iconify-icon icon="solar:phone-bold"></iconify-icon>
                                    Telefone
                                </label>
                                <input type="text" name="phone" class="form-input"
                                       value="<?= htmlspecialchars($user['phone'] ?? '') ?>"
                                       placeholder="(00) 00000-0000">
                            </div>
                            <div class="form-group">
                                <label class="form-label">
                                    <iconify-icon icon="solar:shield-user-bold"></iconify-icon>
                                    Papel/Função
                                </label>
                                <select name="role" class="form-select">
                                    <option value="customer" <?= ($user['role'] ?? '') === 'customer' ? 'selected' : '' ?>>Cliente</option>
                                    <option value="employee" <?= ($user['role'] ?? '') === 'employee' ? 'selected' : '' ?>>Funcionário</option>
                                    <option value="owner" <?= ($user['role'] ?? '') === 'owner' ? 'selected' : '' ?>>Dono da Loja</option>
                                    <option value="admin" <?= ($user['role'] ?? '') === 'admin' ? 'selected' : '' ?>>Administrador</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- Loja Vinculada -->
                    <div class="panel">
                        <div class="panel-header">
                            <div class="panel-icon gold">
                                <iconify-icon icon="solar:shop-bold"></iconify-icon>
                            </div>
                            <div>
                                <h3>Loja Vinculada</h3>
                                <span class="panel-subtitle">Associar usuário a uma loja</span>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="form-label">
                                <iconify-icon icon="solar:shop-2-bold"></iconify-icon>
                                Selecionar Loja
                            </label>
                            <select name="store_id" class="form-select">
                                <option value="">Nenhuma loja (usuário independente)</option>
                                <?php foreach ($stores as $store): ?>
                                <option value="<?= $store['id'] ?>" <?= $user['store_id'] == $store['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($store['name']) ?> 
                                    <?php if ($store['subdomain']): ?>(<?= $store['subdomain'] ?>.duolead.com.br)<?php endif; ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <!-- Segurança -->
                    <div class="panel">
                        <div class="panel-header">
                            <div class="panel-icon purple">
                                <iconify-icon icon="solar:lock-bold"></iconify-icon>
                            </div>
                            <div>
                                <h3>Segurança</h3>
                                <span class="panel-subtitle">Senha e status da conta</span>
                            </div>
                        </div>

                        <div class="info-box">
                            <iconify-icon icon="solar:info-circle-bold"></iconify-icon>
                            <p>Deixe o campo de senha em branco para manter a senha atual do usuário.</p>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label">
                                    <iconify-icon icon="solar:key-bold"></iconify-icon>
                                    Nova Senha
                                </label>
                                <input type="password" name="new_password" class="form-input"
                                       placeholder="Deixe em branco para manter">
                            </div>
                            <div class="form-group">
                                <label class="form-label">
                                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                                    Status
                                </label>
                                <div class="toggle-group" style="margin-top: 0.5rem;">
                                    <label class="toggle-item">
                                        <input type="checkbox" name="is_active" <?= ($user['is_active'] ?? true) ? 'checked' : '' ?>>
                                        <span class="toggle-switch"></span>
                                        <span class="toggle-label">
                                            <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                                            Usuário Ativo
                                        </span>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Botões -->
                    <div class="btn-group">
                        <a href="index.php" class="btn btn-secondary">
                            <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
                            Cancelar
                        </a>
                        <button type="submit" class="btn btn-primary">
                            <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                            Salvar Alterações
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </main>
</div>

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