<?php
declare(strict_types=1);

namespace App\Services;

use App\Repositories\Container;

/**
 * Email orchestration. Uses the bundled Smtp client (Gmail-ready) and
 * renders a shared branded template so every notification looks premium.
 */
class Email
{
    /**
     * Low-level send. Never throws — logs and returns false on failure.
     * SMTP settings are read from admin settings (data/settings.json) first,
     * falling back to config.php values.
     */
    public static function send(string|array $to, string $subject, string $htmlBody, array $opts = []): bool
    {
        $cfg = config('mail');
        // Admin-editable SMTP settings override config.php
        $dbSmtp = Container::settings()->get()['smtp'] ?? [];

        $from = $opts['from']     ?? ($dbSmtp['from_email'] ?? $cfg['from_email'] ?? 'no-reply@localhost');
        $name = $opts['fromName'] ?? ($dbSmtp['from_name']  ?? $cfg['from_name']  ?? 'Mystic Art Tattoo');
        $bcc  = $opts['bcc']      ?? [];
        $attachments = $opts['attachments'] ?? [];

        $smtpHost = $dbSmtp['host']     ?? $cfg['smtp']['host']     ?? '';
        $smtpPort = (int)($dbSmtp['port'] ?? $cfg['smtp']['port'] ?? 587);
        $smtpUser = $dbSmtp['username'] ?? $cfg['smtp']['username'] ?? '';
        $smtpPass = $dbSmtp['password'] ?? $cfg['smtp']['password'] ?? '';

        if ($smtpHost && $smtpUser) {
            $client = new Smtp($smtpHost, $smtpPort, (string)$smtpUser, (string)$smtpPass);
            $ok = $client->send($from, $name, $to, $subject, $htmlBody, $bcc, null, $attachments);
            if (!$ok) error_log('[Email] SMTP failed: ' . $client->lastError());
            return $ok;
        }

        // Fallback: PHP's mail()
        $headers = "MIME-Version: 1.0\r\nContent-type: text/html; charset=UTF-8\r\nFrom: {$name} <{$from}>\r\n";
        $target = is_array($to) ? implode(', ', $to) : $to;
        $ok = @mail($target, $subject, $htmlBody, $headers);
        if (!$ok) error_log('[Email] native mail() failed for ' . $target);
        return $ok;
    }

    /** Shared branded HTML shell. Pass $content as inner HTML. */
    public static function template(string $title, string $content, ?string $ctaUrl = null, ?string $ctaLabel = null): string
    {
        $settings = Container::settings()->get();
        $year = date('Y');
        $shopName = e($settings['shop_name'] ?? 'Mystic Art Tattoo');
        $address  = nl2br(e($settings['address'] ?? ''));
        $phone    = e($settings['phone'] ?? '');
        $email    = e($settings['email'] ?? '');

        $cta = '';
        if ($ctaUrl && $ctaLabel) {
            $cta = <<<HTML
<table role="presentation" cellspacing="0" cellpadding="0" border="0" align="left" style="margin:28px 0">
  <tr><td style="background:#d4af37;border-radius:6px">
    <a href="{$ctaUrl}" style="display:inline-block;padding:14px 28px;color:#0a0a0a;text-decoration:none;font-family:'Inter',Arial,sans-serif;font-size:12px;font-weight:700;letter-spacing:2px;text-transform:uppercase">{$ctaLabel}</a>
  </td></tr>
</table>
HTML;
        }

        return <<<HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{$title}</title>
</head>
<body style="margin:0;padding:0;background:#0a0a0a;font-family:'Inter',Arial,sans-serif;color:#f5f5f2;-webkit-font-smoothing:antialiased">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="background:#0a0a0a">
    <tr>
      <td align="center" style="padding:40px 20px">
        <table role="presentation" width="560" cellspacing="0" cellpadding="0" border="0" style="max-width:560px;width:100%;background:#111113;border:1px solid rgba(212,175,55,0.25);border-radius:14px;overflow:hidden">
          <!-- Header -->
          <tr><td style="padding:36px 44px 24px;border-bottom:1px solid rgba(255,255,255,0.06);text-align:center">
            <img src="https://static.wixstatic.com/media/a23fe6_2d243418b70b4e748fc66a7cbfa8bda6~mv2.png" alt="Mystic Art Tattoo" width="140" style="display:inline-block;width:140px;height:auto;max-width:140px">
          </td></tr>

          <!-- Title -->
          <tr><td style="padding:32px 44px 8px">
            <div style="font-family:'Inter',Arial,sans-serif;font-size:10px;letter-spacing:3px;color:#d4af37;text-transform:uppercase">{$title}</div>
          </td></tr>

          <!-- Body -->
          <tr><td style="padding:0 44px 36px;color:#f5f5f2;font-family:'Inter',Arial,sans-serif;font-size:15px;line-height:1.7">
            {$content}
            {$cta}
          </td></tr>

          <!-- Footer -->
          <tr><td style="padding:28px 44px;background:#0a0a0a;border-top:1px solid rgba(255,255,255,0.06);text-align:center;font-family:'Inter',Arial,sans-serif;font-size:12px;color:rgba(245,245,242,0.45)">
            <div style="color:#d4af37;letter-spacing:2px;text-transform:uppercase;font-size:10px;margin-bottom:8px">Visit the studio</div>
            <div style="line-height:1.6">{$address}</div>
            <div style="margin-top:6px">{$phone} · {$email}</div>
            <div style="margin-top:16px;color:rgba(245,245,242,0.25);font-size:10px">&copy; {$year} {$shopName}</div>
          </td></tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
HTML;
    }

