<?php
session_start();
include('includes/db.php');

// Verificar se o usuário está logado
if (!isset($_SESSION['usuario_id'])) {
    header('Location: login.php');
    exit;
}

// Buscar configurações atuais
$config = $pdo->query("SELECT * FROM configuracoes LIMIT 1")->fetch(PDO::FETCH_ASSOC);

// Buscar usuário logado
$stmt = $pdo->prepare("SELECT * FROM usuarios WHERE id = ?");
$stmt->execute([$_SESSION['usuario_id']]);
$usuarioLogado = $stmt->fetch(PDO::FETCH_ASSOC);

$mensagem = '';

// Atualizar configurações
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $titulo = $_POST['titulo'] ?? $config['titulo'];
    $usuario = $_POST['usuario'] ?? $config['usuario'];
    $senha_antiga = $_POST['senha_antiga'] ?? '';
    $nova_senha = $_POST['senha_nova'] ?? '';

    $senha_valida = password_verify($senha_antiga, $config['senha']);
    $senha_final = $config['senha'];

    $logo = $config['logo'];
    if (!empty($_FILES['logo']['name'])) {
        $ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
        $nomeLogo = 'logo_' . time() . '.' . $ext;
        move_uploaded_file($_FILES['logo']['tmp_name'], 'uploads/' . $nomeLogo);
        $logo = $nomeLogo;
    }

    if (!empty($nova_senha)) {
        if ($senha_valida) {
            $senha_final = password_hash($nova_senha, PASSWORD_DEFAULT);
        } else {
            $mensagem = '<div class="bg-red-100 text-red-700 p-2 rounded">❌ Senha atual incorreta!</div>';
        }
    }

    if (empty($mensagem)) {
        $stmt = $pdo->prepare("UPDATE configuracoes SET titulo=?, logo=?, usuario=?, senha=? WHERE id=?");
        $stmt->execute([$titulo, $logo, $usuario, $senha_final, $config['id']]);
        $mensagem = '<div class="bg-green-100 text-green-800 p-2 rounded">✅ Configurações atualizadas com sucesso!</div>';
        $config['titulo'] = $titulo;
        $config['logo'] = $logo;
        $config['usuario'] = $usuario;
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br" class="dark">
<head>
  <meta charset="UTF-8">
  <title>Configurações - <?= htmlspecialchars($config['titulo']) ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <script src="https://cdn.tailwindcss.com"></script>
  <script>tailwind.config = { darkMode: 'class' }</script>
  <script src="https://unpkg.com/@phosphor-icons/web"></script>
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-800 dark:text-gray-100">

<div class="flex min-h-screen">
  <!-- MENU LATERAL -->
  <aside id="sidebar" class="fixed top-0 left-0 w-64 h-full bg-white dark:bg-gray-800 shadow-md z-50 transform -translate-x-full transition-transform duration-300 md:static md:translate-x-0">
    <div class="p-6 text-2xl font-bold text-blue-600 dark:text-white">
      Sistema <?= htmlspecialchars($config['titulo']) ?>
    </div>
    <nav class="space-y-2 px-4 text-sm">
      <a href="dashboard.php" class="flex items-center gap-3 p-2 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700">
        <i class="ph ph-gauge"></i> Dashboard
      </a>
      <a href="clientes.php" class="flex items-center gap-3 p-2 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700">
        <i class="ph ph-users"></i> Clientes
      </a>
      <a href="configuracoes.php" class="flex items-center gap-3 p-2 rounded-md bg-blue-100 dark:bg-blue-800 text-blue-600 dark:text-white font-medium">
        <i class="ph ph-gear"></i> Configurações
      </a>
      <a href="logout.php" class="flex items-center gap-3 p-2 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 text-red-600 dark:text-red-400 font-medium">
  <i class="ph ph-sign-out"></i> Sair
</a>

    </nav>
  </aside>

  <!-- CONTEÚDO PRINCIPAL -->
  <main class="flex-1 p-6 transition-all duration-300 md:ml-64">
    <!-- TOPO -->
    <div class="flex justify-between items-center mb-6">
  <h1 class="text-xl font-bold">Configurações</h1>
  <div class="flex items-center gap-3">
    <button onclick="toggleSidebar()" class="w-10 h-10 rounded-md bg-blue-600 text-white flex items-center justify-center md:hidden">
      <i class="ph ph-list text-xl"></i>
    </button>
    <button id="toggleTheme" class="w-10 h-10 rounded-full bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 flex items-center justify-center">
      <i id="themeIcon" class="ph ph-sun text-yellow-500 dark:text-yellow-300 text-xl"></i>
    </button>
    <img src="uploads/<?= $config['logo'] ?>" class="w-9 h-9 rounded-full object-cover" alt="Logo">
  </div>
</div>


    <?= $mensagem ?>

    <form method="POST" enctype="multipart/form-data" class="max-w-xl space-y-6">
      <div>
        <label class="block mb-1 text-sm font-medium">Título do Sistema</label>
        <input type="text" name="titulo" value="<?= htmlspecialchars($config['titulo']) ?>" class="w-full rounded px-3 py-2 border dark:bg-gray-800 dark:border-gray-700">
      </div>

      <div>
        <label class="block mb-1 text-sm font-medium">Logo Atual</label><br>
        <?php if ($config['logo']): ?>
          <img src="uploads/<?= $config['logo'] ?>" alt="Logo" class="h-16 mb-2">
        <?php endif; ?>
        <input type="file" name="logo" class="text-sm">
      </div>

      <div>
        <label class="block mb-1 text-sm font-medium">Usuário</label>
        <input type="text" name="usuario" value="<?= htmlspecialchars($config['usuario']) ?>" class="w-full rounded px-3 py-2 border dark:bg-gray-800 dark:border-gray-700">
      </div>

      <div>
        <label class="block mb-1 text-sm font-medium">Senha Atual</label>
        <input type="password" name="senha_antiga" class="w-full rounded px-3 py-2 border dark:bg-gray-800 dark:border-gray-700">
      </div>

      <div>
        <label class="block mb-1 text-sm font-medium">Nova Senha</label>
        <input type="password" name="senha_nova" class="w-full rounded px-3 py-2 border dark:bg-gray-800 dark:border-gray-700">
      </div>

      <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded">
        Salvar Configurações
      </button>
    </form>
  </main>
</div>

<script>
  // Tema escuro/claro
  const html = document.documentElement;
  const toggleBtn = document.getElementById('toggleTheme');
  const icon = document.getElementById('themeIcon');

  if (localStorage.getItem('modo') === 'light') {
    html.classList.remove('dark');
  } else {
    html.classList.add('dark');
  }

  toggleBtn.addEventListener('click', () => {
    html.classList.toggle('dark');
    const modo = html.classList.contains('dark') ? 'dark' : 'light';
    localStorage.setItem('modo', modo);
    icon.classList.toggle('text-yellow-500');
    icon.classList.toggle('text-yellow-300');
  });

  function toggleSidebar() {
    document.getElementById('sidebar').classList.toggle('hidden');
  }
</script>
<script>
  function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    sidebar.classList.toggle('-translate-x-full');
  }
</script>

</body>
</html>
