<?php
session_start();

// PHPMailer einbinden
require_once __DIR__ . '/phpmailer/PHPMailer.php';
use PHPMailer\PHPMailer\PHPMailer;

// Passwort aus separater Konfigurationsdatei laden
require_once __DIR__ . '/config.php';

// Konfiguration
$empfaenger = 'info@yoshi-tools.com';
$max_zeichen = 200;
$max_filesize = 3 * 1024 * 1024; // 3 MB
$allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp'];
$allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];

// IONOS SMTP Konfiguration
$smtp_config = [
    'host' => 'smtp.ionos.de',
    'port' => 587,
    'username' => 'info@yoshi-tools.com',
    'password' => SMTP_PASSWORD,  // aus config.php
    'secure' => 'tls'
];

// Sprache ermitteln (URL-Parameter hat immer Vorrang)
$supported_langs = ['de', 'en', 'fr', 'es'];
if (isset($_GET['lang']) && in_array($_GET['lang'], $supported_langs)) {
    $lang = $_GET['lang'];
} elseif (isset($_SESSION['lang']) && in_array($_SESSION['lang'], $supported_langs)) {
    $lang = $_SESSION['lang'];
} else {
    $lang = 'de';
}
$_SESSION['lang'] = $lang;

// Übersetzungen
$translations = [
    'de' => [
        'title' => 'Kontakt',
        'page_title' => 'Kontakt – Yoshi Tools',
        'subtitle' => 'Schreib uns eine Nachricht (max. %d Zeichen)',
        'email_label' => 'Deine E-Mail-Adresse',
        'email_placeholder' => 'beispiel@email.de',
        'message_label' => 'Deine Nachricht',
        'message_placeholder' => 'Was möchtest du uns mitteilen?',
        'attachment_label' => 'Screenshot anhängen (optional)',
        'attachment_hint' => 'Erlaubt: JPG, PNG, GIF, WebP, BMP (max. 3 MB)',
        'captcha_label' => 'Sicherheitscode eingeben',
        'captcha_placeholder' => 'Code hier eingeben',
        'submit' => 'Nachricht senden',
        'back' => 'Zurück zur Startseite',
        'success' => 'Vielen Dank! Deine Nachricht wurde erfolgreich gesendet.',
        'error_email' => 'Bitte gib eine gültige E-Mail-Adresse ein.',
        'error_message' => 'Bitte gib eine Nachricht ein.',
        'error_length' => 'Die Nachricht darf maximal %d Zeichen haben.',
        'error_captcha' => 'Der Sicherheitscode ist falsch.',
        'error_send' => 'Die E-Mail konnte nicht gesendet werden. Bitte versuche es später erneut.',
        'error_file_type' => 'Nur Bilddateien (JPG, PNG, GIF, WebP, BMP) sind erlaubt.',
        'error_file_size' => 'Die Datei ist zu groß. Maximal 3 MB erlaubt.',
        'error_file_upload' => 'Beim Hochladen der Datei ist ein Fehler aufgetreten.',
        'mail_subject' => 'Kontaktanfrage von Yoshi Tools'
    ],
    'en' => [
        'title' => 'Contact',
        'page_title' => 'Contact – Yoshi Tools',
        'subtitle' => 'Send us a message (max. %d characters)',
        'email_label' => 'Your email address',
        'email_placeholder' => 'example@email.com',
        'message_label' => 'Your message',
        'message_placeholder' => 'What would you like to tell us?',
        'attachment_label' => 'Attach screenshot (optional)',
        'attachment_hint' => 'Allowed: JPG, PNG, GIF, WebP, BMP (max. 3 MB)',
        'captcha_label' => 'Enter security code',
        'captcha_placeholder' => 'Enter code here',
        'submit' => 'Send message',
        'back' => 'Back to homepage',
        'success' => 'Thank you! Your message has been sent successfully.',
        'error_email' => 'Please enter a valid email address.',
        'error_message' => 'Please enter a message.',
        'error_length' => 'The message may not exceed %d characters.',
        'error_captcha' => 'The security code is incorrect.',
        'error_send' => 'The email could not be sent. Please try again later.',
        'error_file_type' => 'Only image files (JPG, PNG, GIF, WebP, BMP) are allowed.',
        'error_file_size' => 'The file is too large. Maximum 3 MB allowed.',
        'error_file_upload' => 'An error occurred while uploading the file.',
        'mail_subject' => 'Contact request from Yoshi Tools'
    ],
    'fr' => [
        'title' => 'Contact',
        'page_title' => 'Contact – Yoshi Tools',
        'subtitle' => 'Envoyez-nous un message (max. %d caractères)',
        'email_label' => 'Votre adresse e-mail',
        'email_placeholder' => 'exemple@email.fr',
        'message_label' => 'Votre message',
        'message_placeholder' => 'Que souhaitez-vous nous dire ?',
        'attachment_label' => 'Joindre une capture d\'écran (optionnel)',
        'attachment_hint' => 'Autorisé : JPG, PNG, GIF, WebP, BMP (max. 3 Mo)',
        'captcha_label' => 'Entrez le code de sécurité',
        'captcha_placeholder' => 'Entrez le code ici',
        'submit' => 'Envoyer le message',
        'back' => 'Retour à la page d\'accueil',
        'success' => 'Merci ! Votre message a été envoyé avec succès.',
        'error_email' => 'Veuillez entrer une adresse e-mail valide.',
        'error_message' => 'Veuillez entrer un message.',
        'error_length' => 'Le message ne peut pas dépasser %d caractères.',
        'error_captcha' => 'Le code de sécurité est incorrect.',
        'error_send' => 'L\'e-mail n\'a pas pu être envoyé. Veuillez réessayer plus tard.',
        'error_file_type' => 'Seuls les fichiers image (JPG, PNG, GIF, WebP, BMP) sont autorisés.',
        'error_file_size' => 'Le fichier est trop volumineux. Maximum 3 Mo autorisé.',
        'error_file_upload' => 'Une erreur s\'est produite lors du téléchargement du fichier.',
        'mail_subject' => 'Demande de contact de Yoshi Tools'
    ],
    'es' => [
        'title' => 'Contacto',
        'page_title' => 'Contacto – Yoshi Tools',
        'subtitle' => 'Envíanos un mensaje (máx. %d caracteres)',
        'email_label' => 'Tu dirección de correo',
        'email_placeholder' => 'ejemplo@email.es',
        'message_label' => 'Tu mensaje',
        'message_placeholder' => '¿Qué te gustaría decirnos?',
        'attachment_label' => 'Adjuntar captura de pantalla (opcional)',
        'attachment_hint' => 'Permitido: JPG, PNG, GIF, WebP, BMP (máx. 3 MB)',
        'captcha_label' => 'Introduce el código de seguridad',
        'captcha_placeholder' => 'Introduce el código aquí',
        'submit' => 'Enviar mensaje',
        'back' => 'Volver a la página principal',
        'success' => '¡Gracias! Tu mensaje ha sido enviado con éxito.',
        'error_email' => 'Por favor, introduce una dirección de correo válida.',
        'error_message' => 'Por favor, introduce un mensaje.',
        'error_length' => 'El mensaje no puede superar los %d caracteres.',
        'error_captcha' => 'El código de seguridad es incorrecto.',
        'error_send' => 'No se pudo enviar el correo. Por favor, inténtalo más tarde.',
        'error_file_type' => 'Solo se permiten archivos de imagen (JPG, PNG, GIF, WebP, BMP).',
        'error_file_size' => 'El archivo es demasiado grande. Máximo 3 MB permitido.',
        'error_file_upload' => 'Se produjo un error al subir el archivo.',
        'mail_subject' => 'Solicitud de contacto de Yoshi Tools'
    ]
];