    // ---------- High-level notification flows ----------

    public static function bookingRequested(array $customer, array $appointment, string $intakeUrl): bool
    {
        $lang = locale();
        $first = e($customer['first_name'] ?? '');
        $when = !empty($appointment['start_at'])
            ? (new \DateTimeImmutable($appointment['start_at']))->format('l, F j · g:i A')
            : '—';

        if ($lang === 'es') {
            $title = 'Reserva recibida';
            $subject = 'Tu solicitud de cita · Mystic Art Tattoo';
            $ctaLabel = 'Completar mi formulario';
            $body = <<<HTML
<p style="font-size:22px;font-family:Georgia,serif;color:#f5f5f2;margin:0 0 18px">Hola {$first},</p>
<p>Gracias por reservar con Mystic Art Tattoo. Hemos recibido tu solicitud y la revisaremos en las próximas 24 horas.</p>
<div style="margin:24px 0;padding:20px;background:rgba(212,175,55,0.06);border-left:3px solid #d4af37;border-radius:4px">
  <div style="font-size:10px;letter-spacing:2px;color:#d4af37;text-transform:uppercase;margin-bottom:6px">Tu cita</div>
  <div style="font-size:18px;color:#f5f5f2">{$when}</div>
</div>
<p>Mientras esperas, por favor completa tu formulario de admisión en línea (historia médica, exoneración, ubicación del tatuaje). Así ahorras tiempo el día de tu sesión — solo firmarás en persona cuando llegues al estudio.</p>
HTML;
        } else {
            $title = 'Booking received';
            $subject = 'Your appointment request · Mystic Art Tattoo';
            $ctaLabel = 'Fill out my intake form';
            $body = <<<HTML
<p style="font-size:22px;font-family:Georgia,serif;color:#f5f5f2;margin:0 0 18px">Hey {$first},</p>
<p>Thanks for booking with Mystic Art Tattoo. We've received your request and will review it within the next 24 hours.</p>
<div style="margin:24px 0;padding:20px;background:rgba(212,175,55,0.06);border-left:3px solid #d4af37;border-radius:4px">
  <div style="font-size:10px;letter-spacing:2px;color:#d4af37;text-transform:uppercase;margin-bottom:6px">Your appointment</div>
  <div style="font-size:18px;color:#f5f5f2">{$when}</div>
</div>
<p>While you wait, please fill out your intake form online (medical history, liability waiver, tattoo placement). It'll save you time on the day of your session — you'll only sign it in person when you arrive at the studio.</p>
HTML;
        }

        $html = self::template($title, $body, $intakeUrl, $ctaLabel);
        // Send ONLY to the customer. Staff gets a separate branded alert.
        return self::send((string)($customer['email'] ?? ''), $subject, $html);
    }

