<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Увеличиваем лимиты для обработки больших изображений
ini_set('memory_limit', '256M');
ini_set('max_execution_time', 120);

$configFile = '/home/private/config.json';
$uploadDir  = __DIR__ . '/uploads/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

$allConfig = json_decode(@file_get_contents($configFile), true) ?: [];
$widgets   = $allConfig['widgets'] ?? [];

function genId(){
  return strtoupper(substr(bin2hex(random_bytes(4)),0,6));
}
function genSecret(){
  return bin2hex(random_bytes(8));
}

$result = null;
$error  = null;

// Инициализируем переменные для формы
$tg = '';
$max = '';
$wa = '';
$owner = '';
$design = '';

// Обработка редиректа после создания (PRG)
if(isset($_GET['created'], $_GET['id'], $_GET['key'])){
  $result = [
    'id'     => $_GET['id'],
    'secret' => $_GET['key']
  ];
}

// Запускаем сессию для временного хранения файла
session_start();

// Функция для обработки изображений (поддерживает PNG и JPEG)
function processImage($file) {
    $uploadDir = __DIR__ . '/uploads/';
    
    // Проверка ошибок загрузки
    if($file['error'] !== UPLOAD_ERR_OK) {
        return ['error' => 'Ошибка загрузки файла'];
    }
    
    // Проверка размера файла (макс 10MB)
    if($file['size'] > 10 * 1024 * 1024) {
        return ['error' => 'Файл слишком большой. Максимальный размер 10MB'];
    }
    
    // Проверка через getimagesize
    $imageInfo = @getimagesize($file['tmp_name']);
    if($imageInfo === false) {
        return ['error' => 'Файл не является изображением'];
    }
    
    // Определяем тип и создаем изображение
    switch($imageInfo[2]) {
        case IMAGETYPE_PNG:
            $img = @imagecreatefrompng($file['tmp_name']);
            break;
        case IMAGETYPE_JPEG:
            $img = @imagecreatefromjpeg($file['tmp_name']);
            break;
        default:
            return ['error' => 'Поддерживаются только PNG и JPEG форматы. Ваш файл: ' . $imageInfo['mime']];
    }
    
    if(!$img) {
        return ['error' => 'Не удалось открыть изображение'];
    }
    
    // Получаем размеры
    $w = imagesx($img);
    $h = imagesy($img);
    
    // Проверка на слишком большие размеры
    if($w > 5000 || $h > 5000) {
        imagedestroy($img);
        return ['error' => 'Изображение слишком большое. Максимальные размеры 5000×5000 пикселей'];
    }
    
    // Масштабируем если нужно (максимум 120px)
    $scale = min(120/$w, 120/$h, 1);
    
    if($scale < 1) {
        // Нужно масштабировать
        $newW = (int)($w * $scale);
        $newH = (int)($h * $scale);
        
        $tmp = imagecreatetruecolor($newW, $newH);
        
        // Для PNG сохраняем прозрачность
        if($imageInfo[2] === IMAGETYPE_PNG) {
            imagesavealpha($tmp, true);
            $trans = imagecolorallocatealpha($tmp, 0,0,0,127);
            imagefill($tmp, 0, 0, $trans);
        }
        
        imagecopyresampled($tmp, $img, 0,0,0,0, $newW,$newH, $w,$h);
        imagedestroy($img);
        $img = $tmp;
    }
    
    // Сохраняем в PNG (всегда сохраняем как PNG для единообразия)
    $filename = 'avatar_' . uniqid() . '.png';
    $dest = $uploadDir . $filename;
    
    if(!imagepng($img, $dest)) {
        imagedestroy($img);
        return ['error' => 'Ошибка при сохранении изображения'];
    }
    
    imagedestroy($img);
    
    return [
        'success' => true,
        'path' => 'https://' . $_SERVER['HTTP_HOST'] . '/uploads/' . $filename,
        'name' => $file['name']
    ];
}

// Если есть временный файл в сессии, используем его
$hasTempImage = isset($_SESSION['temp_image']) && !empty($_SESSION['temp_image']['path']);