$t = $translations[$lang];

// CAPTCHA generieren (falls noch nicht vorhanden)
if (!isset($_SESSION['captcha'])) {
    $_SESSION['captcha'] = rand(1000, 9999);
}

$erfolg = false;
$fehler = '';

// Funktion zum Senden von E-Mail mit PHPMailer über SMTP
function sendMailWithAttachment($to, $subject, $message, $from_email, $reply_to, $attachment = null) {
    global $smtp_config;

    $mail = new PHPMailer();
    $mail->isSMTP();
    $mail->Host = $smtp_config['host'];
    $mail->Port = $smtp_config['port'];
    $mail->SMTPAuth = true;
    $mail->Username = $smtp_config['username'];
    $mail->Password = $smtp_config['password'];
    $mail->SMTPSecure = $smtp_config['secure'];
    $mail->CharSet = 'UTF-8';

    $mail->setFrom($smtp_config['username'], 'Yoshi Tools');
    $mail->addAddress($to);
    $mail->addReplyTo($reply_to);

    $mail->Subject = $subject;
    $mail->Body = $message;

    if ($attachment) {
        $mail->addStringAttachment($attachment['data'], $attachment['name'], 'base64', $attachment['type']);
    }

    return $mail->send();
}

// Formular verarbeiten
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
    $nachricht = htmlspecialchars(trim($_POST['nachricht'] ?? ''), ENT_QUOTES, 'UTF-8');
    $captcha_eingabe = trim($_POST['captcha'] ?? '');

    $attachment = null;

    // Validierung
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $fehler = $t['error_email'];
    } elseif (empty($nachricht)) {
        $fehler = $t['error_message'];
    } elseif (mb_strlen($nachricht) > $max_zeichen) {
        $fehler = sprintf($t['error_length'], $max_zeichen);
    } elseif ($captcha_eingabe !== strval($_SESSION['captcha'])) {
        $fehler = $t['error_captcha'];
    } else {
        // Datei-Upload prüfen
        if (isset($_FILES['anhang']) && $_FILES['anhang']['error'] !== UPLOAD_ERR_NO_FILE) {
            $file = $_FILES['anhang'];

            if ($file['error'] !== UPLOAD_ERR_OK) {
                $fehler = $t['error_file_upload'];
            } elseif ($file['size'] > $max_filesize) {
                $fehler = $t['error_file_size'];
            } else {
                // MIME-Type prüfen
                $finfo = new finfo(FILEINFO_MIME_TYPE);
                $mime_type = $finfo->file($file['tmp_name']);

                // Dateiendung prüfen
                $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

                if (!in_array($mime_type, $allowed_types) || !in_array($extension, $allowed_extensions)) {
                    $fehler = $t['error_file_type'];
                } else {
                    // Datei für Anhang vorbereiten
                    $attachment = [
                        'name' => basename($file['name']),
                        'type' => $mime_type,
                        'data' => file_get_contents($file['tmp_name'])
                    ];
                }
            }
        }

        // E-Mail senden wenn kein Fehler
        if (empty($fehler)) {
            $mail_text = $t['mail_subject'] . "\n";
            $mail_text .= "=====================================\n\n";
            $mail_text .= "Absender / Sender: " . $email . "\n";
            $mail_text .= "Sprache / Language: " . strtoupper($lang) . "\n";
            if ($attachment) {
                $mail_text .= "Anhang / Attachment: " . $attachment['name'] . "\n";
            }
            $mail_text .= "\nNachricht / Message:\n" . $nachricht . "\n";

            if (sendMailWithAttachment($empfaenger, $t['mail_subject'], $mail_text, 'noreply@yoshi-tools.com', $email, $attachment)) {
                $erfolg = true;
                $_SESSION['captcha'] = rand(1000, 9999);
            } else {
                $fehler = $t['error_send'];
            }
        }
    }

    // Bei Fehler neuen CAPTCHA-Code generieren
    if (!empty($fehler)) {
        $_SESSION['captcha'] = rand(1000, 9999);
    }
}