    /**
     * Separate branded alert to the shop / staff when a new booking comes in.
     * Contains customer details and a link to open the appointment in the Shop Hub.
     */
    public static function staffNewBookingAlert(array $customer, array $appointment, ?array $artist, string $hubUrl): bool
    {
        $notify = self::allStaffEmails($appointment['artist_id'] ?? null);
        if (empty($notify)) return true;

        $name  = e(trim(($customer['first_name'] ?? '') . ' ' . ($customer['last_name'] ?? '')));
        $email = e($customer['email'] ?? '');
        $phone = e($customer['phone'] ?? '');
        $addr  = e(trim(($customer['address_line'] ?? '') . ' ' . ($customer['city'] ?? '') . ' ' . ($customer['state'] ?? '') . ' ' . ($customer['zip'] ?? '')));
        $when  = !empty($appointment['start_at'])
            ? (new \DateTimeImmutable($appointment['start_at']))->format('l, F j · g:i A')
            : '—';
        $artistName = e($artist['display_name'] ?? 'No preference');

        $title = 'New booking alert';
        $rawName = trim(($customer['first_name'] ?? '') . ' ' . ($customer['last_name'] ?? ''));
        $subject = "🔔 New booking: " . ($rawName ?: 'customer') . " with " . ($artist['display_name'] ?? 'No preference');
        $body = <<<HTML
<p style="font-size:22px;font-family:Georgia,serif;color:#f5f5f2;margin:0 0 18px">You've got a new booking</p>
<p style="color:rgba(245,245,242,0.75)">Someone just booked an appointment through the site. Here are the details:</p>

<div style="margin:24px 0;padding:20px;background:rgba(212,175,55,0.08);border-left:3px solid #d4af37;border-radius:4px">
  <table role="presentation" cellspacing="0" cellpadding="0" border="0" style="width:100%;font-family:Inter,Arial,sans-serif;font-size:14px;color:#f5f5f2">
    <tr><td style="padding:6px 0;color:#d4af37;text-transform:uppercase;letter-spacing:1px;font-size:10px;width:110px">Customer</td><td style="padding:6px 0">{$name}</td></tr>
    <tr><td style="padding:6px 0;color:#d4af37;text-transform:uppercase;letter-spacing:1px;font-size:10px">Email</td><td style="padding:6px 0"><a href="mailto:{$email}" style="color:#f5f5f2;text-decoration:none">{$email}</a></td></tr>
    <tr><td style="padding:6px 0;color:#d4af37;text-transform:uppercase;letter-spacing:1px;font-size:10px">Phone</td><td style="padding:6px 0"><a href="tel:{$phone}" style="color:#f5f5f2;text-decoration:none">{$phone}</a></td></tr>
    <tr><td style="padding:6px 0;color:#d4af37;text-transform:uppercase;letter-spacing:1px;font-size:10px;vertical-align:top">Address</td><td style="padding:6px 0;color:rgba(245,245,242,0.7)">{$addr}</td></tr>
    <tr><td style="padding:6px 0;color:#d4af37;text-transform:uppercase;letter-spacing:1px;font-size:10px">Artist</td><td style="padding:6px 0">{$artistName}</td></tr>
    <tr><td style="padding:6px 0;color:#d4af37;text-transform:uppercase;letter-spacing:1px;font-size:10px">When</td><td style="padding:6px 0">{$when}</td></tr>
  </table>
</div>

<p style="color:rgba(245,245,242,0.65);font-size:13px">Open it in the Shop Hub to review and approve. Once you approve, the customer will receive a confirmation email automatically.</p>
HTML;

        $html = self::template($title, $body, $hubUrl, 'Open in Shop Hub');
        return self::send($notify, $subject, $html);
    }

