<?php
require_once __DIR__.'/../app/bootstrap.php';
require_once __DIR__.'/_layout.php';
$user=require_login($pdo); csrf_check();
function post_utm(): array { return [
  'utm_source'=>substr(trim($_POST['utm_source']??''),0,120),
  'utm_medium'=>substr(trim($_POST['utm_medium']??''),0,120),
  'utm_campaign'=>substr(trim($_POST['utm_campaign']??''),0,190),
  'utm_term'=>substr(trim($_POST['utm_term']??''),0,190),
  'utm_content'=>substr(trim($_POST['utm_content']??''),0,190),
]; }
$id=(int)($_GET['id']??$_POST['id']??0);
$stmt=$pdo->prepare('SELECT q.* FROM '.qtbl('qr_codes').' q WHERE q.id=? AND '.qr_edit_where('q'));
$stmt->execute([$id,$user['id'],$user['id']]);
$qr=$stmt->fetch(); if(!$qr){http_response_code(404);exit('Nicht gefunden oder keine Bearbeitungsrechte.');}
$error='';
if($_SERVER['REQUEST_METHOD']==='POST'){
    if(isset($_POST['delete'])){ require_post(); delete_logo_file($qr['logo_path'] ?? null); $d=$pdo->prepare('DELETE FROM '.qtbl('qr_codes').' WHERE id=?'); $d->execute([$id]); header('Location: dashboard.php'); exit; }
    $title=trim($_POST['title']??''); $url=trim($_POST['target_url']??''); $groupId=selected_group_id($pdo,(int)$user['id'],$_POST['group_id']??0); $utm=post_utm();
    try { $code = validate_slug($_POST['custom_slug'] ?? ''); } catch (Throwable $e) { $error=$e->getMessage(); $code=''; }
    if(!$error && ($title===''||!valid_url($url))) $error='Bitte Titel und gültige http/https-URL erfassen.';
    if(!$error){ if($code==='') $code=$qr['code']; elseif(!ensure_code_available($pdo,$code,$id)) $error='Dieser Slug ist bereits vergeben. Bitte einen anderen wählen.'; }
    $logoPath = $qr['logo_path'] ?? null;
    if(!$error){
        try {
            if(isset($_POST['remove_logo'])) { delete_logo_file($logoPath); $logoPath=null; }
            $logoPath = handle_logo_upload($_FILES['logo'] ?? [], $logoPath);
        } catch(Throwable $e){ $error=$e->getMessage(); }
    }
    if(!$error){ $u=$pdo->prepare('UPDATE '.qtbl('qr_codes').' SET group_id=?,code=?,title=?,target_url=?,foreground_color=?,background_color=?,transparent_background=?,logo_path=?,utm_source=?,utm_medium=?,utm_campaign=?,utm_term=?,utm_content=? WHERE id=?');$u->execute([$groupId,$code,$title,$url,clean_hex($_POST['foreground_color']??'','#000000'),clean_hex($_POST['background_color']??'','#FFFFFF'),isset($_POST['transparent_background'])?1:0,$logoPath,$utm['utm_source']?:null,$utm['utm_medium']?:null,$utm['utm_campaign']?:null,$utm['utm_term']?:null,$utm['utm_content']?:null,$id]);header('Location: edit.php?id='.$id.'&saved=1');exit;}
}
$short=base_url($config).'/q/'.$qr['code']; $logoUrl=!empty($qr['logo_path'])?'logo.php?id='.(int)$qr['id']:''; page_header('QR-Code bearbeiten'); if(isset($_GET['saved'])) echo '<p class="notice ok">Gespeichert.</p>'; if(isset($_GET['created'])) echo '<p class="notice ok">QR-Code erstellt.</p>'; if($error) echo '<p class="notice">'.e($error).'</p>'; ?>
<section class="card preview"><div><h2><?= e($qr['title']) ?></h2><p class="muted">Kurz-URL: <a href="<?= e($short) ?>" target="_blank"><?= e($short) ?></a></p><?php if(qr_append_utm($qr['target_url'],$qr)!==$qr['target_url']): ?><p class="muted">Ziel mit UTM: <?= e(qr_append_utm($qr['target_url'],$qr)) ?></p><?php endif; ?><div class="qrbox"><canvas id="qr-main" class="qr" width="256" height="256" data-text="<?= e($short) ?>" data-fg="<?= e($qr['foreground_color']) ?>" data-bg="<?= e($qr['background_color']) ?>" data-transparent="<?= (int)$qr['transparent_background'] ?>" data-logo="<?= e($logoUrl) ?>"></canvas></div><div class="downloads"><button class="btn" data-download="png" data-target="#qr-main" data-name="<?= e($qr['code']) ?>">PNG</button><button class="btn" data-download="jpg" data-target="#qr-main" data-name="<?= e($qr['code']) ?>">JPEG</button><button class="btn" data-download="svg" data-target="#qr-main" data-name="<?= e($qr['code']) ?>">SVG</button></div></div></section>
<?php qr_form($qr, 'edit.php', 'Speichern'); ?><form method="post" data-confirm="Diesen QR-Code wirklich löschen?"><input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="id" value="<?= (int)$id ?>"><button class="btn danger" name="delete" value="1">Löschen</button></form><?php page_footer(); ?>
