<?php
/**
 * Handler pentru formularul de programare (bilingual RO/EN).
 * Primește POST din React (FormData) de pe pagina "programare.php".
 * Trimite o notificare către office@petcupartners.ro.
 *
 * Răspuns: JSON { ok: true|false, ref: '...' }. Partea de client face fetch() fire-and-forget —
 * confirmarea către utilizator e afișată deja pe UI înainte să apelam endpoint-ul.
 */

header('Content-Type: application/json; charset=UTF-8');

const DESTINATAR = 'office@petcupartners.ro';

// Limba din POST sau cookie
$lang_post   = isset($_POST['lang']) ? strtolower($_POST['lang']) : '';
$lang_cookie = isset($_COOKIE['lang']) ? strtolower($_COOKIE['lang']) : '';
if (in_array($lang_post, ['ro', 'en'], true)) {
    $lang = $lang_post;
} elseif (in_array($lang_cookie, ['ro', 'en'], true)) {
    $lang = $lang_cookie;
} else {
    $lang = 'ro';
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['ok' => false, 'err' => 'method']);
    exit;
}

// Extract + sanitize
function clean($s) {
    return preg_replace('/[\r\n]+/', ' ', trim((string) $s));
}
$ref     = clean($_POST['ref']    ?? '');
$date    = clean($_POST['date']   ?? '');   // YYYY-MM-DD
$hour    = clean($_POST['hour']   ?? '');   // 9..16
$format  = clean($_POST['format'] ?? '');
$name    = clean($_POST['name']   ?? '');
$email   = clean($_POST['email']  ?? '');
$phone   = clean($_POST['phone']  ?? '');
$matter  = trim($_POST['matter']  ?? '');   // textarea — păstrăm newlines

if ($name === '' || $email === '' || $phone === '' || $matter === '' || $date === '' || $hour === '') {
    echo json_encode(['ok' => false, 'err' => 'missing']);
    exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['ok' => false, 'err' => 'email']);
    exit;
}

// Construim subiect și corp
$is_en = ($lang === 'en');
$subject_h = $is_en
    ? "[Booking] New appointment · {$date} {$hour}:00 · {$name}"
    : "[Programare] Solicitare nouă · {$date} {$hour}:00 · {$name}";

$body  = ($is_en ? "New consultation booking received via the website." : "Solicitare nouă de consultație primită de pe site.") . "\r\n";
$body .= "================================================================\r\n\r\n";
$body .= ($is_en ? "Reference:      " : "Referință:      ") . $ref    . "\r\n";
$body .= ($is_en ? "Date:           " : "Data:           ") . $date   . "\r\n";
$body .= ($is_en ? "Hour:           " : "Ora:            ") . sprintf('%02d:00 – %02d:00', (int)$hour, ((int)$hour)+1) . "\r\n";
$body .= ($is_en ? "Format:         " : "Format:         ") . $format . "\r\n";
$body .= "\r\n----------------------------------------------------------------\r\n";
$body .= ($is_en ? "Name:           " : "Nume:           ") . $name  . "\r\n";
$body .= ($is_en ? "Email:          " : "E-mail:         ") . $email . "\r\n";
$body .= ($is_en ? "Phone:          " : "Telefon:        ") . $phone . "\r\n";
$body .= "\r\n----------------------------------------------------------------\r\n";
$body .= ($is_en ? "Matter:\r\n" : "Detalii caz:\r\n") . $matter . "\r\n";
$body .= "\r\n----------------------------------------------------------------\r\n";
$body .= ($is_en ? "Received at: " : "Primit la:   ") . date('d.m.Y H:i:s') . "\r\n";
$body .= ($is_en ? "IP:          " : "IP:          ") . ($_SERVER['REMOTE_ADDR'] ?? '-') . "\r\n";
$body .= "(lang: {$lang})\r\n";

$host = $_SERVER['HTTP_HOST'] ?? 'petcupartners.ro';
$from_email = 'no-reply@' . preg_replace('/^www\./', '', $host);
$from_label = $is_en ? 'Petcu Partners · Booking' : 'Petcu Partners · Programări';

$headers  = 'From: ' . $from_label . ' <' . $from_email . '>' . "\r\n";
$headers .= 'Reply-To: ' . $name . ' <' . $email . '>' . "\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion() . "\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-Type: text/plain; charset=UTF-8' . "\r\n";
$headers .= 'Content-Transfer-Encoding: 8bit' . "\r\n";

$subject_encoded = '=?UTF-8?B?' . base64_encode($subject_h) . '?=';

$sent = @mail(DESTINATAR, $subject_encoded, $body, $headers);

if ($sent) {
    echo json_encode(['ok' => true, 'ref' => $ref]);
} else {
    error_log('[Booking form] mail() failed for ref ' . $ref . ' (' . $email . ')');
    echo json_encode(['ok' => false, 'err' => 'mail', 'ref' => $ref]);
}