    public static function bookingApproved(array $customer, array $appointment, ?string $staffNotes = null): bool
    {
        $lang = locale();
        $first = e($customer['first_name'] ?? '');
        $when = !empty($appointment['start_at'])
            ? (new \DateTimeImmutable($appointment['start_at']))->format('l, F j · g:i A')
            : '—';
        $settings = Container::settings()->get();
        $addr = e($settings['address'] ?? '');
        $mapLink = 'https://www.google.com/maps?q=' . urlencode($settings['address'] ?? '');

        $notesHtml = '';
        if ($staffNotes) {
            $notesEsc = e($staffNotes);
            $notesHtml = <<<HTML
<div style="margin:20px 0;padding:16px 20px;background:rgba(255,255,255,0.04);border-left:3px solid rgba(212,175,55,0.5);border-radius:4px">
  <div style="font-size:10px;letter-spacing:2px;color:#d4af37;text-transform:uppercase;margin-bottom:6px">Note from us</div>
  <div style="font-size:14px;color:rgba(245,245,242,0.85);line-height:1.6;font-style:italic">{$notesEsc}</div>
</div>
HTML;
        }

        if ($lang === 'es') {
            $title = 'Cita confirmada';
            $subject = '¡Tu cita está confirmada! · Mystic Art Tattoo';
            if ($staffNotes) {
                $notesHtml = str_replace('Note from us', 'Nota de nuestra parte', $notesHtml);
            }
            $body = <<<HTML
<p style="font-size:22px;font-family:Georgia,serif;color:#f5f5f2;margin:0 0 18px">¡{$first}, todo listo!</p>
<p>Tu cita en Mystic Art Tattoo ha sido <strong style="color:#d4af37">confirmada</strong>.</p>
<div style="margin:24px 0;padding:20px;background:rgba(212,175,55,0.06);border-left:3px solid #d4af37;border-radius:4px">
  <div style="font-size:10px;letter-spacing:2px;color:#d4af37;text-transform:uppercase;margin-bottom:6px">Fecha y hora</div>
  <div style="font-size:18px;color:#f5f5f2">{$when}</div>
  <div style="font-size:10px;letter-spacing:2px;color:#d4af37;text-transform:uppercase;margin:14px 0 6px">Dirección</div>
  <div style="font-size:14px;color:rgba(245,245,242,0.7);line-height:1.6">{$addr}</div>
</div>
{$notesHtml}
<p style="color:rgba(245,245,242,0.7);font-size:13px">Por favor ven con tiempo y descansado. Trae tu identificación con foto.</p>
HTML;
            $cta = 'Cómo llegar';
        } else {
            $title = 'Appointment confirmed';
            $subject = 'Your appointment is confirmed · Mystic Art Tattoo';
            $body = <<<HTML
<p style="font-size:22px;font-family:Georgia,serif;color:#f5f5f2;margin:0 0 18px">{$first}, you're all set.</p>
<p>Your appointment at Mystic Art Tattoo has been <strong style="color:#d4af37">confirmed</strong>.</p>
<div style="margin:24px 0;padding:20px;background:rgba(212,175,55,0.06);border-left:3px solid #d4af37;border-radius:4px">
  <div style="font-size:10px;letter-spacing:2px;color:#d4af37;text-transform:uppercase;margin-bottom:6px">When</div>
  <div style="font-size:18px;color:#f5f5f2">{$when}</div>
  <div style="font-size:10px;letter-spacing:2px;color:#d4af37;text-transform:uppercase;margin:14px 0 6px">Where</div>
  <div style="font-size:14px;color:rgba(245,245,242,0.7);line-height:1.6">{$addr}</div>
</div>
{$notesHtml}
<p style="color:rgba(245,245,242,0.7);font-size:13px">Please arrive on time, well rested, and with a valid photo ID.</p>
HTML;
            $cta = 'Get directions';
        }

        $html = self::template($title, $body, $mapLink, $cta);
        // BCC all staff so they know the appointment was confirmed
        $staffBcc = self::allStaffEmails($appointment['artist_id'] ?? null);
        return self::send((string)($customer['email'] ?? ''), $subject, $html, ['bcc' => $staffBcc]);
    }