if($_SERVER['REQUEST_METHOD']==='POST'){
  $tg  = trim($_POST['tg']  ?? '');
  $max = trim($_POST['max'] ?? '');
  $wa  = trim($_POST['wa']  ?? '');
  $owner = trim($_POST['owner'] ?? '');
  $design = $_POST['design'] ?? '';

  // Переменная для хранения результата обработки файла
  $processResult = null;
  
  // СНАЧАЛА обрабатываем файл, если он загружен
  if($design === 'custom' && !empty($_FILES['image']['tmp_name'])) {
      $processResult = processImage($_FILES['image']);
      if(isset($processResult['error'])) {
          $error = $processResult['error'];
      } else {
          // Сохраняем в сессию
          $_SESSION['temp_image'] = [
              'path' => $processResult['path'],
              'name' => $processResult['name']
          ];
          $hasTempImage = true;
      }
  }

  // ТОЛЬКО если нет ошибки файла, проверяем остальные поля
  if(!$error) {
      if(!$owner){
        $error = "Укажите ник организатора!";
      }
      elseif(!$design){
        $error = "Выберите дизайн!";
      }
      elseif(!$tg && !$max && !$wa){
        $error = "Заполните хотя бы одну ссылку на социальную сеть!";
      }
      elseif($design === 'custom' && !$hasTempImage){
        $error = "Вы выбрали свой PNG, но не загрузили изображение!";
      }
  }

  // Если все проверки пройдены - создаем виджет
  if(!$error) {
      $links = [
        [
          'name'=>'Telegram',
          'url'=>$tg,
          'iconUrl'=>'https://widget.ann123.ru/icons/telegram.png',
          'subtitle'=>'Написать в чат'
        ],
        [
          'name'=>'MAX',
          'url'=>$max,
          'iconUrl'=>'https://widget.ann123.ru/icons/max.png',
          'subtitle'=>'Написать в чат'
        ],
        [
          'name'=>'WhatsApp',
          'url'=>$wa,
          'iconUrl'=>'https://widget.ann123.ru/icons/whatsapp.png',
          'subtitle'=>'Написать в чат'
        ]
      ];
      
      // Определяем путь к изображению
      $imagePath = 'https://widget.ann123.ru/sp-mini2.png';
      if($design === 'custom' && $hasTempImage) {
          $imagePath = $_SESSION['temp_image']['path'];
      }

      // Генерируем ID и секрет
      do {
        $id = genId();
      } while(isset($widgets[$id]));

      $secret = genSecret();

      // Сохраняем виджет с IP и датой создания
      $widgets[$id] = [
        'owner'     => $owner,
        'secret'    => $secret,
        'design'    => $design,
        'panelBg'   => '#FFFFFF',
        'textColor' => '#222222',
        'position'  => 'right',
        'title'     => 'Напишите нам',
        'custom_image' => ($design === 'custom') ? $imagePath : null,
        'shift'     => 0,
        'offsetY'   => 0,
        'created_ip' => $_SERVER['REMOTE_ADDR'],  // Добавлен IP создателя
        'created_at' => date('Y-m-d H:i:s'),      // Добавлена дата создания
        'stats' => [                               // Добавлена статистика
            'telegram' => 0,
            'max' => 0,
            'whatsapp' => 0,
            'total' => 0
        ],
        'links'     => $links
      ];

      $allConfig['widgets'] = $widgets;
      file_put_contents($configFile, json_encode($allConfig, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));

      // Очищаем временные данные сессии
      unset($_SESSION['temp_image']);
      
      // Редирект
      header("Location: create.php?created=1&id=$id&key=$secret");
      exit;
  }
}

// Получаем данные для отображения
$selected = $_POST['design'] ?? ($hasTempImage ? 'custom' : '');
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Создать виджет</title>
<style>
*{
  box-sizing:border-box;
}

body{
  margin:0;
  font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif;
  background:#f4f6f9;
  color:#222;
}

.container{
  max-width:900px;
  margin:40px auto;
  background:#fff;
  padding:30px;
  border-radius:16px;
  box-shadow:0 10px 40px rgba(0,0,0,.08);
}

h1{
  margin-top:0;
  font-size:28px;
}

h3{
  margin-top:30px;
  margin-bottom:10px;
  font-size:18px;
}

input[type="text"],
input[type="url"]{
  width:100%;
  padding:12px;
  border-radius:10px;
  border:1px solid #ddd;
  margin-bottom:15px;
  font-size:14px;
  transition:.2s;
}

input[type="text"]:focus,
input[type="url"]:focus{
  border-color:#57b19a;
  outline:none;
  box-shadow:0 0 0 3px rgba(87,177,154,.15);
}

