<?php
session_start();
if (!isset($_SESSION['id'])) { header("Location: login.php"); exit(); }

include "includes/header.php";

$folderPath = './img/animation/';
if (!is_dir($folderPath)) mkdir($folderPath, 0777, true);

$jsonImg = $folderPath . 'wall_info.json';
$jsonFx = $folderPath . 'wall_fx.json';

if (!file_exists($jsonImg)) file_put_contents($jsonImg, json_encode([["ImageName" => "linear-gradient(180deg, rgb(15, 23, 42) 0%, rgb(2, 6, 23) 100%)", "Upload_type" => "by_color"]]));
// Inicializa o JSON de efeitos com os novos botões inclusos
if (!file_exists($jsonFx)) file_put_contents($jsonFx, json_encode(["snow" => "0", "fire" => "0", "rain" => "0", "carnaval" => "0", "pascoa" => "0", "halloween" => "0"]));

if (isset($_POST['ajax_fx'])) {
    $currentFx = json_decode(file_get_contents($jsonFx), true);
    $currentFx[$_POST['effect_type']] = $_POST['status'];
    file_put_contents($jsonFx, json_encode($currentFx));
    exit;
}

$imgData = json_decode(file_get_contents($jsonImg), true)[0];
$fx = json_decode(file_get_contents($jsonFx), true);
$type = $imgData['Upload_type'];
$val = $imgData['ImageName'];
$previewStyle = ($type == "by_color") ? "background: $val;" : "background-image: url(".($type == "by_file" ? substr($val, 1) : $val)."); background-size: cover;";
?>

