<?php
session_start();

// Verifica se o utilizador está autenticado
if (!isset($_SESSION['user']) || $_SESSION['user'] !== 'admin') {
    header('Location: login.php');
    exit;
}

$dataFile = __DIR__ . '/data.json';
$data = json_decode(file_get_contents($dataFile), true);
if (!$data) {
    $data = [];
}

// Processa formulário quando enviado via POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Higieniza e actualiza dados gerais
    $data['siteName'] = $_POST['siteName'] ?? $data['siteName'];
    $data['logoText'] = $_POST['logoText'] ?? $data['logoText'];
    $data['tagline'] = $_POST['tagline'] ?? '';
    $data['accentColor'] = $_POST['accentColor'] ?? $data['accentColor'];
    $data['heroTitle'] = $_POST['heroTitle'] ?? $data['heroTitle'];
    $data['heroSubtitle'] = $_POST['heroSubtitle'] ?? '';
    $data['aboutTitle'] = $_POST['aboutTitle'] ?? $data['aboutTitle'];
    $data['aboutText'] = $_POST['aboutText'] ?? $data['aboutText'];
    // Actualiza serviços
    $titles = $_POST['serviceTitles'] ?? [];
    $descs = $_POST['serviceDescriptions'] ?? [];
    $services = [];
    if (is_array($titles)) {
        foreach ($titles as $i => $title) {
            $title = trim($title);
            $desc = isset($descs[$i]) ? trim($descs[$i]) : '';
            if ($title && $desc) {
                $services[] = ['title' => $title, 'description' => $desc];
            }
        }
    }
    $data['services'] = $services;
    // Actualiza contactos
    if (!isset($data['contact']) || !is_array($data['contact'])) {
        $data['contact'] = [];
    }
    $data['contact']['phone'] = $_POST['contactPhone'] ?? '';
    $data['contact']['email'] = $_POST['contactEmail'] ?? '';
    $data['contact']['address'] = $_POST['contactAddress'] ?? '';
    // Grava as alterações no ficheiro JSON
    file_put_contents($dataFile, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    // Redirecciona após guardar para evitar repost
    header('Location: admin.php');
    exit;
}