    /**
     * Send the aftercare email + a copy of the signed intake form (as HTML).
     * Fired after the appointment is marked COMPLETED.
     */
    public static function aftercareAndFormCopy(array $customer, array $appointment, array $form): bool
    {
        $lang = locale();
        $first = e($customer['first_name'] ?? '');
        $artistName = '';
        if (!empty($appointment['artist_id'])) {
            $art = Container::artists()->find($appointment['artist_id']);
            $artistName = e($art['display_name'] ?? '');
        }

        $stepsHtml = '';
        for ($i = 1; $i <= 13; $i++) {
            $step = t('page.aftercare.step_' . $i);
            if ($step === 'page.aftercare.step_' . $i) continue;
            $stepsHtml .= '<li style="margin:0 0 10px;line-height:1.7"><span style="color:#d4af37;font-weight:600">' . $i . '.</span> ' . e($step) . '</li>';
        }

        // Google review URL from settings (or hardcoded fallback)
        $settings = Container::settings()->get();
        $reviewUrl = $settings['google_review_url'] ?? 'https://www.google.com/search?q=Mystic+Art+tattoo+shop+Reviews#lrd=0x89c30b667ccfa9e3:0xf84887e3506b6b5b,3,,,,';

        if ($lang === 'es') {
            $title = 'Cuidados + copia de tu formulario';
            $subject = 'Cuidados posteriores · Mystic Art Tattoo';
            $greeting = "¡{$first}, gracias por tu visita!";
            $intro = 'Fue un placer trabajar contigo' . ($artistName ? " — {$artistName} espera que disfrutes tu nueva pieza." : '.') . ' Aquí están tus instrucciones de cuidado para los próximos 30 días, junto con una copia de tu formulario firmado.';
            $stepsLabel = 'Instrucciones de cuidado';
            $formLabel = 'Copia de tu formulario';
            $reviewTitle = '¿Te gustó tu experiencia?';
            $reviewBody = 'Tu opinión nos ayuda a crecer. Si tuviste una buena experiencia, nos encantaría que dejaras una reseña en Google — toma solo un minuto.';
            $reviewBtn = 'Dejar una reseña';
            $shareTitle = 'Comparte tu tatuaje';
            $shareBody = 'Etiquétanos en Instagram <strong style="color:#d4af37">@tattoostudiomysticart</strong> — nos encanta ver cómo lucen nuestros trabajos ya sanados.';
        } else {
            $title = 'Aftercare + your form';
            $subject = 'Aftercare instructions · Mystic Art Tattoo';
            $greeting = "{$first}, thanks for coming in!";
            $intro = 'It was great working with you' . ($artistName ? " — {$artistName} hopes you love your new piece." : '.') . ' Here are your care instructions for the next 30 days, along with a copy of your signed intake form.';
            $stepsLabel = 'Aftercare instructions';
            $formLabel = 'A copy of your form';
            $reviewTitle = 'Enjoyed your experience?';
            $reviewBody = 'Your feedback helps us grow. If you had a great time, we\'d love it if you left us a quick Google review — it only takes a minute.';
            $reviewBtn = 'Leave a review';
            $shareTitle = 'Share your tattoo';
            $shareBody = 'Tag us on Instagram <strong style="color:#d4af37">@tattoostudiomysticart</strong> — we love seeing our work healed.';
        }

        $formHtml = self::renderIntakeSummary($form, $customer);
        $body = <<<HTML
<p style="font-size:22px;font-family:Georgia,serif;color:#f5f5f2;margin:0 0 18px">{$greeting}</p>
<p>{$intro}</p>

<h3 style="color:#d4af37;font-family:'Inter',Arial,sans-serif;font-size:11px;letter-spacing:3px;text-transform:uppercase;margin:28px 0 12px">{$stepsLabel}</h3>
<ol style="padding-left:0;list-style:none;color:rgba(245,245,242,0.85);font-size:14px">
{$stepsHtml}
</ol>

<!-- Google review CTA -->
<div style="margin:36px 0;padding:28px;background:rgba(212,175,55,0.06);border:1px solid rgba(212,175,55,0.2);border-radius:12px;text-align:center">
  <div style="font-size:28px;margin-bottom:12px">⭐</div>
  <div style="font-size:16px;font-weight:600;color:#f5f5f2;margin-bottom:8px">{$reviewTitle}</div>
  <p style="font-size:13px;color:rgba(245,245,242,0.6);margin:0 0 18px;line-height:1.6">{$reviewBody}</p>
  <a href="{$reviewUrl}" style="display:inline-block;padding:14px 32px;background:#d4af37;color:#0a0a0a;text-decoration:none;font-family:'Inter',Arial,sans-serif;font-size:12px;font-weight:700;letter-spacing:2px;text-transform:uppercase;border-radius:6px">{$reviewBtn}</a>
</div>

<!-- Share on Instagram -->
<div style="margin:24px 0;padding:20px;background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06);border-radius:8px;text-align:center">
  <div style="font-size:11px;letter-spacing:3px;color:#d4af37;text-transform:uppercase;margin-bottom:8px">{$shareTitle}</div>
  <p style="font-size:13px;color:rgba(245,245,242,0.55);margin:0;line-height:1.6">{$shareBody}</p>
</div>

<h3 style="color:#d4af37;font-family:'Inter',Arial,sans-serif;font-size:11px;letter-spacing:3px;text-transform:uppercase;margin:36px 0 12px">{$formLabel}</h3>
<div style="padding:20px;background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.08);border-radius:6px;font-size:13px;line-height:1.7">
{$formHtml}
</div>
HTML;

        $html = self::template($title, $body);
        return self::send((string)($customer['email'] ?? ''), $subject, $html);
    }

