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

$jsonFile = './img/api.json';
$uploadDir = './img/';
$bannerGroups = [
    'ads' => ['ads', 'ads2', 'ads3'],
    'bads' => ['bads', 'bads2', 'bads3'],
    'cads' => ['cads', 'cads2', 'cads3']
];
$bannerNames = array_merge(...array_values($bannerGroups));
$maxFileSize = 5 * 1024 * 1024;

function carregarDadosJson() {
    global $jsonFile;
    if (!file_exists($jsonFile)) {
        file_put_contents($jsonFile, json_encode(['data' => []]));
    }
    return json_decode(file_get_contents($jsonFile), true);
}

function atualizarJsonBanner($bannerKey, $novoNomeBanner) {
    global $jsonFile;
    $data = carregarDadosJson();
    if (!isset($data['data'][0])) {
        $data['data'][0] = [];
    }
    $data['data'][0][$bannerKey] = $novoNomeBanner;
    return file_put_contents($jsonFile, json_encode($data, JSON_PRETTY_PRINT));
}

function processarUpload($bannerKey, $file) {
    global $uploadDir, $maxFileSize;

    if ($file['error'] !== UPLOAD_ERR_OK) {
        return ['error' => "Erro no upload: " . $file['error']];
    }

    if ($file['size'] > $maxFileSize) {
        return ['error' => "Arquivo muito grande. Máximo: " . formatBytes($maxFileSize)];
    }

    $novoNomeBanner = $bannerKey . ".png";
    $fileTmpPath = $file['tmp_name'];

    if (!getimagesize($fileTmpPath)) {
        return ['error' => "Arquivo não é uma imagem válida"];
    }

    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $allowed = ['png', 'jpg', 'jpeg', 'gif'];
    if (!in_array($ext, $allowed)) {
        return ['error' => "Formato não suportado. Use: " . implode(', ', $allowed)];
    }

    switch ($ext) {
        case 'png': $image = imagecreatefrompng($fileTmpPath); break;
        case 'jpg':
        case 'jpeg': $image = imagecreatefromjpeg($fileTmpPath); break;
        case 'gif': $image = imagecreatefromgif($fileTmpPath); break;
        default: return ['error' => "Formato inválido"];
    }

    if (!$image) return ['error' => "Erro ao processar imagem"];

    if (!imagepng($image, $uploadDir . $novoNomeBanner)) {
        imagedestroy($image);
        return ['error' => "Erro ao salvar a imagem"];
    }

    imagedestroy($image);

    if (!atualizarJsonBanner($bannerKey, $novoNomeBanner)) {
        return ['error' => "Erro ao atualizar JSON"];
    }

    return ['success' => "Banner atualizado com sucesso!"];
}

function excluirBanner($bannerKey) {
    global $uploadDir, $jsonFile;
    $dados = carregarDadosJson();
    $arquivo = $dados['data'][0][$bannerKey] ?? null;

    if ($arquivo && file_exists($uploadDir . $arquivo)) {
        unlink($uploadDir . $arquivo);
    }

    unset($dados['data'][0][$bannerKey]);
    file_put_contents($jsonFile, json_encode($dados, JSON_PRETTY_PRINT));
    return ['success' => "Banner excluído com sucesso!"];
}

function formatBytes($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes, 1024) : 0));
    $pow = min($pow, count($units) - 1);
    $bytes /= (1 << (10 * $pow));
    return round($bytes, $precision) . ' ' . $units[$pow];
}

$mensagens = [];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    foreach ($bannerNames as $bannerKey) {
        if (isset($_POST['delete_' . $bannerKey])) {
            $mensagens[$bannerKey] = excluirBanner($bannerKey);
        }
    }
    foreach ($bannerNames as $bannerKey) {
        if (isset($_FILES[$bannerKey]) && $_FILES[$bannerKey]['size'] > 0) {
            $result = processarUpload($bannerKey, $_FILES[$bannerKey]);
            $mensagens[$bannerKey] = $result;
        }
    }

    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