button{
  padding:14px 24px;
  background:#57b19a;
  color:#fff;
  border:none;
  border-radius:12px;
  cursor:pointer;
  font-size:15px;
  font-weight:600;
  transition:.2s;
}

button:hover{
  transform:translateY(-2px);
  box-shadow:0 8px 20px rgba(87,177,154,.3);
}

/* ==== ДИЗАЙН ==== */

.design-choice{
  display:grid;
  grid-template-columns:repeat(auto-fit,minmax(140px,1fr));
  gap:15px;
  margin:15px 0 25px;
}

.design-item{
  border:2px solid #e5e7eb;
  border-radius:16px;
  padding:15px;
  cursor:pointer;
  text-align:center;
  transition:.2s;
  display:flex;
  flex-direction:column;
  justify-content:center;
  align-items:center;
  min-height:150px;
  background:#fafafa;
}

.design-item:hover{
  border-color:#57b19a;
  transform:translateY(-3px);
}

.design-item.active{
  border-color:#57b19a;
  box-shadow:0 0 0 4px rgba(87,177,154,.15);
  background:#fff;
}

.design-item img{
  margin-bottom:10px;
  max-width:90px;
  max-height:90px;
}

.design-item input{
  display:none;
}

#preview-upload{
  pointer-events:none;
}

/* ==== РЕЗУЛЬТАТ ==== */

.result-box{
  background:#f9fafb;
  border-radius:14px;
  padding:20px;
  margin-top:20px;
}

.result-box input{
  width:100%;
  padding:10px;
  border-radius:8px;
  border:1px solid #ddd;
  font-family:monospace;
  margin-bottom:15px;
}

.actions{
  margin-top:20px;
  display:flex;
  gap:12px;
  flex-wrap:wrap;
}

.actions a{
  padding:12px 18px;
  border-radius:10px;
  text-decoration:none;
  font-weight:600;
  font-size:14px;
  transition:.2s;
}

.btn-green{
  background:#57b19a;
  color:#fff;
}

.btn-green:hover{
  transform:translateY(-2px);
  box-shadow:0 8px 20px rgba(87,177,154,.3);
}

.btn-blue{
  background:#4a6fdc;
  color:#fff;
}

.btn-blue:hover{
  transform:translateY(-2px);
  box-shadow:0 8px 20px rgba(74,111,220,.3);
}

.actions a:hover{
  transform:translateY(-2px);
  box-shadow:0 6px 16px rgba(0,0,0,.15);
}

/* ==== УЛУЧШЕННЫЙ РЕЗУЛЬТАТ ==== */
.code-block {
    margin-bottom: 20px;
}

.code-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.code-label {
    font-size: 14px;
    color: #666;
}

.copy-btn {
    background: #57b19a;
    color: white;
    border: none;
    border-radius: 6px;
    padding: 6px 12px;
    font-size: 13px;
    cursor: pointer;
    transition: background 0.2s;
}

.copy-btn:hover {
    background: #469d86;
}

.save-note {
    background: #fff3cd;
    border: 1px solid #ffeeba;
    border-radius: 8px;
    padding: 15px;
    margin: 20px 0;
    color: #856404;
    font-size: 14px;
    text-align: center;
}

/* Адаптация для мобильных */
@media (max-width: 600px) {
    .code-header {
        flex-direction: column;
        gap: 10px;
    }
    
    .copy-btn {
        width: 100%;
    }
}

/* Общий стиль для ссылок-кнопок */
.btn-action{
  padding:14px 24px;
  border-radius:12px;
  font-size:15px;
  font-weight:600;
  text-decoration:none;
  display:inline-block;
  transition:.2s;
}

/* ==== MOBILE ==== */

@media(max-width:600px){
  .container{
    margin:0;
    border-radius:0;
    padding:20px;
  }

  h1{
    font-size:22px;
  }
}

.file-name {
    font-size: 12px;
    color: #57b19a;
    margin-top: 5px;
    word-break: break-all;
}

.btn-pdf {
    background: #dc3545;
    color: #fff;
}

.btn-pdf:hover {
    background: #c82333;
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(220,53,69,.3);
}
</style>

</head>
<body>

<div class="container">
<h1>Создать виджет</h1>

<?php if($error): ?>
<p style="color:red;font-weight:bold;"><?=htmlspecialchars($error)?></p>
<?php endif; ?>

<?php if($result): ?>
<div class="result-box">
<h2>Готово 🎉</h2>

