<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
set_time_limit(300);

$senha_definida = "123456"; 
$mensagem = "";

$cadeiras = [];
for ($i = 1; $i <= 50; $i++) {
    $id = str_pad($i, 2, "0", STR_PAD_LEFT);
    $cadeiras[$id] = "Cadeira Produtiva " . $id;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload'])) {
    if (isset($_POST['senha']) && $_POST['senha'] === $senha_definida) {
        $id = $_POST['cadeira'];
        $target_dir = "uploads/" . $id . "/";
        
        if (file_exists($target_dir)) {
            $arquivos_antigos = glob($target_dir . "*"); 
            foreach($arquivos_antigos as $arquivo){
                if(is_file($arquivo)) unlink($arquivo); 
            }
        } else {
            mkdir($target_dir, 0777, true);
        }

        $sucesso_arquivos = 0;

        if (!empty($_FILES['thumb']['name'])) {
            if(move_uploaded_file($_FILES['thumb']['tmp_name'], $target_dir . "thumb.jpg")){
                $sucesso_arquivos++;
            }
        }

        if (!empty($_FILES['arquivos']['name'][0])) {
            foreach ($_FILES['arquivos']['name'] as $key => $name) {
                if ($_FILES['arquivos']['error'][$key] === 0) {
                    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
                    
                    if ($ext === 'pdf') {
                        $novo_nome = "estatisticas.pdf";
                        file_put_contents("version_" . $id . ".txt", time());
                    } else {
                        $novo_nome = preg_replace("/[^a-zA-Z0-9.]/", "_", $name);
                    }
                    
                    if (move_uploaded_file($_FILES['arquivos']['tmp_name'][$key], $target_dir . $novo_nome)) {
                        $sucesso_arquivos++;
                    }
                }
            }
        }

        $mensagem = "<div style='color:#27ae60; font-weight:bold; padding:10px;'>✅ Item $id atualizado com sucesso ($sucesso_arquivos arquivos)!</div>";

    } else {
        $mensagem = "<div style='color:#e74c3c; font-weight:bold; padding:10px;'>❌ Senha incorreta!</div>";
    }
}

