<?php
session_start();
if (!isset($_SESSION['admin_logado']) || $_SESSION['admin_logado'] !== true) {
    header("Location: login.php?admin=1");
    exit();
}

$config_file = __DIR__ . '/config.json';
$config = file_exists($config_file) ? json_decode(file_get_contents($config_file), true) : [];

$action = $_POST['action'] ?? '';

if ($action === 'upload_logo') {
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['logo'];
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        if (strtolower($ext) === 'png') {
            move_uploaded_file($file['tmp_name'], __DIR__ . '/img/logo.png');
            $_SESSION['admin_message'] = 'Logo atualizada com sucesso!';
            $_SESSION['admin_message_type'] = 'success';
        } else {
            $_SESSION['admin_message'] = 'Apenas arquivos PNG são permitidos!';
            $_SESSION['admin_message_type'] = 'error';
        }
    } else {
        $_SESSION['admin_message'] = 'Erro ao fazer upload da logo!';
        $_SESSION['admin_message_type'] = 'error';
    }
}

if ($action === 'save_colors') {
    $config['login_border_color'] = $_POST['login_border_color'] ?? $config['login_border_color'] ?? '#39FF14';
    $config['main_border_color'] = $_POST['main_border_color'] ?? $config['main_border_color'] ?? '#07a802';
    $config['admin_border_color'] = $_POST['admin_border_color'] ?? $config['admin_border_color'] ?? '#FFD700';
    $config['banner_border_color'] = $_POST['banner_border_color'] ?? $config['banner_border_color'] ?? '#07a802';
    file_put_contents($config_file, json_encode($config, JSON_PRETTY_PRINT));
    $_SESSION['admin_message'] = 'Cores atualizadas com sucesso!';
    $_SESSION['admin_message_type'] = 'success';
}

if ($action === 'save_users') {
    $config['main_user'] = $_POST['main_user'] ?? $config['main_user'] ?? 'admin';
    $config['main_password'] = $_POST['main_password'] ?? $config['main_password'] ?? '102030';
    $config['admin_user'] = $_POST['admin_user'] ?? $config['admin_user'] ?? 'admin_panel';
    $config['admin_password'] = $_POST['admin_password'] ?? $config['admin_password'] ?? 'admin123';
    file_put_contents($config_file, json_encode($config, JSON_PRETTY_PRINT));
    $_SESSION['admin_message'] = 'Usuários e senhas atualizados com sucesso!';
    $_SESSION['admin_message_type'] = 'success';
}

if ($action === 'save_watermark') {
    $config['watermark_text'] = $_POST['watermark_text'] ?? $config['watermark_text'] ?? 'TéchPlay-shop';
    file_put_contents($config_file, json_encode($config, JSON_PRETTY_PRINT));
    $_SESSION['admin_message'] = 'Marca d\'água atualizada com sucesso!';
    $_SESSION['admin_message_type'] = 'success';
}

header("Location: admin.php");
exit();