<div class="code-block">
    <div class="code-header">
        <span class="code-label">Код для вставки:</span>
        <button class="copy-btn" onclick="copyToClipboard('embed-code')">📋 Скопировать</button>
    </div>
    <input type="text" id="embed-code" readonly onclick="this.select()"
           value='&lt;script src="https://<?=htmlspecialchars($_SERVER['HTTP_HOST'])?>/widget.php?id=<?=$result['id']?>" async&gt;&lt;/script&gt;'
           style="width:100%;font-family:monospace">
</div>

<div class="code-block">
    <div class="code-header">
        <span class="code-label">Ссылка для редактирования:</span>
        <button class="copy-btn" onclick="copyToClipboard('edit-link')">📋 Скопировать</button>
    </div>
    <input type="text" id="edit-link" readonly onclick="this.select()"
           value="https://<?=htmlspecialchars($_SERVER['HTTP_HOST'])?>/edit.php?id=<?=$result['id']?>&key=<?=$result['secret']?>"
           style="width:100%;font-family:monospace">
</div>

<div class="save-note">
    ⚠️ <strong>Важно!</strong> Сохраните эти ссылки. Они больше не будут показаны.
</div>

<div class="actions">
    <a href="create.php" class="btn-green btn-action">Создать ещё один виджет</a>
    <a href="https://<?=htmlspecialchars($_SERVER['HTTP_HOST'])?>/edit.php?id=<?=$result['id']?>&key=<?=$result['secret']?>" class="btn-blue btn-action">Редактировать этот виджет</a>
    <a href="https://sp-kapusta.ru/" target="_blank" class="btn-green btn-action">На сайт</a>
<!-- Новая кнопка PDF -->
    <a href="generate_pdf.php?id=<?=$result['id']?>&key=<?=$result['secret']?>" class="btn-pdf btn-action" target="_blank">📄 Скачать PDF</a>
</div>

</div>

<!-- Добавляем JavaScript для копирования -->
<script>
function copyToClipboard(elementId) {
    var copyText = document.getElementById(elementId);
    copyText.select();
    copyText.setSelectionRange(0, 99999); // Для мобильных устройств
    document.execCommand("copy");
    
    // Визуальная обратная связь
    var btn = event.target;
    var originalText = btn.innerText;
    btn.innerText = '✅ Скопировано!';
    setTimeout(function() {
        btn.innerText = originalText;
    }, 2000);
}
</script>
<?php endif; ?>

<?php if(!$result): ?>
<form method="post" enctype="multipart/form-data">

<h3>Организатор</h3>
Ник организатора: 
<input type="text" name="owner"
 value="<?=htmlspecialchars($owner ?? '')?>"
 placeholder="Ваш ник, по желанию как на сайте"><br><br>

<h3>Дизайн</h3>
<div class="design-choice">
<?php
function isActiveCreate($design, $selected){
    return $selected === $design
        ? ['active'=>'active','checked'=>'checked']
        : ['active'=>'','checked'=>''];
}

$designs = [
    'character'=>[
        'img'=>'https://widget.ann123.ru/sp-mini2.png',
        'label'=>'Персонаж'
    ],
    'anyutka85'=>[
        'img'=>'https://widget.ann123.ru/avatar/ann.png',
        'label'=>'Анютка85'
    ],
    'callibri'=>[
        'img'=>'',
        'label'=>'Кнопка',
        'customDiv'=>'💬'
    ],
    'wide'=>[
        'img'=>'',
        'label'=>'Широкая кнопка',
        'customDiv'=>'💬 Написать'
    ]
];

foreach($designs as $key=>$d){
    $a = isActiveCreate($key,$selected);

    echo '<label class="design-item '.$a['active'].'">';
    echo '<input type="radio" name="design" value="'.$key.'" '.$a['checked'].'>';

    if(!empty($d['img'])){
        echo '<img src="'.$d['img'].'" style="width:90px;height:90px;object-fit:contain;">';
    } else {
        echo '<div style="
            width:'.($key==='callibri'?60:110).'px;
            height:'.($key==='callibri'?60:40).'px;
            border-radius:'.($key==='callibri'?'50%':'24px').';
            background:#57b19a;
            color:#fff;
            display:flex;
            align-items:center;
            justify-content:center;
            font-size:'.($key==='callibri'?26:15).'px;
            font-weight:'.($key==='wide'?'bold':'normal').';
            margin:0 auto 8px;
        ">'.$d['customDiv'].'</div>';
    }

    echo '<div>'.$d['label'].'</div>';
    echo '</label>';
}

