<?php
include 'check_code.php';
include 'includes/db.php';
include 'includes/functions.php';
// Session bereits in check_code gestartet

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $photog = trim($_POST['photographer']);
    if (!$photog) $errors[] = 'Fotograf/in erforderlich';
    if (!isset($_FILES['images'])) $errors[] = 'Keine Dateien';
    else {
        foreach ($_FILES['images']['error'] as $i => $err) {
            if ($err !== UPLOAD_ERR_OK) { $errors[] = 'Fehler beim Upload'; break; }
            $tmp = ['tmp_name' => $_FILES['images']['tmp_name'][$i], 'name' => $_FILES['images']['name'][$i]];
            if (!is_allowed_image($tmp)) { $errors[] = 'Nur JPG/PNG erlaubt'; break; }
            if (filesize($tmp['tmp_name']) > 50*1024*1024) { $errors[] = 'Max 50MB pro Datei'; break; }
        }
    }
    if (!$errors) {
        foreach ($_FILES['images']['tmp_name'] as $i => $tmpName) {
            $orig = $_FILES['images']['name'][$i];
            $ext = pathinfo($orig, PATHINFO_EXTENSION);
            $safe = sanitize_filename($photog) . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
            move_uploaded_file($tmpName, __DIR__ . '/uploads/' . $safe);
            $stmt = $pdo->prepare('INSERT INTO photos (filename, photographer_name, description, uploader_ip) VALUES (?,?,?,?)');
            $desc = trim($_POST['description'][$i] ?? '');
            $stmt->execute([$safe, $photog, $desc, $_SERVER['REMOTE_ADDR']]);
        }
        header('Location: gallery.php');
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Upload</title>
  <link rel="stylesheet" href="css/style.css">
</head>
<body>
<nav class="navbar">
  <a href="index.php">Home</a>
  <a href="gallery.php">Galerie</a>
  <a href="upload.php">Hochladen</a>
  <a href="ranking.php">Ranking</a>
  <a href="logout.php">Logout</a>
</nav>
<main class="container">
  <?php if ($errors): ?>
    <div class="error">
      <?php foreach ($errors as $e) echo '<p>' . escape($e) . '</p>'; ?>
    </div>
  <?php endif; ?>
  <form method="post" enctype="multipart/form-data">
    <input type="text" name="photographer" placeholder="Fotograf/in-Name" required>
    <input type="file" name="images[]" accept="image/jpeg,image/png" multiple required>
    <button type="submit">Hochladen</button>
  </form>
</main>
</body>
</html>