<?php
declare(strict_types=1);
require __DIR__ . '/bootstrap.php';
method('POST');
require_auth(true);
$in = input_json(1024 * 1024);
$email = $in['email'] ?? null;
if (!is_array($email)) respond(['error' => 'La solicitud no contiene un correo válido.'], 422);
if (empty($config['mail_enabled'])) respond(['error' => 'El envío de correo no está habilitado en el servidor. Configure instalar.php o api/config.override.php.'], 503);
$to = trim((string)($email['to'] ?? ''));
$subject = trim((string)($email['subject'] ?? 'INFORMACIÓN INSTITUCIONAL'));
$body = trim((string)($email['body'] ?? ''));
$cc = trim((string)($email['cc'] ?? ''));
if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) respond(['error' => 'El destinatario no es válido.'], 422);
if ($subject === '' || $body === '') respond(['error' => 'Asunto y mensaje son obligatorios.'], 422);
$strlen = static fn(string $v): int => function_exists('mb_strlen') ? mb_strlen($v, 'UTF-8') : strlen($v);
if ($strlen($subject) > 180 || $strlen($body) > 250000) respond(['error' => 'El contenido del correo supera el límite permitido.'], 413);
$from = trim((string)($config['mail_from'] ?? ''));
if ($from === '' || !filter_var($from, FILTER_VALIDATE_EMAIL)) respond(['error' => 'El correo remitente del servidor no está configurado correctamente.'], 503);
$fromName = trim((string)($config['mail_from_name'] ?? 'SIAPA'));
$reply = trim((string)($config['mail_reply_to'] ?? ''));
$clean = static fn(string $v): string => str_replace(["\r", "\n"], '', $v);
$headers = [];
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-Type: text/plain; charset=UTF-8';
$headers[] = 'From: ' . $clean($fromName) . ' <' . $clean($from) . '>';
if ($reply !== '' && filter_var($reply, FILTER_VALIDATE_EMAIL)) $headers[] = 'Reply-To: ' . $clean($reply);
if ($cc !== '') {
    $validCc = [];
    foreach (array_slice(array_filter(array_map('trim', explode(',', $cc))), 0, (int)($config['mail_max_recipients'] ?? 5)) as $addr) {
        if (filter_var($addr, FILTER_VALIDATE_EMAIL)) $validCc[] = $addr;
    }
    if ($validCc) $headers[] = 'Cc: ' . implode(', ', $validCc);
}
$encodedSubject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
$ok = @mail($to, $encodedSubject, $body, implode("\r\n", $headers));
if (!$ok) respond(['error' => 'El servidor web no pudo entregar el correo. Verifique que la función mail() esté habilitada o use el canal Mailto/WhatsApp.'], 502);
respond(['ok' => true, 'message' => 'Correo aceptado por el servidor institucional.', 'to' => $to, 'sent_at' => gmdate('c')]);