$a = isActiveCreate('custom',$selected);
?>

<label class="design-item <?=$a['active']?> <?=($hasTempImage && $selected==='custom') ? 'active' : ''?>" id="custom-character">
    <input type="radio" id="custom-radio" name="design" value="custom" <?=($selected==='custom') ? 'checked' : ''?>>
    <img id="preview-upload"
         src="<?=($hasTempImage && $selected==='custom') ? $_SESSION['temp_image']['path'] : ''?>"
         style="width:90px;height:90px;object-fit:contain;<?=($hasTempImage && $selected==='custom') ? 'display:block;' : 'display:none;'?>">
    <div>Свой PNG</div>
    <div id="file-name" class="file-name" style="<?=($hasTempImage && $selected==='custom') ? 'display:block;' : 'display:none;'?>">
        <?=($hasTempImage && $selected==='custom') ? '✓ ' . $_SESSION['temp_image']['name'] : ''?>
    </div>
</label>

<input type="file" id="custom-file" name="image" accept="image/png,image/jpeg" style="display:none;">

</div>

<h3>Ссылки</h3>
Telegram: <input type="url" name="tg"
 value="<?=htmlspecialchars($tg ?? '')?>"
 placeholder="Ссылка на ЛС или Группу"><br>
MAX: <input type="url" name="max"
 value="<?=htmlspecialchars($max ?? '')?>"
 placeholder="Ссылка на ЛС или Группу"><br>
WhatsApp: <input type="url" name="wa"
 value="<?=htmlspecialchars($wa ?? '')?>"
 placeholder="Ссылка на ЛС или Группу"><br>

<button>Создать виджет</button>
</form>

<?php endif; ?>

<script>
(function() {
    const items = document.querySelectorAll('.design-item');
    const radios = document.querySelectorAll('.design-item input[type="radio"]');
    const fileInput = document.getElementById('custom-file');
    const preview = document.getElementById('preview-upload');
    const customBox = document.getElementById('custom-character');
    const customRadio = document.getElementById('custom-radio');
    const fileNameDiv = document.getElementById('file-name');

    // Подсветка дизайна при выборе
    radios.forEach(radio => {
        radio.addEventListener('change', function() {
            items.forEach(i => i.classList.remove('active'));
            this.closest('.design-item').classList.add('active');

            // Если кастом — открываем файл
            if (this === customRadio) {
                fileInput.click();
            }
        });
    });

    // Клик по кастом-карточке
    customBox.addEventListener('click', function(e) {
        e.preventDefault();
        customRadio.checked = true;
        items.forEach(i => i.classList.remove('active'));
        customBox.classList.add('active');
        fileInput.click();
    });

    // Обработка выбора файла
    fileInput.addEventListener('change', function() {
        const file = this.files[0];
        if (!file) return;
        
        // Проверка расширения (теперь можно .png или .jpg/.jpeg)
        const extension = file.name.split('.').pop().toLowerCase();
        if (!['png', 'jpg', 'jpeg'].includes(extension)) {
            alert('Можно загружать только PNG или JPG/JPEG файлы!');
            this.value = '';
            return;
        }
        
        // Проверка MIME типа
        if (!['image/png', 'image/jpeg'].includes(file.type)) {
            alert('Файл должен быть PNG или JPEG изображением!');
            this.value = '';
            return;
        }

        // Проверка размера
        if (file.size > 10 * 1024 * 1024) {
            alert('Файл слишком большой. Максимальный размер 10MB');
            this.value = '';
            return;
        }

        // Показываем превью
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.src = e.target.result;
            preview.style.display = 'block';
            fileNameDiv.textContent = '✓ ' + file.name;
            fileNameDiv.style.display = 'block';
        };
        reader.readAsDataURL(file);
        
        // Активируем кастом
        items.forEach(i => i.classList.remove('active'));
        customBox.classList.add('active');
        customRadio.checked = true;
    });

    // Восстановление после перезагрузки
    document.addEventListener('DOMContentLoaded', function() {
        const checked = document.querySelector('input[name="design"]:checked');
        if (checked) {
            items.forEach(i => i.classList.remove('active'));
            checked.closest('.design-item').classList.add('active');
        }
    });
})();
</script>
</div>

</body>
</html>
