<?php
// Horliko podlahářství – odeslání kontaktního formuláře
// Odesílá naformátovaný HTML e-mail + přílohy (JPG/PNG/PDF) a vrací JSON.
//
// Nastavte si cílový e-mail:
$TO_EMAIL = 'hornik34@seznam.cz';

header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');

function respond(bool $ok, string $error = ''): void {
  http_response_code($ok ? 200 : 400);
  echo json_encode(
    $ok ? ['ok' => true] : ['ok' => false, 'error' => $error],
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
  );
  exit;
}

// Only POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  respond(false, 'Neplatný požadavek.');
}

// Basic anti-spam (honeypot)
$honeypot = trim((string)($_POST['_honeypot'] ?? ''));
if ($honeypot !== '') {
  // Pretend OK, but do nothing
  respond(true);
}

// Read + validate fields
$name    = trim((string)($_POST['name'] ?? ''));
$email   = trim((string)($_POST['email'] ?? ''));
$phone   = trim((string)($_POST['phone'] ?? ''));
$service = trim((string)($_POST['service'] ?? ''));
$message = trim((string)($_POST['message'] ?? ''));
$gdpr    = (string)($_POST['gdpr'] ?? '');

if (mb_strlen($name) < 2) respond(false, 'Zadejte prosím jméno.');
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) respond(false, 'Zadejte prosím platný e-mail.');
if ($service === '') respond(false, 'Vyberte prosím službu.');
if (mb_strlen($message) < 10) respond(false, 'Popište prosím zakázku (alespoň 10 znaků).');
if ($gdpr === '' && $gdpr !== 'on') respond(false, 'Souhlas GDPR je povinný.');

// Attachments validation
$files = $_FILES['attachments'] ?? null;
$allowed = [
  'image/jpeg' => 'jpg',
  'image/png'  => 'png',
  'application/pdf' => 'pdf',
];
$maxTotal = 5 * 1024 * 1024; // 5 MB

$attachments = [];
$totalSize = 0;

if ($files && isset($files['name']) && is_array($files['name'])) {
  $count = count($files['name']);
  for ($i = 0; $i < $count; $i++) {
    $err = $files['error'][$i];
    if ($err === UPLOAD_ERR_NO_FILE) continue;
    if ($err !== UPLOAD_ERR_OK) respond(false, 'Nepodařilo se nahrát přílohu.');

    $tmp  = $files['tmp_name'][$i];
    $size = (int)$files['size'][$i];
    $orig = (string)$files['name'][$i];

    $totalSize += $size;
    if ($totalSize > $maxTotal) respond(false, 'Celková velikost příloh je max 5 MB.');

    // detect mime
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = $finfo ? finfo_file($finfo, $tmp) : '';
    if ($finfo) finfo_close($finfo);

    if (!isset($allowed[$mime])) respond(false, 'Povolené jsou pouze soubory JPG, PNG nebo PDF.');

    // sanitize filename
    $safeName = preg_replace('/[^a-zA-Z0-9._-]+/', '_', $orig);
    if ($safeName === '' || $safeName === null) $safeName = 'priloha.' . $allowed[$mime];

    $attachments[] = [
      'path' => $tmp,
      'name' => $safeName,
      'mime' => $mime,
    ];
  }
}

// Build email
$subject = 'Poptávka – Horliko podlahářství';
$sentAt = date('Y-m-d H:i:s');

function esc(string $s): string {
  return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

$html = '<!doctype html><html><body style="font-family:Arial,sans-serif;color:#111;">'
      . '<h2 style="margin:0 0 12px;">Nová poptávka z webu</h2>'
      . '<table cellpadding="8" cellspacing="0" style="border-collapse:collapse;width:100%;max-width:700px;">'
      . '<tr><td style="border:1px solid #ddd;background:#f7f7f7;width:220px;"><b>Jméno</b></td><td style="border:1px solid #ddd;">' . esc($name) . '</td></tr>'
      . '<tr><td style="border:1px solid #ddd;background:#f7f7f7;"><b>E-mail</b></td><td style="border:1px solid #ddd;">' . esc($email) . '</td></tr>'
      . '<tr><td style="border:1px solid #ddd;background:#f7f7f7;"><b>Telefon</b></td><td style="border:1px solid #ddd;">' . ($phone !== '' ? esc($phone) : '—') . '</td></tr>'
      . '<tr><td style="border:1px solid #ddd;background:#f7f7f7;"><b>Služba</b></td><td style="border:1px solid #ddd;">' . esc($service) . '</td></tr>'
      . '<tr><td style="border:1px solid #ddd;background:#f7f7f7;"><b>Čas</b></td><td style="border:1px solid #ddd;">' . esc($sentAt) . '</td></tr>'
      . '</table>'
      . '<h3 style="margin:18px 0 8px;">Popis zakázky</h3>'
      . '<div style="white-space:pre-wrap;border:1px solid #ddd;padding:12px;border-radius:8px;max-width:700px;">' . esc($message) . '</div>'
      . '</body></html>';

$fromEmail = 'no-reply@' . ($_SERVER['SERVER_NAME'] ?? 'localhost');
$fromName  = 'Horliko web';

// Prepare headers
$boundary = 'b1_' . md5((string)microtime(true));

$headers = [];
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'From: ' . $fromName . ' <' . $fromEmail . '>';
$headers[] = 'Reply-To: ' . $name . ' <' . $email . '>';
$headers[] = 'X-Mailer: PHP/' . phpversion();
$headers[] = 'Content-Type: multipart/mixed; boundary="' . $boundary . '"';

// Body parts
$body = "--$boundary\r\n";
$body .= "Content-Type: text/html; charset=UTF-8\r\n";
$body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
$body .= $html . "\r\n";

foreach ($attachments as $a) {
  $content = file_get_contents($a['path']);
  if ($content === false) continue;
  $b64 = chunk_split(base64_encode($content));

  $body .= "--$boundary\r\n";
  $body .= 'Content-Type: ' . $a['mime'] . '; name="' . $a['name'] . "\"\r\n";
  $body .= "Content-Transfer-Encoding: base64\r\n";
  $body .= 'Content-Disposition: attachment; filename="' . $a['name'] . "\"\r\n\r\n";
  $body .= $b64 . "\r\n";
}

$body .= "--$boundary--\r\n";

$ok = @mail($TO_EMAIL, '=?UTF-8?B?' . base64_encode($subject) . '?=', $body, implode("\r\n", $headers));

if (!$ok) {
  respond(false, 'Odeslání se nepodařilo. Hosting může blokovat funkci mail().');
}

respond(true);