$captcha_code = $_SESSION['captcha'];
?>
<!doctype html>
<html lang="<?php echo $lang; ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo $t['page_title']; ?></title>
<style>
html, body {
  margin: 0;
  padding: 0;
  font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

.container {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px 24px;
}

.card {
  background: rgba(255,255,255,0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 20px 60px rgba(0,0,0,0.2);
}

h1 {
  margin: 0 0 4px;
  font-size: 24px;
  color: #222;
}

.subtitle {
  color: #666;
  font-size: 13px;
  margin-bottom: 16px;
}

/* Language Switcher */
.lang-switcher {
  position: fixed;
  top: 16px;
  right: 16px;
  z-index: 10;
  display: flex;
  gap: 8px;
}

.lang-btn {
  width: 36px;
  height: 26px;
  border: 2px solid transparent;
  border-radius: 4px;
  cursor: pointer;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.2);
  transition: transform 0.2s, border-color 0.2s, box-shadow 0.2s;
  padding: 0;
  background: #fff;
  text-decoration: none;
  display: block;
}

.lang-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(0,0,0,0.3);
}

.lang-btn.active {
  border-color: #FFD700;
  box-shadow: 0 0 12px 3px rgba(255,215,0,0.6), 0 4px 12px rgba(0,0,0,0.3);
  transform: scale(1.15);
}

.lang-btn svg {
  width: 100%;
  height: 100%;
  display: block;
}

label {
  display: block;
  font-weight: 600;
  color: #333;
  margin-bottom: 6px;
  font-size: 14px;
}

input[type="email"],
input[type="text"],
textarea {
  width: 100%;
  padding: 10px 12px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  font-family: inherit;
  box-sizing: border-box;
  transition: border-color 0.2s;
}

input[type="email"]:focus,
input[type="text"]:focus,
textarea:focus {
  outline: none;
  border-color: #667eea;
}

textarea {
  resize: vertical;
  min-height: 70px;
}

.field {
  margin-bottom: 12px;
}