    /**
     * Staff proposed a new time — ask the customer to approve or reject.
     */
    public static function rescheduleProposal(array $customer, array $appointment, string $baseUrl): bool
    {
        $lang  = locale();
        $first = e($customer['first_name'] ?? '');
        $token = $appointment['reschedule_token'] ?? '';

        $oldWhen = !empty($appointment['start_at'])
            ? (new \DateTimeImmutable($appointment['start_at']))->format('l, F j · g:i A')
            : '—';
        $newWhen = !empty($appointment['proposed_start_at'])
            ? (new \DateTimeImmutable($appointment['proposed_start_at']))->format('l, F j · g:i A')
            : '—';
        $reason  = e($appointment['reschedule_reason'] ?? '');

        $approveUrl = $baseUrl . '/reschedule/' . rawurlencode($token) . '/approve';
        $rejectUrl  = $baseUrl . '/reschedule/' . rawurlencode($token) . '/reject';

        $reasonHtml = $reason ? "<div style=\"margin:14px 0;padding:14px 18px;background:rgba(255,255,255,0.04);border-left:3px solid rgba(212,175,55,0.5);border-radius:4px\"><div style=\"font-size:10px;letter-spacing:2px;color:#d4af37;text-transform:uppercase;margin-bottom:4px\">" . ($lang === 'es' ? 'Motivo' : 'Reason') . "</div><div style=\"font-size:14px;color:rgba(245,245,242,0.85);font-style:italic\">{$reason}</div></div>" : '';

        $rejectLabel = $lang === 'es' ? 'No, quiero otro horario' : 'No, I\'d like a different time';

        if ($lang === 'es') {
            $title   = 'Cambio de horario propuesto';
            $subject = 'Cambio de horario para tu cita · Mystic Art Tattoo';
            $ctaLabel = 'Sí, acepto el nuevo horario';
            $body = <<<HTML
<p style="font-size:22px;font-family:Georgia,serif;color:#f5f5f2;margin:0 0 18px">Hola {$first},</p>
<p>Nuestro equipo necesita proponer un cambio de horario para tu cita:</p>
<div style="margin:24px 0;padding:20px;background:rgba(212,175,55,0.06);border-left:3px solid #d4af37;border-radius:4px">
  <div style="font-size:10px;letter-spacing:2px;color:#d4af37;text-transform:uppercase;margin-bottom:6px">Horario original</div>
  <div style="font-size:16px;color:rgba(245,245,242,0.5);text-decoration:line-through">{$oldWhen}</div>
  <div style="font-size:10px;letter-spacing:2px;color:#d4af37;text-transform:uppercase;margin:16px 0 6px">Nuevo horario propuesto</div>
  <div style="font-size:18px;color:#f5f5f2">{$newWhen}</div>
</div>
{$reasonHtml}
<p style="color:rgba(245,245,242,0.7);font-size:14px;margin:20px 0">Si el nuevo horario funciona, haz clic en "Acepto". Si prefieres otro horario, haz clic en "No" y nos pondremos en contacto.</p>
HTML;
        } else {
            $title   = 'Proposed time change';
            $subject = 'Time change for your appointment · Mystic Art Tattoo';
            $ctaLabel = 'Yes, I accept the new time';
            $body = <<<HTML
<p style="font-size:22px;font-family:Georgia,serif;color:#f5f5f2;margin:0 0 18px">Hey {$first},</p>
<p>Our team needs to propose a time change for your appointment:</p>
<div style="margin:24px 0;padding:20px;background:rgba(212,175,55,0.06);border-left:3px solid #d4af37;border-radius:4px">
  <div style="font-size:10px;letter-spacing:2px;color:#d4af37;text-transform:uppercase;margin-bottom:6px">Original time</div>
  <div style="font-size:16px;color:rgba(245,245,242,0.5);text-decoration:line-through">{$oldWhen}</div>
  <div style="font-size:10px;letter-spacing:2px;color:#d4af37;text-transform:uppercase;margin:16px 0 6px">Proposed new time</div>
  <div style="font-size:18px;color:#f5f5f2">{$newWhen}</div>
</div>
{$reasonHtml}
<p style="color:rgba(245,245,242,0.7);font-size:14px;margin:20px 0">If the new time works for you, click "Accept". If you'd prefer a different time, click "No" and we'll reach out to you.</p>
HTML;
        }

        // Two CTAs: approve (gold) + reject (ghost)
        $body .= <<<HTML
<table role="presentation" cellspacing="0" cellpadding="0" border="0" style="margin:28px 0">
  <tr>
    <td style="background:#d4af37;border-radius:6px;padding:0">
      <a href="{$approveUrl}" style="display:inline-block;padding:14px 28px;color:#0a0a0a;text-decoration:none;font-family:'Inter',Arial,sans-serif;font-size:12px;font-weight:700;letter-spacing:2px;text-transform:uppercase">{$ctaLabel}</a>
    </td>
    <td style="width:12px"></td>
    <td style="border:1px solid rgba(245,245,242,0.2);border-radius:6px;padding:0">
      <a href="{$rejectUrl}" style="display:inline-block;padding:13px 24px;color:#f5f5f2;text-decoration:none;font-family:'Inter',Arial,sans-serif;font-size:12px;font-weight:500;letter-spacing:1px;text-transform:uppercase">{$rejectLabel}</a>
    </td>
  </tr>
</table>
HTML;

        $html = self::template($title, $body);
        return self::send((string)($customer['email'] ?? ''), $subject, $html);
    }

