<?php
// ============================================================
//  Otto Limser – Formulario de contacto
//  Servidor  : mail.ottolimser.com.ar:465
//  Remitente : enviar@ottolimser.com.ar
//  Destino   : info@ottolimser.com.ar
//  BCC       : wd_archivos@hotmail.com, juanjosecastellano8@gmail.com
// ============================================================

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

function clean(string $val): string {
    return htmlspecialchars(strip_tags(trim($val)), ENT_QUOTES, 'UTF-8');
}

$nombre   = clean($_POST['name']    ?? '');
$email    = clean($_POST['email']   ?? '');
$telefono = clean($_POST['phone']   ?? '');
$mensaje  = clean($_POST['message'] ?? '');

$errores = [];
if ($nombre === '')                              { $errores[] = 'El nombre es obligatorio.'; }
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errores[] = 'El email ingresado no es válido.'; }
if ($mensaje === '')                             { $errores[] = 'El mensaje no puede estar vacío.'; }

if (!empty($errores)) {
    http_response_code(422);
    echo json_encode(['ok' => false, 'errores' => $errores]);
    exit;
}

function smtp_read_all($conn): string {
    $data = '';
    while ($line = fgets($conn, 512)) {
        $data .= $line;
        if (substr($line, 3, 1) === ' ') break;
    }
    return $data;
}

function smtp_cmd($conn, string $cmd): string {
    fwrite($conn, $cmd . "\r\n");
    return smtp_read_all($conn);
}

function smtp_send_mail(): bool {
    global $nombre, $email, $telefono, $mensaje;

    $host = 'mail.ottolimser.com.ar';
    $port = 465;
    $user = 'enviar@ottolimser.com.ar';
    $pass = 'Lospiojos87@';
    $from = 'enviar@ottolimser.com.ar';
    $to   = 'info@ottolimser.com.ar';
    $bcc  = ['wd_archivos@hotmail.com', 'juan.castellano@lapampa.edu.ar', 'hernanfz@hotmail.com'];

    $conn = @fsockopen("ssl://$host", $port, $errno, $errstr, 15);
    if (!$conn) return false;
    stream_set_timeout($conn, 15);

    smtp_read_all($conn);
    smtp_cmd($conn, "EHLO " . gethostname());

    $r = smtp_cmd($conn, "AUTH LOGIN");
    if (strpos($r, '334') === false) { fclose($conn); return false; }
    $r = smtp_cmd($conn, base64_encode($user));
    if (strpos($r, '334') === false) { fclose($conn); return false; }
    $r = smtp_cmd($conn, base64_encode($pass));
    if (strpos($r, '235') === false) { fclose($conn); return false; }

    $r = smtp_cmd($conn, "MAIL FROM:<$from>");
    if (strpos($r, '250') === false) { fclose($conn); return false; }

    smtp_cmd($conn, "RCPT TO:<$to>");
    foreach ($bcc as $b) { smtp_cmd($conn, "RCPT TO:<$b>"); }

    $r = smtp_cmd($conn, "DATA");
    if (strpos($r, '354') === false) { fclose($conn); return false; }

    $boundary = md5(uniqid());
    $subject  = '=?UTF-8?B?' . base64_encode('Consulta web - ' . $nombre) . '?=';

    $txt  = "Nueva consulta desde ottolimser.com.ar\n";
    $txt .= str_repeat('-', 45) . "\n";
    $txt .= "Nombre   : $nombre\n";
    $txt .= "Email    : $email\n";
    $txt .= "Telefono : " . ($telefono ?: '(no informado)') . "\n";
    $txt .= str_repeat('-', 45) . "\n\nMensaje:\n$mensaje\n";

    $html = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head>
<body style="font-family:Arial,sans-serif;color:#333;max-width:600px;margin:auto;">
  <div style="background:#003366;padding:20px;text-align:center;">
    <h2 style="color:#fff;margin:0;">Nueva consulta desde el sitio web</h2>
    <p style="color:#cce0ff;margin:4px 0 0;">ottolimser.com.ar</p>
  </div>
  <div style="padding:24px;border:1px solid #ddd;border-top:none;">
    <table style="width:100%;border-collapse:collapse;">
      <tr style="background:#f4f4f4;">
        <td style="padding:10px;font-weight:bold;width:120px;">Nombre</td>
        <td style="padding:10px;">' . $nombre . '</td>
      </tr>
      <tr>
        <td style="padding:10px;font-weight:bold;">Email</td>
        <td style="padding:10px;"><a href="mailto:' . $email . '">' . $email . '</a></td>
      </tr>
      <tr style="background:#f4f4f4;">
        <td style="padding:10px;font-weight:bold;">Telefono</td>
        <td style="padding:10px;">' . ($telefono ?: '<em>No informado</em>') . '</td>
      </tr>
    </table>
    <div style="margin-top:20px;">
      <p style="font-weight:bold;">Consulta:</p>
      <div style="background:#f9f9f9;border-left:4px solid #003366;padding:14px;white-space:pre-wrap;">' . nl2br($mensaje) . '</div>
    </div>
  </div>
  <div style="padding:12px;text-align:center;font-size:12px;color:#999;">
    Mensaje generado automaticamente - ottolimser.com.ar
  </div>
</body></html>';

    $headers  = "Date: " . date('r') . "\r\n";
    $headers .= "Message-ID: <" . md5(uniqid(rand(), true)) . "@ottolimser.com.ar>\r\n";
    $headers .= "From: \"Formulario Web - Otto Limser\" <$from>\r\n";
    $headers .= "Reply-To: $email\r\n";
    $headers .= "To: $to\r\n";
    $headers .= "Subject: $subject\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: multipart/alternative; boundary=\"$boundary\"\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";

    $body  = "--$boundary\r\n";
    $body .= "Content-Type: text/plain; charset=UTF-8\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $body .= chunk_split(base64_encode($txt)) . "\r\n";
    $body .= "--$boundary\r\n";
    $body .= "Content-Type: text/html; charset=UTF-8\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $body .= chunk_split(base64_encode($html)) . "\r\n";
    $body .= "--$boundary--\r\n";

    fwrite($conn, $headers . "\r\n" . $body . "\r\n.\r\n");
    $result = smtp_read_all($conn);

    smtp_cmd($conn, "QUIT");
    fclose($conn);

    return strpos($result, '250') !== false;
}

$enviado = smtp_send_mail();

if ($enviado) {
    echo json_encode(['ok' => true, 'mensaje' => '¡Gracias! Su consulta fue enviada correctamente. Nos comunicaremos en menos de 24 hs.']);
} else {
    http_response_code(500);
    echo json_encode(['ok' => false, 'errores' => ['No se pudo enviar el correo. Por favor contáctenos por teléfono.']]);
}