$accent = $data['accentColor'] ?? '#E94298';
?>
<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - <?php echo htmlspecialchars($data['siteName'] ?? 'Site'); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="css/styles.css">
    <style>:root{--accent: <?php echo htmlspecialchars($accent); ?>;}</style>
    <style>
        body {
            background:#f9f9f9;
            font-family:'Montserrat', sans-serif;
            margin:0;
        }
        .admin-container {
            max-width:1000px;
            margin:30px auto;
            padding:20px;
            background:#fff;
            border-radius:10px;
            box-shadow:0 2px 8px rgba(0,0,0,0.1);
        }
        h1 {
            text-align:center;
            color:var(--accent);
            margin-top:0;
        }
        form .section {
            margin-bottom:30px;
        }
        form .section h3 {
            margin:0 0 15px;
            color:var(--accent);
            font-size:1.4rem;
        }
        form label {
            display:block;
            font-weight:600;
            margin-bottom:5px;
        }
        form input[type="text"], form input[type="color"], form input[type="email"], form textarea {
            width:100%;
            padding:10px;
            border:1px solid #ddd;
            border-radius:5px;
            margin-bottom:15px;
            box-sizing:border-box;
            font-size:0.95rem;
        }
        .services-group {
            border:1px solid #ddd;
            padding:15px;
            border-radius:5px;
            margin-bottom:15px;
        }
        .services-group h4 {
            margin-top:0;
            color:var(--accent);
            font-size:1.1rem;
        }
        .add-service {
            background:var(--accent);
            color:#fff;
            padding:10px 15px;
            border:none;
            border-radius:5px;
            cursor:pointer;
            font-weight:600;
        }
        .save-btn {
            background:var(--accent);
            color:#fff;
            padding:15px 25px;
            border:none;
            border-radius:5px;
            cursor:pointer;
            font-weight:600;
            font-size:1rem;
            margin-top:10px;
        }
        .logout-link {
            display:inline-block;
            margin-top:10px;
            text-decoration:none;
            color:var(--accent);
            font-weight:600;
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <h1>Painel de Administração</h1>
        <form method="POST" action="admin.php">
            <div class="section">
                <h3>Informações Gerais</h3>
                <label>Nome do Site</label>
                <input type="text" name="siteName" value="<?php echo htmlspecialchars($data['siteName'] ?? ''); ?>" required>
                <label>Texto do Logotipo</label>
                <input type="text" name="logoText" value="<?php echo htmlspecialchars($data['logoText'] ?? ''); ?>" required>
                <label>Tagline</label>
                <input type="text" name="tagline" value="<?php echo htmlspecialchars($data['tagline'] ?? ''); ?>">
                <label>Cor Principal</label>
                <input type="color" name="accentColor" value="<?php echo htmlspecialchars($data['accentColor'] ?? '#E94298'); ?>">
            </div>
            <div class="section">
                <h3>Secção Hero</h3>
                <label>Título Principal</label>
                <input type="text" name="heroTitle" value="<?php echo htmlspecialchars($data['heroTitle'] ?? ''); ?>" required>
                <label>Subtítulo</label>
                <input type="text" name="heroSubtitle" value="<?php echo htmlspecialchars($data['heroSubtitle'] ?? ''); ?>">
            </div>
            <div class="section">
                <h3>Quem Somos</h3>
                <label>Título</label>
                <input type="text" name="aboutTitle" value="<?php echo htmlspecialchars($data['aboutTitle'] ?? 'Quem Somos'); ?>" required>
                <label>Texto</label>
                <textarea name="aboutText" rows="5" required><?php echo htmlspecialchars($data['aboutText'] ?? ''); ?></textarea>
            </div>
            <div class="section">
                <h3>Serviços</h3>
                <div id="services-container">
                    <?php if (!empty($data['services']) && is_array($data['services'])): ?>
                        <?php foreach ($data['services'] as $index => $service): ?>
                            <div class="services-group">
                                <h4>Serviço <span class="service-number"><?php echo $index + 1; ?></span></h4>
                                <label>Título</label>
                                <input type="text" name="serviceTitles[]" value="<?php echo htmlspecialchars($service['title']); ?>" required>
                                <label>Descrição</label>
                                <textarea name="serviceDescriptions[]" rows="3" required><?php echo htmlspecialchars($service['description']); ?></textarea>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                <button type="button" class="add-service" onclick="addService()">Adicionar Serviço</button>
            </div>
            <div class="section">
                <h3>Contactos</h3>
                <label>Telefone</label>
                <input type="text" name="contactPhone" value="<?php echo htmlspecialchars($data['contact']['phone'] ?? ''); ?>">
                <label>Email</label>
                <input type="email" name="contactEmail" value="<?php echo htmlspecialchars($data['contact']['email'] ?? ''); ?>">
                <label>Endereço</label>
                <textarea name="contactAddress" rows="2"><?php echo htmlspecialchars($data['contact']['address'] ?? ''); ?></textarea>
            </div>
            <button type="submit" class="save-btn">Guardar Alterações</button>
        </form>
        <a href="logout.php" class="logout-link">Sair</a>
    </div>
    <script>
        function addService() {
            const container = document.getElementById('services-container');
            const count = container.children.length + 1;
            const div = document.createElement('div');
            div.className = 'services-group';
            div.innerHTML = '<h4>Serviço <span class="service-number">' + count + '</span></h4>' +
                '<label>Título</label>' +
                '<input type="text" name="serviceTitles[]" required>' +
                '<label>Descrição</label>' +
                '<textarea name="serviceDescriptions[]" rows="3" required></textarea>';
            container.appendChild(div);
        }
    </script>
</body>
</html>