    private static function renderIntakeSummary(array $form, array $customer): string
    {
        $gi = (array)($form['general_info'] ?? []);
        $lines = [];
        $add = function (string $label, $value) use (&$lines) {
            if ($value === null || $value === '' || $value === []) return;
            $val = is_array($value) ? implode(', ', $value) : (string)$value;
            $lines[] = '<div style="margin:6px 0"><span style="color:#d4af37;font-size:10px;letter-spacing:2px;text-transform:uppercase">' . e($label) . '</span><br><span style="color:#f5f5f2">' . e($val) . '</span></div>';
        };
        $add('Name', trim(($gi['first_name'] ?? '') . ' ' . ($gi['last_name'] ?? '')));
        $add('Email', $gi['email'] ?? ($customer['email'] ?? ''));
        $add('Phone', $gi['phone'] ?? ($customer['phone'] ?? ''));
        $add('Date of birth', $gi['date_of_birth'] ?? '');
        $add('Address', trim(($gi['address'] ?? '') . ' ' . ($gi['city'] ?? '') . ' ' . ($gi['state'] ?? '') . ' ' . ($gi['zip'] ?? '')));
        $add('Body part', $form['body_part'] ?? '');
        $add('Pigments', $form['pigments'] ?? '');
        $add('Medical conditions', $form['medical_conditions'] ?? []);
        $add('Medication notes', $form['medication_notes'] ?? '');
        $add('Signed at', $form['signed_at'] ?? '');
        return implode('', $lines) ?: '<em style="color:rgba(245,245,242,0.4)">No details</em>';
    }

    /**
     * Notify the customer their appointment was canceled.
     * If $reason is provided, it's shown in the email; otherwise just a generic notice.
     */
    public static function appointmentCanceled(array $customer, array $appointment, ?array $artist, ?string $reason = null): bool
    {
        $lang  = locale();
        $first = e($customer['first_name'] ?? '');
        $when  = !empty($appointment['start_at'])
            ? (new \DateTimeImmutable($appointment['start_at']))->format('l, F j · g:i A')
            : '—';
        $artistName = e($artist['display_name'] ?? '');

        $reasonHtml = '';
        if ($reason) {
            $reasonEsc = e($reason);
            $lbl = $lang === 'es' ? 'Motivo' : 'Reason';
            $reasonHtml = "<div style=\"margin:20px 0;padding:16px 20px;background:rgba(255,255,255,0.04);border-left:3px solid rgba(239,68,68,0.4);border-radius:4px\"><div style=\"font-size:10px;letter-spacing:2px;color:rgba(239,68,68,0.7);text-transform:uppercase;margin-bottom:4px\">{$lbl}</div><div style=\"font-size:14px;color:rgba(245,245,242,0.8);font-style:italic\">{$reasonEsc}</div></div>";
        }

        if ($lang === 'es') {
            $title   = 'Cita cancelada';
            $subject = 'Tu cita ha sido cancelada · Mystic Art Tattoo';
            $body = <<<HTML
<p style="font-size:22px;font-family:Georgia,serif;color:#f5f5f2;margin:0 0 18px">Hola {$first},</p>
<p>Lamentamos informarte que tu cita ha sido <strong style="color:#f87171">cancelada</strong>.</p>
<div style="margin:24px 0;padding:20px;background:rgba(239,68,68,0.06);border-left:3px solid rgba(239,68,68,0.4);border-radius:4px">
  <div style="font-size:10px;letter-spacing:2px;color:rgba(239,68,68,0.7);text-transform:uppercase;margin-bottom:6px">Cita cancelada</div>
  <div style="font-size:16px;color:rgba(245,245,242,0.5);text-decoration:line-through">{$when}</div>
  <div style="font-size:12px;color:rgba(245,245,242,0.4);margin-top:4px">{$artistName}</div>
</div>
{$reasonHtml}
<p style="color:rgba(245,245,242,0.6);font-size:13px">Si deseas reprogramar, puedes reservar una nueva cita en nuestro sitio web o contactarnos directamente.</p>
HTML;
            $cta = 'Reservar nueva cita';
        } else {
            $title   = 'Appointment canceled';
            $subject = 'Your appointment has been canceled · Mystic Art Tattoo';
            $body = <<<HTML
<p style="font-size:22px;font-family:Georgia,serif;color:#f5f5f2;margin:0 0 18px">Hey {$first},</p>
<p>We're sorry to let you know that your appointment has been <strong style="color:#f87171">canceled</strong>.</p>
<div style="margin:24px 0;padding:20px;background:rgba(239,68,68,0.06);border-left:3px solid rgba(239,68,68,0.4);border-radius:4px">
  <div style="font-size:10px;letter-spacing:2px;color:rgba(239,68,68,0.7);text-transform:uppercase;margin-bottom:6px">Canceled appointment</div>
  <div style="font-size:16px;color:rgba(245,245,242,0.5);text-decoration:line-through">{$when}</div>
  <div style="font-size:12px;color:rgba(245,245,242,0.4);margin-top:4px">{$artistName}</div>
</div>
{$reasonHtml}
<p style="color:rgba(245,245,242,0.6);font-size:13px">If you'd like to reschedule, you can book a new appointment on our website or contact us directly.</p>
HTML;
            $cta = 'Book a new appointment';
        }

        $bookUrl = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http')
            . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . '/book';
        $html = self::template($title, $body, $bookUrl, $cta);
        return self::send((string)($customer['email'] ?? ''), $subject, $html);
    }