.char-count {
  text-align: right;
  font-size: 12px;
  color: #888;
  margin-top: 4px;
}

.char-count.over {
  color: #e53935;
  font-weight: 600;
}

/* File Upload Styling */
.file-upload-wrapper {
  position: relative;
  border: 2px dashed #e0e0e0;
  border-radius: 8px;
  padding: 12px;
  text-align: center;
  transition: border-color 0.2s, background 0.2s;
  cursor: pointer;
}

.file-upload-wrapper:hover {
  border-color: #667eea;
  background: rgba(102, 126, 234, 0.05);
}

.file-upload-wrapper.dragover {
  border-color: #667eea;
  background: rgba(102, 126, 234, 0.1);
}

.file-upload-wrapper input[type="file"] {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}

.file-upload-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.file-upload-text {
  color: #666;
  font-size: 14px;
}

.file-upload-hint {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}

.file-name {
  margin-top: 10px;
  padding: 8px 12px;
  background: #e8f5e9;
  border-radius: 6px;
  font-size: 13px;
  color: #2e7d32;
  display: none;
}

.file-name.visible {
  display: block;
}

.captcha-box {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 14px;
}

.captcha-code {
  background: #f0f0f0;
  padding: 10px 16px;
  border-radius: 8px;
  font-size: 20px;
  font-weight: 700;
  letter-spacing: 4px;
  color: #333;
  font-family: monospace;
  user-select: none;
}

.captcha-input {
  flex: 1;
}

.captcha-input input {
  width: 100%;
}

button {
  width: 100%;
  padding: 12px;
  background: #667eea;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.2s;
}

button:hover {
  background: #5a6fd6;
}

.message {
  padding: 10px 14px;
  border-radius: 8px;
  margin-bottom: 12px;
  font-size: 13px;
}

.message.success {
  background: #e8f5e9;
  color: #2e7d32;
  border: 1px solid #a5d6a7;
}

.message.error {
  background: #ffebee;
  color: #c62828;
  border: 1px solid #ef9a9a;
}

.back-link {
  display: inline-block;
  margin-top: 14px;
  color: #667eea;
  text-decoration: none;
  font-weight: 600;
  font-size: 14px;
}

.back-link:hover {
  text-decoration: underline;
}

@media (max-width: 500px) {
  .card {
    padding: 24px;
  }
  .captcha-box {
    flex-direction: column;
    align-items: stretch;
  }
  .captcha-code {
    text-align: center;
  }
}
</style>
</head>
<body>

<!-- Language Switcher -->
<div class="lang-switcher">
  <a href="kontakt.php?lang=de" class="lang-btn <?php echo $lang === 'de' ? 'active' : ''; ?>" title="Deutsch">
    <svg viewBox="0 0 5 3"><rect width="5" height="1" y="0" fill="#000"/><rect width="5" height="1" y="1" fill="#D00"/><rect width="5" height="1" y="2" fill="#FFCE00"/></svg>
  </a>
  <a href="kontakt.php?lang=en" class="lang-btn <?php echo $lang === 'en' ? 'active' : ''; ?>" title="English">
    <svg viewBox="0 0 60 30"><clipPath id="s"><path d="M0,0 v30 h60 v-30 z"/></clipPath><clipPath id="t"><path d="M30,15 h30 v15 z v15 h-30 z h-30 v-15 z v-15 h30 z"/></clipPath><g clip-path="url(#s)"><path d="M0,0 v30 h60 v-30 z" fill="#012169"/><path d="M0,0 L60,30 M60,0 L0,30" stroke="#fff" stroke-width="6"/><path d="M0,0 L60,30 M60,0 L0,30" clip-path="url(#t)" stroke="#C8102E" stroke-width="4"/><path d="M30,0 v30 M0,15 h60" stroke="#fff" stroke-width="10"/><path d="M30,0 v30 M0,15 h60" stroke="#C8102E" stroke-width="6"/></g></svg>
  </a>
  <a href="kontakt.php?lang=fr" class="lang-btn <?php echo $lang === 'fr' ? 'active' : ''; ?>" title="Français">
    <svg viewBox="0 0 3 2"><rect width="1" height="2" x="0" fill="#002395"/><rect width="1" height="2" x="1" fill="#fff"/><rect width="1" height="2" x="2" fill="#ED2939"/></svg>
  </a>
  <a href="kontakt.php?lang=es" class="lang-btn <?php echo $lang === 'es' ? 'active' : ''; ?>" title="Español">
    <svg viewBox="0 0 3 2"><rect width="3" height="2" fill="#AA151B"/><rect width="3" height="1" y="0.5" fill="#F1BF00"/></svg>
  </a>
