<?php
require_once __DIR__.'/../app/bootstrap.php';
require_once __DIR__.'/_layout.php';
$user=require_login($pdo); csrf_check(); $error='';
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),
]; }
if($_SERVER['REQUEST_METHOD']==='POST'){
    $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=generate_available_code($pdo); elseif(!ensure_code_available($pdo,$code)) $error='Dieser Slug ist bereits vergeben. Bitte einen anderen wählen.'; }
    if(!$error){ try { $logoPath = handle_logo_upload($_FILES['logo'] ?? []); } catch(Throwable $e){ $error=$e->getMessage(); } }
    if(!$error){
        $stmt=$pdo->prepare('INSERT INTO '.qtbl('qr_codes').'(user_id,group_id,code,title,target_url,foreground_color,background_color,transparent_background,logo_path,utm_source,utm_medium,utm_campaign,utm_term,utm_content) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
        $stmt->execute([$user['id'],$groupId,$code,$title,$url,clean_hex($_POST['foreground_color']??'','#000000'),clean_hex($_POST['background_color']??'','#FFFFFF'),isset($_POST['transparent_background'])?1:0,$logoPath ?? null,$utm['utm_source']?:null,$utm['utm_medium']?:null,$utm['utm_campaign']?:null,$utm['utm_term']?:null,$utm['utm_content']?:null]);
        header('Location: edit.php?id='.$pdo->lastInsertId().'&created=1'); exit;
    }
}
page_header('QR-Code erstellen'); if($error) echo '<p class="notice">'.e($error).'</p>'; qr_form([], 'create.php', 'Erstellen'); page_footer();