$dados = carregarDadosJson();
$bannersAtuais = [];
foreach ($bannerNames as $bannerKey) {
    $bannersAtuais[$bannerKey] = $dados['data'][0][$bannerKey] ?? null;
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Gerenciador de Banners</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
    <script src="https://kit.fontawesome.com/3794d2f89f.js" crossorigin="anonymous"></script>
    <style>
        :root {
            --bg: #121829;
            --text: #fff;
            --accent: #4a5fc1;
            --error: #dc3545;
            --success: #28a745;
            --card: rgba(26,33,60,0.9);
            --border: #2a3250;
        }
        body {
            background: var(--bg);
            color: var(--text);
            font-family: 'Inter', sans-serif;
            margin: 0;
            padding: 2rem;
        }
        .card {
            max-width: 1000px;
            margin: auto;
            background: var(--card);
            padding: 2rem;
            border-radius: 10px;
            border: 1px solid var(--border);
        }
        h1 {
            text-align: center;
            margin-bottom: 2rem;
            font-size: 1.8rem;
        }
        h3 {
            color: var(--accent);
            margin-top: 2rem;
            text-transform: uppercase;
        }
        .banners-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 1.5rem;
            margin-top: 1rem;
        }
        .banner-card {
            background: rgba(0,0,0,0.2);
            padding: 1rem;
            border-radius: 8px;
            border: 1px solid var(--border);
        }
        .banner-header {
            font-weight: bold;
            margin-bottom: 0.5rem;
            color: var(--accent);
        }
        .banner-preview {
            height: 120px;
            background: #0003;
            border-radius: 6px;
            border: 1px dashed var(--border);
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            margin-bottom: 0.8rem;
        }
        .banner-preview img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
        .no-banner {
            font-size: 0.8rem;
            opacity: 0.6;
        }
        .file-input-wrapper {
            margin-bottom: 0.5rem;
        }
        .file-input-button {
            display: block;
            background: #2a325066;
            padding: 8px;
            border: 1px dashed var(--border);
            color: #fff;
            text-align: center;
            border-radius: 6px;
            cursor: pointer;
        }
        .file-input-wrapper input[type="file"] {
            display: none;
        }
        .submit-btn {
            width: 100%;
            padding: 0.6rem;
            border: none;
            border-radius: 6px;
            color: #fff;
            background-color: var(--accent);
            cursor: pointer;
            font-size: 0.85rem;
            margin-bottom: 6px;
        }
        .delete-btn {
            background-color: var(--error);
        }
        .alert {
            padding: 0.6rem;
            margin-top: 0.6rem;
            border-left: 3px solid;
            font-size: 0.8rem;
        }
        .alert-success {
            border-color: var(--success);
            background: rgba(40, 167, 69, 0.1);
            color: var(--success);
        }
        .alert-error {
            border-color: var(--error);
            background: rgba(220, 53, 69, 0.1);
            color: var(--error);
        }
    </style>
</head>
<body>

<div class="card">
    <h1>Gerenciador de Banners</h1>

    <?php
    $titulosPersonalizados = [
        'ads' => '800x600',
        'bads' => '800x300',
        'cads' => '800x300'
    ];
    ?>

    <form method="POST" enctype="multipart/form-data">
        <?php foreach ($bannerGroups as $grupo => $banners): ?>
            <h3><?= $titulosPersonalizados[$grupo] ?? strtoupper($grupo) ?></h3>
            <div class="banners-grid">
                <?php foreach ($banners as $bannerKey): ?>
                    <div class="banner-card">
                        <div class="banner-header"><?= strtoupper($bannerKey) ?></div>
                        <div class="banner-preview">
                            <?php if ($bannersAtuais[$bannerKey] && file_exists($uploadDir . $bannersAtuais[$bannerKey])): ?>
                                <img src="<?= $uploadDir . $bannersAtuais[$bannerKey] ?>?<?= time() ?>" alt="<?= $bannerKey ?>">
                            <?php else: ?>
                                <span class="no-banner">Nenhum banner</span>
                            <?php endif; ?>
                        </div>
                        <label class="file-input-wrapper">
                            <span class="file-input-button"><i class="fas fa-cloud-upload-alt"></i> Selecione imagem</span>
                            <input type="file" name="<?= $bannerKey ?>" onchange="this.form.submit()">
                        </label>
                        <button type="submit" class="submit-btn delete-btn" name="delete_<?= $bannerKey ?>" value="1">Excluir</button>
                        <?php if (isset($mensagens[$bannerKey])): ?>
                            <div class="alert alert-<?= isset($mensagens[$bannerKey]['success']) ? 'success' : 'error' ?>">
                                <?= $mensagens[$bannerKey]['success'] ?? $mensagens[$bannerKey]['error'] ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endforeach; ?>
    </form>
</div>

</body>
</html>