// URL Relativa do Protocolo para evitar bloqueio no HTTPS
$protocolo = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https://" : "http://";
$url_base = $protocolo . $_SERVER['HTTP_HOST'];
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Painel de Controle - Cotações Agro</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; background: #f0f2f5; padding: 20px; margin: 0; }
        .container { max-width: 850px; margin: auto; background: white; padding: 25px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
        .upload-box { background: #fffcf5; padding: 20px; border: 1px solid #ffeaa7; border-radius: 8px; margin-bottom: 20px; }
        label { font-weight: bold; display: block; margin-top: 15px; color: #1b5e20; }
        
        .drop-zone { 
            border: 2px dashed #27ae60; border-radius: 8px; padding: 30px; 
            text-align: center; background: #fff; cursor: pointer; 
            position: relative; margin-top: 5px; transition: 0.3s;
        }
        .drop-zone.dragover { background: #e8f5e9; border-color: #1b5e20; transform: scale(1.01); }
        .drop-zone input { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; }
        
        .file-info { font-size: 13px; color: #2e7d32; margin-top: 10px; font-weight: bold; min-height: 1.2em; }
        select, input[type="password"], .btn-main { width: 100%; padding: 14px; margin: 8px 0; border-radius: 6px; border: 1px solid #ccc; box-sizing: border-box; }
        .btn-main { background: #27ae60; color: white; border: none; font-weight: bold; cursor: pointer; font-size: 16px; }
        .btn-main:hover { background: #1b5e20; }
        .item-row { display: flex; justify-content: space-between; align-items: center; padding: 10px; border-bottom: 1px solid #eee; }
        .btn-sm { padding: 8px 14px; border-radius: 4px; text-decoration: none; font-size: 12px; color: white; border: none; cursor: pointer; font-weight: bold; }
        .bg-blue { background: #3498db; }
        .bg-blue:hover { background: #2980b9; }
    </style>
</head>
<body>
<div class="container">
    <h2 style="text-align:center; color:#1b5e20;">Central Conexão Agro</h2>
    
    <div class="upload-box">
        <?php echo $mensagem; ?>
        <form action="upload.php" method="POST" enctype="multipart/form-data">
            <label>1. Selecionar ID da Cadeira:</label>
            <select name="cadeira">
                <?php foreach($cadeiras as $id => $n) echo "<option value='$id'>$n</option>"; ?>
            </select>

            <label>2. Thumbnail / Capa WhatsApp (.jpg):</label>
            <div class="drop-zone" id="zone-thumb">
                <p>Arraste a capa única aqui ou clique</p>
                <input type="file" name="thumb" accept="image/jpeg">
                <div class="file-info"></div>
            </div>

            <label>3. Novo PDF e Imagens Adicionais (Múltiplos):</label>
            <div class="drop-zone" id="zone-files">
                <p>Arraste os arquivos aqui ou clique</p>
                <input type="file" name="arquivos[]" accept="image/*,application/pdf" multiple>
                <div class="file-info"></div>
            </div>

            <label>4. Senha Administrativa:</label>
            <input type="password" name="senha" required>

            <button type="submit" name="upload" class="btn-main">🚀 Resetar e Publicar Novos Arquivos</button>
        </form>
    </div>

    <h3>Monitoramento das Cadeiras</h3>
    <?php foreach($cadeiras as $id_link => $n_link): 
        $path = "uploads/" . $id_link . "/";
        $existe = (file_exists($path) && count(glob($path . "*")) > 0);
        $link = $url_base . "/slides.php?id=" . $id_link;
    ?>
    <div class="item-row" style="border-left: 5px solid <?php echo $existe ? '#27ae60' : '#ccc'; ?>;">
        <span><strong>ID <?php echo $id_link; ?></strong> (<?php echo $existe ? 'ATIVO' : 'VAZIO'; ?>)</span>
        <div>
            <button class="btn-sm bg-blue" onclick="copiarLink('<?php echo $link; ?>')">📋 Copiar Link</button>
            <a href="<?php echo $link; ?>" target="_blank" class="btn-sm" style="background:#27ae60;">👁️ Ver Slide</a>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<script>
function copiarLink(texto) {
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(texto).then(() => {
            alert('Link copiado!\n\n' + texto);
        }).catch(() => fallbackCopiar(texto));
    } else {
        fallbackCopiar(texto);
    }
}

function fallbackCopiar(texto) {
    const tempInput = document.createElement('input');
    tempInput.value = texto;
    document.body.appendChild(tempInput);
    tempInput.select();
    tempInput.setSelectionRange(0, 99999);
    try {
        document.execCommand('copy');
        alert('Link copiado!\n\n' + texto);
    } catch (err) {
        prompt('Copie o link manualmente:', texto);
    }
    document.body.removeChild(tempInput);
}

document.querySelectorAll('.drop-zone').forEach(zone => {
    const input = zone.querySelector('input');
    const info = zone.querySelector('.file-info');

    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        zone.addEventListener(eventName, e => {
            e.preventDefault();
            e.stopPropagation();
        }, false);
    });

    ['dragenter', 'dragover'].forEach(eventName => {
        zone.addEventListener(eventName, () => zone.classList.add('dragover'), false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        zone.addEventListener(eventName, () => zone.classList.remove('dragover'), false);
    });

    zone.addEventListener('drop', e => {
        input.files = e.dataTransfer.files;
        updateLabel(input, info);
    }, false);

    input.addEventListener('change', () => updateLabel(input, info));
});

function updateLabel(input, infoElement) {
    if (input.files.length > 1) {
        infoElement.innerText = "📦 " + input.files.length + " arquivos selecionados.";
    } else if (input.files.length === 1) {
        infoElement.innerText = "📄 " + input.files[0].name;
    } else {
        infoElement.innerText = "";
    }
}
</script>
</body>
</html>