    /**
     * Internal staff + artist alert when an appointment is canceled.
     * Always includes the full reason.
     */
    public static function staffCancelAlert(?array $customer, array $appointment, ?array $artist, string $canceledBy, string $reason): bool
    {
        $recipients = self::allStaffEmails($appointment['artist_id'] ?? null);
        if (empty($recipients)) return true;

        $custName   = $customer ? e(trim(($customer['first_name'] ?? '') . ' ' . ($customer['last_name'] ?? ''))) : 'Unknown';
        $when       = !empty($appointment['start_at'])
            ? (new \DateTimeImmutable($appointment['start_at']))->format('l, F j · g:i A')
            : '—';
        $artistName = e($artist['display_name'] ?? 'No preference');
        $reasonEsc  = $reason ? e($reason) : '<em style="color:rgba(245,245,242,0.3)">No reason given</em>';
        $byEsc      = e($canceledBy);

        $subject = "❌ Appointment canceled: {$custName}";
        $body = <<<HTML
<p style="font-size:22px;font-family:Georgia,serif;color:#f5f5f2;margin:0 0 18px">Appointment canceled</p>
<div style="margin:20px 0;padding:20px;background:rgba(239,68,68,0.06);border-left:3px solid rgba(239,68,68,0.4);border-radius:4px">
  <table role="presentation" cellspacing="0" cellpadding="0" border="0" style="width:100%;font-family:Inter,Arial,sans-serif;font-size:14px;color:#f5f5f2">
    <tr><td style="padding:5px 0;color:rgba(239,68,68,0.7);text-transform:uppercase;letter-spacing:1px;font-size:10px;width:100px">Customer</td><td style="padding:5px 0">{$custName}</td></tr>
    <tr><td style="padding:5px 0;color:rgba(239,68,68,0.7);text-transform:uppercase;letter-spacing:1px;font-size:10px">Artist</td><td style="padding:5px 0">{$artistName}</td></tr>
    <tr><td style="padding:5px 0;color:rgba(239,68,68,0.7);text-transform:uppercase;letter-spacing:1px;font-size:10px">When</td><td style="padding:5px 0;text-decoration:line-through;color:rgba(245,245,242,0.5)">{$when}</td></tr>
    <tr><td style="padding:5px 0;color:rgba(239,68,68,0.7);text-transform:uppercase;letter-spacing:1px;font-size:10px">Canceled&nbsp;by</td><td style="padding:5px 0">{$byEsc}</td></tr>
    <tr><td style="padding:8px 0 0;color:rgba(239,68,68,0.7);text-transform:uppercase;letter-spacing:1px;font-size:10px;vertical-align:top">Reason</td><td style="padding:8px 0 0;font-style:italic;color:rgba(245,245,242,0.7)">{$reasonEsc}</td></tr>
  </table>
</div>
HTML;

        $html = self::template('Cancellation alert', $body);
        return self::send($recipients, $subject, $html);
    }

    private static function notifyEmail(): array
    {
        $n = config('mail.notify_email');
        return $n ? [$n] : [];
    }

    /**
     * Collect emails that should receive booking notifications.
     * - Config notify email (always)
     * - All active STAFF + ADMIN users (always — they manage the shop)
     * - The specific assigned artist's user account (if an artist was selected)
     * - Other ARTIST accounts are NOT included (they only see their own bookings)
     */
    private static function allStaffEmails(?string $artistId = null): array
    {
        $emails = [];

        $cfg = config('mail.notify_email');
        if ($cfg) $emails[] = strtolower(trim($cfg));

        $users = Container::users()->all();

        // STAFF + ADMIN always get notified
        foreach ($users as $u) {
            if (empty($u['is_active']) || empty($u['email'])) continue;
            if (in_array($u['role'] ?? '', ['STAFF', 'ADMIN'], true)) {
                $emails[] = strtolower(trim($u['email']));
            }
        }

        // Only the assigned artist gets notified (not all artists)
        if ($artistId) {
            foreach ($users as $u) {
                if (empty($u['is_active']) || empty($u['email'])) continue;
                if (($u['role'] ?? '') === 'ARTIST' && ($u['artist_profile_id'] ?? '') === $artistId) {
                    $emails[] = strtolower(trim($u['email']));
                }
            }
        }

        return array_values(array_unique($emails));
    }
}