</div>

<div class="container">
  <div class="card">
    <h1><?php echo $t['title']; ?></h1>
    <p class="subtitle"><?php echo sprintf($t['subtitle'], $max_zeichen); ?></p>

    <?php if ($erfolg): ?>
      <div class="message success">
        <?php echo $t['success']; ?>
      </div>
    <?php elseif (!empty($fehler)): ?>
      <div class="message error">
        <?php echo $fehler; ?>
      </div>
    <?php endif; ?>

    <?php if (!$erfolg): ?>
    <form method="post" action="?lang=<?php echo $lang; ?>" enctype="multipart/form-data">
      <div class="field">
        <label for="email"><?php echo $t['email_label']; ?></label>
        <input type="email" id="email" name="email" required
               value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>"
               placeholder="<?php echo $t['email_placeholder']; ?>">
      </div>

      <div class="field">
        <label for="nachricht"><?php echo $t['message_label']; ?></label>
        <textarea id="nachricht" name="nachricht" required
                  maxlength="<?php echo $max_zeichen; ?>"
                  placeholder="<?php echo $t['message_placeholder']; ?>"><?php echo htmlspecialchars($_POST['nachricht'] ?? ''); ?></textarea>
        <div class="char-count" id="charCount">0 / <?php echo $max_zeichen; ?></div>
      </div>

      <div class="field">
        <label><?php echo $t['attachment_label']; ?></label>
        <div class="file-upload-wrapper" id="dropZone">
          <input type="file" name="anhang" id="anhang" accept="image/jpeg,image/png,image/gif,image/webp,image/bmp">
          <div class="file-upload-icon">📷</div>
          <div class="file-upload-text">Drag & Drop</div>
          <div class="file-upload-hint"><?php echo $t['attachment_hint']; ?></div>
        </div>
        <div class="file-name" id="fileName"></div>
      </div>

      <div class="field">
        <label><?php echo $t['captcha_label']; ?></label>
        <div class="captcha-box">
          <div class="captcha-code"><?php echo $captcha_code; ?></div>
          <div class="captcha-input">
            <input type="text" name="captcha" required
                   placeholder="<?php echo $t['captcha_placeholder']; ?>"
                   autocomplete="off">
          </div>
        </div>
      </div>

      <button type="submit"><?php echo $t['submit']; ?></button>
    </form>
    <?php endif; ?>

    <a href="index.html" class="back-link">&larr; <?php echo $t['back']; ?></a>
  </div>
</div>

<script>
const textarea = document.getElementById('nachricht');
const charCount = document.getElementById('charCount');
const maxChars = <?php echo $max_zeichen; ?>;

if (textarea && charCount) {
  function updateCount() {
    const len = textarea.value.length;
    charCount.textContent = len + ' / ' + maxChars;
    charCount.classList.toggle('over', len > maxChars);
  }
  textarea.addEventListener('input', updateCount);
  updateCount();
}

// File Upload
const fileInput = document.getElementById('anhang');
const dropZone = document.getElementById('dropZone');
const fileNameDisplay = document.getElementById('fileName');
const maxFileSize = <?php echo $max_filesize; ?>;

if (fileInput && dropZone) {
  fileInput.addEventListener('change', handleFileSelect);

  dropZone.addEventListener('dragover', (e) => {
    e.preventDefault();
    dropZone.classList.add('dragover');
  });

  dropZone.addEventListener('dragleave', () => {
    dropZone.classList.remove('dragover');
  });

  dropZone.addEventListener('drop', (e) => {
    e.preventDefault();
    dropZone.classList.remove('dragover');
    if (e.dataTransfer.files.length) {
      fileInput.files = e.dataTransfer.files;
      handleFileSelect();
    }
  });
}

function handleFileSelect() {
  if (fileInput.files.length > 0) {
    const file = fileInput.files[0];
    if (file.size > maxFileSize) {
      fileNameDisplay.textContent = '⚠️ <?php echo addslashes($t['error_file_size']); ?>';
      fileNameDisplay.style.background = '#ffebee';
      fileNameDisplay.style.color = '#c62828';
    } else {
      fileNameDisplay.textContent = '✓ ' + file.name + ' (' + formatFileSize(file.size) + ')';
      fileNameDisplay.style.background = '#e8f5e9';
      fileNameDisplay.style.color = '#2e7d32';
    }
    fileNameDisplay.classList.add('visible');
  } else {
    fileNameDisplay.classList.remove('visible');
  }
}

function formatFileSize(bytes) {
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}
</script>

</body>
</html>