<style>
    * { box-sizing: border-box !important; border: none !important; }
    html, body { max-width: 100%; overflow-x: hidden !important; background-color: #020617 !important; font-family: 'Inter', sans-serif; }
    
    .premium-card { background: #070e1b !important; border-radius: 20px; padding: 25px; max-width: 500px; margin: 20px auto; width: 100%; box-shadow: 0 10px 30px rgba(0,0,0,0.5); }
    .preview-box { border-radius: 16px; margin-bottom: 25px; aspect-ratio: 16/9; transition: 0.3s; background-color: #000; }
    
    .fx-row { display: flex; align-items: center; justify-content: space-between; background: #0f172a; padding: 15px; border-radius: 14px; margin-bottom: 10px; }
    
    .switch { position: relative; width: 44px; height: 22px; flex-shrink: 0; }
    .switch input { opacity: 0; width: 0; height: 0; }
    .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #1e293b; transition: .4s; border-radius: 34px; }
    .slider:before { position: absolute; content: ""; height: 16px; width: 16px; left: 4px; bottom: 3px; background-color: white; transition: .4s; border-radius: 50%; }
    input:checked + .slider { background-color: #ffaa00; }
    input:checked + .slider:before { transform: translateX(20px); }

    .tab-container { display: grid; grid-template-columns: 1fr 1fr 1fr; background: #0f172a; border-radius: 12px; padding: 4px; margin-bottom: 20px; }
    .tab-item { padding: 10px; text-align: center; border-radius: 8px; font-size: 0.7rem; font-weight: 800; cursor: pointer; color: #64748b; text-transform: uppercase; border: none !important; }
    .tab-item.active { background: #ffaa00; color: #fff; }

    .rgb-group { background: #0f172a; border-radius: 15px; padding: 15px; margin-bottom: 15px; }
    .rgb-row { display: flex; align-items: center; gap: 15px; margin-bottom: 12px; }
    .rgb-label { color: #fff; font-weight: 800; width: 15px; font-size: 0.9rem; }
    .rgb-slider { flex-grow: 1; accent-color: #ffaa00; cursor: pointer; height: 6px; border-radius: 5px; background: #1e293b; }
    .rgb-val { color: #64748b; font-weight: 700; width: 35px; text-align: right; font-size: 0.85rem; }
    .color-indicator { width: 100%; height: 40px; border-radius: 8px; margin-bottom: 10px; }

    .dir-container { display: flex; gap: 10px; margin-bottom: 15px; }
    .dir-btn { flex: 1; background: #0f172a; color: #64748b; padding: 10px; border-radius: 10px; font-size: 0.7rem; font-weight: 800; cursor: pointer; text-align: center; border: none !important; }
    .dir-btn.active { color: #fff; background: #ffaa00; }

    .btn-premium-action { width: 100%; background: #ffaa00 !important; color: #fff !important; padding: 18px; border-radius: 15px; font-weight: 800; border: none !important; cursor: pointer; text-transform: uppercase; margin-top: 10px; }
    .my-swal-popup { border-radius: 25px !important; background: #0f172a !important; padding: 30px !important; border: none !important; }
</style>

<div class="container-fluid">
    <div class="premium-card">
        <h3 style="font-weight: 800; color:#fff; margin-bottom: 5px;">Deus da Guerra Script</h3>
        <p style="color: #64748b; font-size: 0.75rem; margin-bottom: 20px;">Background & Efeitos Premium</p>
        
        <div class="preview-box" id="live-preview" style="<?= $previewStyle ?>"></div>

        <div style="margin-bottom: 25px;">
            <?php 
            // Lista atualizada com os 3 novos efeitos solicitados
            $lista_efeitos = [
                'snow'      => 'Neve Artística', 
                'fire'      => 'Efeito Fogo', 
                'rain'      => 'Chuva Suave',
                'carnaval'  => 'Carnaval (Folia)',
                'pascoa'    => 'Páscoa (Cenouras)',
                'halloween' => 'Halloween (Terror)'
            ];
            foreach($lista_efeitos as $key => $label): ?>
            <div class="fx-row">
                <span style="font-weight: 600; color: #e2e8f0; font-size: 0.9rem;"><?= $label ?></span>
                <label class="switch">
                    <input type="checkbox" class="fx-toggle" data-effect="<?= $key ?>" <?= (isset($fx[$key]) && $fx[$key] == '1') ? 'checked' : '' ?>>
                    <span class="slider"></span>
                </label>
            </div>
            <?php endforeach; ?>
        </div>

        <div class="tab-container">
            <div class="tab-item active" id="t-file">UPLOAD</div>
            <div class="tab-item" id="t-url">LINK</div>
            <div class="tab-item" id="t-color">RGB</div>
        </div>

        <form method="post" enctype="multipart/form-data" id="f-file">
            <input style="width:100%; background:#0f172a; color:#fff; padding:12px; border-radius:12px; margin-bottom:15px;" type="file" name="img_file" accept="image/*" required>
            <button type="submit" name="do_upload" class="btn-premium-action">Salvar Imagem</button>
        </form>

        <form method="post" id="f-url" style="display:none;">
            <input style="width:100%; background:#0f172a; color:#fff; padding:12px; border-radius:12px; margin-bottom:15px;" type="text" name="img_url" placeholder="https://..." required>
            <button type="submit" name="do_url" class="btn-premium-action">Aplicar Link</button>
        </form>

        <form method="post" id="f-color" style="display:none;">
            <label style="color:#ffaa00; font-size:0.65rem; font-weight:800; margin-left:5px;">DIREÇÃO DO GRADIENT</label>
            <div class="dir-container">
                <div class="dir-btn active" data-dir="180deg">VERTICAL</div>
                <div class="dir-btn" data-dir="90deg">HORIZONTAL</div>
            </div>
            
            <label style="color:#ffaa00; font-size:0.65rem; font-weight:800; margin-left:5px;">COR 1 (INÍCIO)</label>
            <div class="rgb-group">
                <div class="color-indicator" id="ind1"></div>
                <div class="rgb-row"> <span class="rgb-label">R</span> <input type="range" class="rgb-slider s1" data-color="1" data-rgb="r" min="0" max="255" value="15"> <span class="rgb-val" id="v1r">15</span> </div>
                <div class="rgb-row"> <span class="rgb-label">G</span> <input type="range" class="rgb-slider s1" data-color="1" data-rgb="g" min="0" max="255" value="23"> <span class="rgb-val" id="v1g">23</span> </div>
                <div class="rgb-row"> <span class="rgb-label">B</span> <input type="range" class="rgb-slider s1" data-color="1" data-rgb="b" min="0" max="255" value="42"> <span class="rgb-val" id="v1b">42</span> </div>
            </div>

            <label style="color:#ffaa00; font-size:0.65rem; font-weight:800; margin-left:5px;">COR 2 (FINAL)</label>
            <div class="rgb-group">
                <div class="color-indicator" id="ind2"></div>
                <div class="rgb-row"> <span class="rgb-label">R</span> <input type="range" class="rgb-slider s2" data-color="2" data-rgb="r" min="0" max="255" value="2"> <span class="rgb-val" id="v2r">2</span> </div>
                <div class="rgb-row"> <span class="rgb-label">G</span> <input type="range" class="rgb-slider s2" data-color="2" data-rgb="g" min="0" max="255" value="6"> <span class="rgb-val" id="v2g">6</span> </div>
                <div class="rgb-row"> <span class="rgb-label">B</span> <input type="range" class="rgb-slider s2" data-color="2" data-rgb="b" min="0" max="255" value="23"> <span class="rgb-val" id="v2b">23</span> </div>
            </div>
            <input type="hidden" name="bg_gradient" id="final-grad-input">
            <button type="submit" name="do_color" class="btn-premium-action">Aplicar Gradient RGB</button>
        </form>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(document).ready(function() {
    let currentDir = "180deg";

    function updateRGB() {
        let r1 = $('[data-color="1"][data-rgb="r"]').val(); let g1 = $('[data-color="1"][data-rgb="g"]').val(); let b1 = $('[data-color="1"][data-rgb="b"]').val();
        $('#v1r').text(r1); $('#v1g').text(g1); $('#v1b').text(b1);
        let color1 = `rgb(${r1}, ${g1}, ${b1})`; $('#ind1').css('background', color1);

        let r2 = $('[data-color="2"][data-rgb="r"]').val(); let g2 = $('[data-color="2"][data-rgb="g"]').val(); let b2 = $('[data-color="2"][data-rgb="b"]').val();
        $('#v2r').text(r2); $('#v2g').text(g2); $('#v2b').text(b2);
        let color2 = `rgb(${r2}, ${g2}, ${b2})`; $('#ind2').css('background', color2);

        let grad = `linear-gradient(${currentDir}, ${color1} 0%, ${color2} 100%)`;
        $('#live-preview').css('background', grad); $('#live-preview').css('background-image', 'none');
        $('#final-grad-input').val(grad);
    }

    $('.rgb-slider').on('input', updateRGB);
    
    $('.dir-btn').click(function() {
        $('.dir-btn').removeClass('active');
        $(this).addClass('active');
        currentDir = $(this).data('dir');
        updateRGB();
    });

    $('.tab-item').click(function() {
        $('.tab-item').removeClass('active'); $(this).addClass('active');
        const id = $(this).attr('id');
        $('#f-file, #f-url, #f-color').hide();
        if(id === 't-file') $('#f-file').show();
        if(id === 't-url') $('#f-url').show();
        if(id === 't-color') { $('#f-color').show(); updateRGB(); }
    });

    const iconCheck = `<div style="margin-bottom:15px;"><svg width="65" height="65" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" fill="#22c55e" fill-opacity="0.1" stroke="#22c55e" stroke-width="1.5"/><path d="M8.5 12.5L11 15L16 10" stroke="#22c55e" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></div>`;
    const iconDeactivated = `<div style="margin-bottom:15px;"><svg width="65" height="65" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" fill="#64748b" fill-opacity="0.1" stroke="#64748b" stroke-width="1.5"/><path d="M15 9L9 15M9 9L15 15" stroke="#64748b" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></div>`;

    $('.fx-toggle').on('change', function() {
        const effect = $(this).data('effect');
        const status = $(this).is(':checked') ? "1" : "0";
        const label = $(this).closest('.fx-row').find('span').text();
        $.post('Image_animation.php', { ajax_fx: 1, effect_type: effect, status: status }, function() {
            Swal.fire({
                html: (status === "1" ? iconCheck : iconDeactivated) + `<div style="color:#fff; font-weight:800; font-size:1.1rem; margin-top:10px;">${label} ${status === "1" ? 'Ativado' : 'Desativado'}</div>`,
                background: '#070e1b', showConfirmButton: false, timer: 1500, timerProgressBar: true, customClass: { popup: 'my-swal-popup' }
            });
        });
    });

    <?php if(isset($_GET['status']) && $_GET['status'] == 'ok'): ?>
    Swal.fire({
        html: iconCheck + `<div style="color:#fff; font-weight:800; font-size:1.1rem; margin-top:10px;">Estilo Salvo com Sucesso!</div>`,
        background: '#070e1b', showConfirmButton: false, timer: 2000, timerProgressBar: true, customClass: { popup: 'my-swal-popup' }
    });
    window.history.replaceState({}, document.title, "Image_animation.php");
    <?php endif; ?>
});
</script>

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !isset($_POST['ajax_fx'])) {
    if (isset($_POST['do_upload'])) {
        $upPath = './img/animation/uploads/'; if (!is_dir($upPath)) mkdir($upPath, 0777, true);
        $name = uniqid() . '.jpg';
        if (move_uploaded_file($_FILES['img_file']['tmp_name'], $upPath . $name)) {
            file_put_contents($jsonImg, json_encode([["ImageName" => "../img/animation/uploads/" . $name, "Upload_type" => "by_file"]]));
        }
    } elseif (isset($_POST['do_url'])) {
        file_put_contents($jsonImg, json_encode([["ImageName" => $_POST['img_url'], "Upload_type" => "by_url"]]));
    } elseif (isset($_POST['do_color'])) {
        file_put_contents($jsonImg, json_encode([["ImageName" => $_POST['bg_gradient'], "Upload_type" => "by_color"]]));
    }
    echo "<script>window.location.href='Image_animation.php?status=ok';</script>";
}
include "includes/footer.php";
?>
