<?php
// ============================================================
// Elegant Work — Email Templates
// All templates return HTML strings
// ============================================================

function emailWrapper(string $title, string $bodyContent, string $footerNote = ''): string
{
  $year = date('Y');
  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:#f4f6f9;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f6f9;padding:32px 16px">
    <tr><td align="center">
      <table width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%">

        <!-- Header -->
        <tr><td style="background:#1b4b8a;border-radius:10px 10px 0 0;padding:24px 32px">
          <table width="100%" cellpadding="0" cellspacing="0">
            <tr>
              <td>
                <div style="color:#fff;font-size:22px;font-weight:700;letter-spacing:-.3px">⚡ Elegant Work</div>
                <div style="color:rgba(255,255,255,.65);font-size:13px;margin-top:2px">Business Management Platform</div>
              </td>
            </tr>
          </table>
        </td></tr>

        <!-- Body -->
        <tr><td style="background:#fff;padding:32px;border-left:1px solid #e5e7eb;border-right:1px solid #e5e7eb">
          {$bodyContent}
        </td></tr>

        <!-- Footer -->
        <tr><td style="background:#f8fafc;border:1px solid #e5e7eb;border-top:none;border-radius:0 0 10px 10px;padding:18px 32px">
          <div style="color:#9ca3af;font-size:12px;line-height:1.5">
            {$footerNote}
            <br>This is an automated notification from Elegant Work. &copy; {$year} Elegant Work Group.
          </div>
        </td></tr>

      </table>
    </td></tr>
  </table>
</body>
</html>
HTML;
}

function emailSection(string $title, string $content, string $borderColor = '#1b4b8a'): string
{
  return <<<HTML
<div style="border-left:3px solid {$borderColor};padding:12px 16px;margin:16px 0;background:#f8fafc;border-radius:0 6px 6px 0">
  <div style="font-size:11px;font-weight:700;color:#6b7280;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px">{$title}</div>
  <div style="color:#111827;font-size:14px;line-height:1.6">{$content}</div>
</div>
HTML;
}

function emailButton(string $label, string $url, string $color = '#1b4b8a'): string
{
  return <<<HTML
<div style="margin:24px 0 8px">
  <a href="{$url}" style="display:inline-block;background:{$color};color:#fff;text-decoration:none;padding:12px 24px;border-radius:6px;font-weight:600;font-size:14px">{$label}</a>
</div>
HTML;
}

function emailBadge(string $label, string $bg, string $color): string
{
  return "<span style=\"display:inline-block;background:{$bg};color:{$color};padding:3px 10px;border-radius:20px;font-size:12px;font-weight:700\">{$label}</span>";
}

// ── Status badge colors ──────────────────────────────────
function statusBadgeHtml(string $status): string
{
  $map = [
    'draft' => ['#f3f4f6', '#6b7280'],
    'assigned' => ['#dbeafe', '#1e40af'],
    'travelling' => ['#fef3c7', '#92400e'],
    'on_site' => ['#fef3c7', '#b45309'],
    'working' => ['#fef9c3', '#713f12'],
    'completed' => ['#dcfce7', '#166534'],
    'internal_complete' => ['#dcfce7', '#166534'],
    'invoiced' => ['#dbeafe', '#1e40af'],
    'no_charge' => ['#f0fdf4', '#15803d'],
    'pending' => ['#f3f4f6', '#6b7280'],
    'in_progress' => ['#fef3c7', '#92400e'],
    'missed' => ['#fee2e2', '#991b1b'],
  ];
  [$bg, $col] = $map[$status] ?? ['#f3f4f6', '#6b7280'];
  $label = ucwords(str_replace('_', ' ', $status));
  return emailBadge($label, $bg, $col);
}

// ── Template: Job Card Created ───────────────────────────
function tplJobCreated(array $jc, string $recipientName, string $appUrl = ''): string
{
  $title = "New Job Card Created";
  $jcTitle = htmlspecialchars($jc['title'] ?? '');
  $jobNo = htmlspecialchars($jc['job_number'] ?? '');
  $client = htmlspecialchars($jc['client_name'] ?? 'Internal');
  $site = htmlspecialchars($jc['site_name'] ?? '—');
  $sched = !empty($jc['scheduled_date']) ? date('d M Y', strtotime($jc['scheduled_date'])) : 'Not scheduled';
  $techName = htmlspecialchars($jc['tech_name'] ?? 'Unassigned');
  $priority = ucfirst($jc['priority'] ?? 'normal');
  $link = $appUrl ? emailButton('View Job Card', $appUrl) : '';

  $body = <<<HTML
    <h2 style="margin:0 0 6px;font-size:20px;color:#111827">📋 New Job Card Created</h2>
    <p style="color:#6b7280;margin:0 0 20px;font-size:14px">Hi {$recipientName}, a new job card has been created in the system.</p>
    <div style="background:#f0f7ff;border:1px solid #bfdbfe;border-radius:8px;padding:18px;margin:0 0 20px">
      <div style="font-size:22px;font-weight:700;color:#1b4b8a;letter-spacing:-.3px">{$jobNo}</div>
      <div style="font-size:16px;font-weight:600;color:#111827;margin-top:4px">{$jcTitle}</div>
    </div>
    HTML;
  $body .= emailSection('Client', $client);
  $body .= emailSection('Site', $site);
  $body .= emailSection('Scheduled', $sched);
  $body .= emailSection('Assigned To', $techName);
  $body .= emailSection('Priority', $priority);
  $body .= $link;

  return emailWrapper($title, $body, "You received this because you are set as admin notification recipient.");
}

// ── Template: Job Assigned (to tech) ────────────────────
function tplJobAssigned(array $jc, string $techName, string $appUrl = ''): string
{
  $jcTitle = htmlspecialchars($jc['title'] ?? '');
  $jobNo = htmlspecialchars($jc['job_number'] ?? '');
  $client = htmlspecialchars($jc['client_name'] ?? 'Internal');
  $site = htmlspecialchars($jc['site_name'] ?? '—');
  $addr = htmlspecialchars($jc['site_address'] ?? '—');
  $sched = !empty($jc['scheduled_date']) ? date('D, d M Y', strtotime($jc['scheduled_date'])) : 'TBD';
  $time = !empty($jc['scheduled_time']) ? date('H:i', strtotime($jc['scheduled_time'])) : '';
  $desc = htmlspecialchars($jc['description'] ?? '');
  $link = $appUrl ? emailButton('Open Job Card', $appUrl, '#059669') : '';

  $body = <<<HTML
    <h2 style="margin:0 0 6px;font-size:20px;color:#111827">🔧 You've Been Assigned a Job</h2>
    <p style="color:#6b7280;margin:0 0 20px;font-size:14px">Hi {$techName}, you have been assigned to the following job card.</p>
    <div style="background:#f0fdf4;border:1px solid #86efac;border-radius:8px;padding:18px;margin:0 0 20px">
      <div style="font-size:22px;font-weight:700;color:#15803d;letter-spacing:-.3px">{$jobNo}</div>
      <div style="font-size:16px;font-weight:600;color:#111827;margin-top:4px">{$jcTitle}</div>
    </div>
    HTML;
  $body .= emailSection('Client', $client);
  $body .= emailSection('Site / Address', "{$site}<br><span style='color:#6b7280'>{$addr}</span>");
  $body .= emailSection('Scheduled', $sched . ($time ? " at {$time}" : ''));
  if ($desc)
    $body .= emailSection('Description', nl2br($desc));
  $body .= $link;

  return emailWrapper("Job Assigned: {$jobNo}", $body, "You received this because you were assigned to this job card.");
}

// ── Template: Job Status Changed (internal only) ────────
function tplJobStatusChanged(array $jc, string $recipientName, string $oldStatus, string $newStatus, string $changedBy, string $appUrl = ''): string
{
  $jcTitle = htmlspecialchars($jc['title'] ?? '');
  $jobNo = htmlspecialchars($jc['job_number'] ?? '');
  $client = htmlspecialchars($jc['client_name'] ?? 'Internal');
  $oldBadge = statusBadgeHtml($oldStatus);
  $newBadge = statusBadgeHtml($newStatus);
  $link = $appUrl ? emailButton('View Job Card', $appUrl) : '';

  $body = <<<HTML
    <h2 style="margin:0 0 6px;font-size:20px;color:#111827">🔄 Job Card Status Updated</h2>
    <p style="color:#6b7280;margin:0 0 20px;font-size:14px">Hi {$recipientName}, the status of a job card has been updated.</p>
    <div style="background:#f8fafc;border:1px solid #e5e7eb;border-radius:8px;padding:18px;margin:0 0 20px">
      <div style="font-size:18px;font-weight:700;color:#1b4b8a">{$jobNo}</div>
      <div style="font-size:15px;font-weight:600;color:#111827;margin:4px 0 10px">{$jcTitle}</div>
      <table cellpadding="0" cellspacing="0"><tr>
        <td style="padding-right:8px">{$oldBadge}</td>
        <td style="color:#9ca3af;font-size:14px;padding:0 8px">→</td>
        <td>{$newBadge}</td>
      </tr></table>
    </div>
    HTML;
  $body .= emailSection('Client', $client);
  $body .= emailSection('Updated By', htmlspecialchars($changedBy));
  $body .= $link;

  return emailWrapper("Job Status: {$jobNo}", $body, "You received this because you are set as admin notification recipient.");
}

// ── CLIENT: Job Scheduled / Planned ─────────────────────
// Sent to client when a job is created with their details
function tplClientJobPlanned(array $jc, string $recipientName, string $company): string
{
  $jcTitle = htmlspecialchars($jc['title'] ?? '');
  $site = htmlspecialchars($jc['site_name'] ?? '');
  $addr = htmlspecialchars($jc['site_address'] ?? '');
  $techName = htmlspecialchars($jc['tech_name'] ?? '');
  $desc = htmlspecialchars($jc['description'] ?? '');
  $sched = !empty($jc['scheduled_date']) ? date('l, d F Y', strtotime($jc['scheduled_date'])) : null;
  $time = !empty($jc['scheduled_time']) ? date('H:i', strtotime($jc['scheduled_time'])) : null;

  $schedLine = $sched
    ? ($time ? "{$sched} at {$time}" : $sched)
    : 'We will confirm the date and time shortly.';

  $techLine = $techName
    ? "Your job will be attended to by <strong>{$techName}</strong>."
    : "We will confirm your assigned technician shortly.";

  $body = <<<HTML
    <h2 style="margin:0 0 8px;font-size:22px;color:#111827">We've Scheduled a Job For You</h2>
    <p style="color:#374151;margin:0 0 22px;font-size:15px;line-height:1.6">Dear {$recipientName},<br><br>
    Thank you for choosing <strong>{$company}</strong>. We have scheduled a job at your site and wanted to let you know the details.</p>

    <div style="background:#f0f7ff;border:1px solid #bfdbfe;border-radius:10px;padding:20px;margin:0 0 22px">
      <div style="font-size:17px;font-weight:700;color:#1e3a5f;margin-bottom:4px">{$jcTitle}</div>
      <div style="font-size:13px;color:#3b82f6;font-weight:600;letter-spacing:.3px">SCHEDULED</div>
    </div>
    HTML;

  $body .= emailSection('Planned Date', $schedLine, '#3b82f6');
  if ($site)
    $body .= emailSection('Site', $site . ($addr ? "<br><span style='color:#9ca3af;font-size:13px'>{$addr}</span>" : ''));
  if ($techName)
    $body .= emailSection('Attending Technician', $techName);
  if ($desc)
    $body .= emailSection('Job Description', nl2br($desc));

  $body .= <<<HTML
    <div style="background:#fefce8;border:1px solid #fde047;border-radius:8px;padding:14px 16px;margin-top:20px;font-size:13px;color:#713f12;line-height:1.5">
      📞 If you need to reschedule or have any questions, please don't hesitate to contact us.
    </div>
    HTML;

  return emailWrapper(
    "Job Scheduled — {$jcTitle}",
    $body,
    "This email was sent because a job has been scheduled at your site by {$company}."
  );
}

// ── CLIENT: Job Confirmed (tech assigned) ───────────────
function tplClientJobConfirmed(array $jc, string $recipientName, string $company): string
{
  $jcTitle = htmlspecialchars($jc['title'] ?? '');
  $site = htmlspecialchars($jc['site_name'] ?? '');
  $addr = htmlspecialchars($jc['site_address'] ?? '');
  $techName = htmlspecialchars($jc['tech_name'] ?? ($jc['assigned_name'] ?? ''));
  $desc = htmlspecialchars($jc['description'] ?? '');
  $sched = !empty($jc['scheduled_date']) ? date('l, d F Y', strtotime($jc['scheduled_date'])) : null;
  $time = !empty($jc['scheduled_time']) ? date('H:i', strtotime($jc['scheduled_time'])) : null;

  $schedLine = $sched
    ? ($time ? "{$sched} at {$time}" : $sched)
    : 'We will confirm the exact date and time shortly.';

  $body = <<<HTML
    <h2 style="margin:0 0 8px;font-size:22px;color:#111827">Your Job is Confirmed</h2>
    <p style="color:#374151;margin:0 0 22px;font-size:15px;line-height:1.6">Dear {$recipientName},<br><br>
    We are pleased to confirm that your job has been scheduled and a technician has been assigned. Please find the details below.</p>

    <div style="background:#f0fdf4;border:1px solid #86efac;border-radius:10px;padding:20px;margin:0 0 22px">
      <div style="display:flex;align-items:center;gap:10px">
        <span style="font-size:28px">✅</span>
        <div>
          <div style="font-size:17px;font-weight:700;color:#14532d">{$jcTitle}</div>
          <div style="font-size:13px;color:#16a34a;font-weight:600;margin-top:2px;letter-spacing:.3px">CONFIRMED</div>
        </div>
      </div>
    </div>
    HTML;

  $body .= emailSection('Scheduled Date', $schedLine, '#16a34a');
  if ($site)
    $body .= emailSection('Site', $site . ($addr ? "<br><span style='color:#9ca3af;font-size:13px'>{$addr}</span>" : ''));
  if ($techName)
    $body .= emailSection('Your Technician', $techName);
  if ($desc)
    $body .= emailSection('Job Description', nl2br($desc));

  $body .= <<<HTML
    <div style="background:#fefce8;border:1px solid #fde047;border-radius:8px;padding:14px 16px;margin-top:20px;font-size:13px;color:#713f12;line-height:1.5">
      📞 If you need to reschedule or have any questions, please don't hesitate to contact us.
    </div>
    HTML;

  return emailWrapper(
    "Job Confirmed — {$jcTitle}",
    $body,
    "This email was sent to confirm your upcoming job with {$company}."
  );
}

function tplClientJobCompleted(array $jc, string $recipientName, string $company): string
{
  $jcTitle = htmlspecialchars($jc['title'] ?? '');
  $jobNo = htmlspecialchars($jc['job_number'] ?? '');
  $site = htmlspecialchars($jc['site_name'] ?? '—');
  $addr = htmlspecialchars($jc['site_address'] ?? '');
  $techName = htmlspecialchars($jc['assigned_name'] ?? ($jc['tech_name'] ?? ''));
  $compDate = !empty($jc['completed_at']) ? date('l, d F Y', strtotime($jc['completed_at'])) : date('l, d F Y');
  $signed = htmlspecialchars($jc['client_name_signed'] ?? '');
  $desc = htmlspecialchars($jc['description'] ?? '');
  $jobId = (int) ($jc['id'] ?? 0);
  $appUrl = $jc['_app_url'] ?? '';
  $pdfLink = !empty($jc['_pdf_url']) ? emailButton('View Job Document (PDF)', $jc['_pdf_url'], '#16a34a') : '';

  $body = <<<HTML
    <h2 style="margin:0 0 8px;font-size:22px;color:#111827">Work Has Been Completed</h2>
    <p style="color:#374151;margin:0 0 22px;font-size:15px;line-height:1.6">Dear {$recipientName},<br><br>
    We are pleased to let you know that work at your site has been completed. A summary is below and your job document is attached to this email.</p>

    <div style="background:#f0fdf4;border:1px solid #86efac;border-radius:10px;padding:20px;margin:0 0 22px">
      <div style="display:flex;align-items:center;gap:10px">
        <span style="font-size:28px">✅</span>
        <div>
          <div style="font-size:13px;color:#16a34a;font-weight:700;letter-spacing:.5px;margin-bottom:2px">{$jobNo}</div>
          <div style="font-size:17px;font-weight:700;color:#14532d">{$jcTitle}</div>
          <div style="font-size:13px;color:#16a34a;font-weight:600;margin-top:2px">COMPLETED — {$compDate}</div>
        </div>
      </div>
    </div>
    HTML;

  $body .= emailSection('Site', $site . ($addr ? "<br><span style='color:#9ca3af;font-size:13px'>{$addr}</span>" : ''), '#16a34a');
  if ($techName)
    $body .= emailSection('Completed By', $techName);
  if ($signed)
    $body .= emailSection('Signed Off By', $signed);
  if ($desc)
    $body .= emailSection('Job', nl2br($desc));
  $body .= $pdfLink;

  $body .= <<<HTML
    <div style="background:#f0fdf4;border:1px solid #86efac;border-radius:8px;padding:14px 16px;margin-top:16px;font-size:13px;color:#166534;line-height:1.6">
      📎 Your job document is also attached to this email as a PDF.<br>
      If you have any questions about the work performed, please contact us.
    </div>
    HTML;

  return emailWrapper(
    "Work Completed — {$jobNo}",
    $body,
    "Thank you for choosing {$company}. We appreciate your business."
  );
}

// ── CLIENT: Invoice / No Charge — Job Card Document ─────
function tplClientInvoice(array $jc, string $recipientName, string $company): string
{
  $jcTitle = htmlspecialchars($jc['title'] ?? '');
  $jobNo = htmlspecialchars($jc['job_number'] ?? '');
  $site = htmlspecialchars($jc['site_name'] ?? '—');
  $addr = htmlspecialchars($jc['site_address'] ?? '');
  $compDate = !empty($jc['completed_at']) ? date('d F Y', strtotime($jc['completed_at'])) : date('d F Y');
  $techName = htmlspecialchars($jc['assigned_name'] ?? ($jc['tech_name'] ?? ''));
  $desc = htmlspecialchars($jc['description'] ?? '');
  $jobId = (int) ($jc['id'] ?? 0);
  $appUrl = $jc['_app_url'] ?? '';
  $pdfLink = !empty($jc['_pdf_url']) ? emailButton('View Job Document (PDF)', $jc['_pdf_url'], '#1b4b8a') : '';

  $body = <<<HTML
    <h2 style="margin:0 0 8px;font-size:22px;color:#111827">Job Card Document — Your Copy</h2>
    <p style="color:#374151;margin:0 0 22px;font-size:15px;line-height:1.6">Dear {$recipientName},<br><br>
    Please find your job card document attached to this email. A summary of the work completed at your site is included below.</p>

    <div style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:10px;padding:20px;margin:0 0 22px">
      <div style="font-size:13px;color:#3b82f6;font-weight:700;letter-spacing:.5px;margin-bottom:2px">{$jobNo}</div>
      <div style="font-size:17px;font-weight:700;color:#1e3a5f">{$jcTitle}</div>
      <div style="font-size:13px;color:#3b82f6;font-weight:600;margin-top:2px">COMPLETED — {$compDate}</div>
    </div>
    HTML;

  $body .= emailSection('Site', $site . ($addr ? "<br><span style='color:#9ca3af;font-size:13px'>{$addr}</span>" : ''), '#1b4b8a');
  if ($techName)
    $body .= emailSection('Attended By', $techName);
  if ($desc)
    $body .= emailSection('Work Description', nl2br($desc));
  $body .= $pdfLink;

  $body .= <<<HTML
    <div style="background:#f8fafc;border:1px solid #e5e7eb;border-radius:8px;padding:14px 16px;margin-top:16px;font-size:13px;color:#374151;line-height:1.6">
      📎 Your job card document is also attached to this email as a PDF.<br>
      If you have any questions about the work performed, please don't hesitate to contact us.
    </div>
    HTML;

  return emailWrapper(
    "Job Card Document — {$jobNo}",
    $body,
    "Thank you for your business. {$company}."
  );
}

// ── CLIENT: No Charge ────────────────────────────────────
function tplClientNoCharge(array $jc, string $recipientName, string $company): string
{
  $jcTitle = htmlspecialchars($jc['title'] ?? '');
  $jobNo = htmlspecialchars($jc['job_number'] ?? '');
  $site = htmlspecialchars($jc['site_name'] ?? '—');
  $addr = htmlspecialchars($jc['site_address'] ?? '');
  $compDate = !empty($jc['completed_at']) ? date('d F Y', strtotime($jc['completed_at'])) : date('d F Y');
  $techName = htmlspecialchars($jc['assigned_name'] ?? ($jc['tech_name'] ?? ''));
  $desc = htmlspecialchars($jc['description'] ?? '');
  $jobId = (int) ($jc['id'] ?? 0);
  $appUrl = $jc['_app_url'] ?? '';
  $pdfLink = !empty($jc['_pdf_url']) ? emailButton('View Job Document (PDF)', $jc['_pdf_url'], '#16a34a') : '';

  $body = <<<HTML
    <h2 style="margin:0 0 8px;font-size:22px;color:#111827">Job Card Document — Your Copy</h2>
    <p style="color:#374151;margin:0 0 22px;font-size:15px;line-height:1.6">Dear {$recipientName},<br><br>
    Please find your job card document attached to this email. A summary of the work completed at your site is included below.</p>

    <div style="background:#f0fdf4;border:1px solid #86efac;border-radius:10px;padding:20px;margin:0 0 22px">
      <div style="font-size:13px;color:#16a34a;font-weight:700;letter-spacing:.5px;margin-bottom:2px">{$jobNo}</div>
      <div style="font-size:17px;font-weight:700;color:#14532d">{$jcTitle}</div>
      <div style="font-size:13px;color:#16a34a;font-weight:600;margin-top:2px">COMPLETED — {$compDate}</div>
    </div>
    HTML;

  $body .= emailSection('Site', $site . ($addr ? "<br><span style='color:#9ca3af;font-size:13px'>{$addr}</span>" : ''), '#16a34a');
  if ($techName)
    $body .= emailSection('Attended By', $techName);
  if ($desc)
    $body .= emailSection('Work Description', nl2br($desc));
  $body .= $pdfLink;

  $body .= <<<HTML
    <div style="background:#f0fdf4;border:1px solid #86efac;border-radius:8px;padding:14px 16px;margin-top:16px;font-size:13px;color:#166534;line-height:1.6">
      📎 Your job card document is also attached to this email as a PDF.<br>
      If you have any questions about the work performed, please don't hesitate to contact us.
    </div>
    HTML;

  return emailWrapper(
    "Job Card Document — {$jobNo}",
    $body,
    "Thank you for choosing {$company}. We appreciate your business."
  );
}

// ── INTERNAL: Job Completed (admin/tech) ─────────────────
function tplJobCompleted(array $jc, string $recipientName, bool $isClient = false, string $appUrl = ''): string
{
  // Client version — redirect to dedicated template
  // (kept for backward compat — callers should use tplClientJobCompleted directly)
  if ($isClient) {
    return tplClientJobCompleted($jc, $recipientName, 'Elegant Work');
  }
  $jcTitle = htmlspecialchars($jc['title'] ?? '');
  $jobNo = htmlspecialchars($jc['job_number'] ?? '');
  $client = htmlspecialchars($jc['client_name'] ?? '—');
  $site = htmlspecialchars($jc['site_name'] ?? '—');
  $compDate = !empty($jc['completed_at']) ? date('d M Y H:i', strtotime($jc['completed_at'])) : date('d M Y');
  $signed = htmlspecialchars($jc['client_name_signed'] ?? '');
  $link = $appUrl ? emailButton('View Job Card', $appUrl) : '';

  $body = <<<HTML
    <h2 style="margin:0 0 6px;font-size:20px;color:#111827">✅ Job Completed</h2>
    <p style="color:#6b7280;margin:0 0 20px;font-size:14px">Hi {$recipientName}, the following job card has been marked as completed.</p>
    <div style="background:#f0fdf4;border:1px solid #86efac;border-radius:8px;padding:18px;margin:0 0 20px">
      <div style="font-size:18px;font-weight:700;color:#15803d">{$jobNo}</div>
      <div style="font-size:15px;font-weight:600;color:#111827;margin-top:4px">{$jcTitle}</div>
    </div>
    HTML;
  $body .= emailSection('Client', $client);
  $body .= emailSection('Site', $site);
  $body .= emailSection('Completed', $compDate);
  if ($signed)
    $body .= emailSection('Signed By', $signed);
  $body .= $link;

  return emailWrapper("Completed: {$jobNo}", $body);
}

// ── INTERNAL: Job Invoiced (admin/tech) ──────────────────
function tplJobInvoiced(array $jc, string $recipientName, bool $isClient = false, string $appUrl = ''): string
{
  // Client version — redirect to dedicated templates
  if ($isClient) {
    return tplClientInvoice($jc, $recipientName, 'Elegant Work');
  }
  $jcTitle = htmlspecialchars($jc['title'] ?? '');
  $jobNo = htmlspecialchars($jc['job_number'] ?? '');
  $invoiceNo = htmlspecialchars($jc['invoice_no'] ?? '—');
  $amount = !empty($jc['invoice_amount']) ? 'R ' . number_format((float) $jc['invoice_amount'], 2) : '—';
  $site = htmlspecialchars($jc['site_name'] ?? '—');
  $link = $appUrl ? emailButton('View Job Card', $appUrl) : '';

  $body = <<<HTML
    <h2 style="margin:0 0 6px;font-size:20px;color:#111827">🧾 Job Invoiced</h2>
    <p style="color:#6b7280;margin:0 0 20px;font-size:14px">Hi {$recipientName}, the following job card has been marked as invoiced.</p>
    <div style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:8px;padding:18px;margin:0 0 20px">
      <div style="font-size:18px;font-weight:700;color:#1d4ed8">{$jobNo}</div>
      <div style="font-size:15px;font-weight:600;color:#111827;margin-top:4px">{$jcTitle}</div>
    </div>
    HTML;
  $body .= emailSection('Invoice No.', $invoiceNo);
  $body .= emailSection('Amount', "<strong style='font-size:18px;color:#1b4b8a'>{$amount}</strong>", '#1b4b8a');
  $body .= emailSection('Site', $site);
  $body .= $link;

  return emailWrapper("Invoice: {$jobNo}", $body);
}

// ── Template: Checklist Due ──────────────────────────────
function tplChecklistDue(array $inst, string $recipientName, string $appUrl = ''): string
{
  $tplName = htmlspecialchars($inst['template_name'] ?? 'Checklist');
  $dueDate = !empty($inst['due_date']) ? date('D, d M Y', strtotime($inst['due_date'])) : '—';
  $dueTime = !empty($inst['due_time']) ? date('H:i', strtotime($inst['due_time'])) : '';
  $vehicle = $inst['vehicle_reg'] ? htmlspecialchars($inst['vehicle_reg'] . ' ' . ($inst['vehicle_make'] ?? '')) : '';
  $progress = $inst['total_items'] > 0
    ? round(($inst['answered_items'] / $inst['total_items']) * 100) . '% (' . $inst['answered_items'] . '/' . $inst['total_items'] . ' items)'
    : 'Not started';
  $link = $appUrl ? emailButton('Fill In Checklist', $appUrl, '#0891b2') : '';

  $body = <<<HTML
    <h2 style="margin:0 0 6px;font-size:20px;color:#111827">📋 Checklist Due</h2>
    <p style="color:#6b7280;margin:0 0 20px;font-size:14px">Hi {$recipientName}, you have a checklist that needs to be completed.</p>
    <div style="background:#f0fdfa;border:1px solid #99f6e4;border-radius:8px;padding:18px;margin:0 0 20px">
      <div style="font-size:18px;font-weight:700;color:#0f766e">{$tplName}</div>
    </div>
    HTML;
  $body .= emailSection('Due', $dueDate . ($dueTime ? " at {$dueTime}" : ''), '#0891b2');
  if ($vehicle)
    $body .= emailSection('Vehicle', $vehicle);
  $body .= emailSection('Progress', $progress);
  $body .= $link;

  return emailWrapper("Checklist Due: {$tplName}", $body, "Please complete this checklist by the due date.");
}

// ── Template: Checklist Missed ───────────────────────────
function tplChecklistMissed(array $inst, string $recipientName, string $appUrl = ''): string
{
  $tplName = htmlspecialchars($inst['template_name'] ?? 'Checklist');
  $dueDate = !empty($inst['due_date']) ? date('d M Y', strtotime($inst['due_date'])) : '—';
  $assignee = htmlspecialchars($inst['assigned_to_name'] ?? $inst['assignee_name'] ?? 'Unknown');
  $link = $appUrl ? emailButton('View Checklist', $appUrl, '#dc2626') : '';

  $body = <<<HTML
    <h2 style="margin:0 0 6px;font-size:20px;color:#991b1b">⚠️ Overdue Checklist</h2>
    <p style="color:#6b7280;margin:0 0 20px;font-size:14px">Hi {$recipientName}, a checklist was not completed by its due date.</p>
    <div style="background:#fff1f2;border:1px solid #fecdd3;border-radius:8px;padding:18px;margin:0 0 20px">
      <div style="font-size:18px;font-weight:700;color:#dc2626">{$tplName}</div>
      <div style="font-size:13px;color:#991b1b;margin-top:4px">Was due: {$dueDate}</div>
    </div>
    HTML;
  $body .= emailSection('Assigned To', $assignee, '#dc2626');
  $body .= $link;

  return emailWrapper("Overdue: {$tplName}", $body);
}

// ── Template: Checklist Completed ───────────────────────
function tplChecklistCompleted(array $inst, string $recipientName, string $completedBy, string $appUrl = ''): string
{
  $tplName = htmlspecialchars($inst['template_name'] ?? 'Checklist');
  $compTime = !empty($inst['completed_at']) ? date('d M Y H:i', strtotime($inst['completed_at'])) : date('d M Y H:i');
  $vehicle = $inst['vehicle_reg'] ? htmlspecialchars($inst['vehicle_reg']) : '';
  $progress = $inst['total_items'] > 0 ? $inst['answered_items'] . '/' . $inst['total_items'] . ' items completed' : '—';
  $link = $appUrl ? emailButton('View Submission', $appUrl, '#059669') : '';

  $body = <<<HTML
    <h2 style="margin:0 0 6px;font-size:20px;color:#111827">✅ Checklist Completed</h2>
    <p style="color:#6b7280;margin:0 0 20px;font-size:14px">Hi {$recipientName}, a checklist has been submitted.</p>
    <div style="background:#f0fdf4;border:1px solid #86efac;border-radius:8px;padding:18px;margin:0 0 20px">
      <div style="font-size:18px;font-weight:700;color:#15803d">{$tplName}</div>
    </div>
    HTML;
  $body .= emailSection('Completed By', htmlspecialchars($completedBy));
  $body .= emailSection('Completed At', $compTime);
  $body .= emailSection('Progress', $progress);
  if ($vehicle)
    $body .= emailSection('Vehicle', $vehicle);
  $body .= $link;

  return emailWrapper("Checklist Submitted: {$tplName}", $body);
}

// ── Template: Leave Submitted ────────────────────────────
function tplLeaveSubmitted(array $leave, string $empName, string $recipientName, string $appUrl = ''): string
{
  $type = ucwords(str_replace('_', ' ', $leave['leave_type'] ?? ''));
  $from = !empty($leave['start_date']) ? date('d M Y', strtotime($leave['start_date'])) : '—';
  $to = $leave['end_date'] ? date('d M Y', strtotime($leave['end_date'])) : '—';
  $days = $leave['days_requested'] ?? '—';
  $reason = htmlspecialchars($leave['reason'] ?? '—');
  $link = $appUrl ? emailButton('Review Leave Request', $appUrl) : '';

  $body = <<<HTML
    <h2 style="margin:0 0 6px;font-size:20px;color:#111827">🌴 Leave Request Submitted</h2>
    <p style="color:#6b7280;margin:0 0 20px;font-size:14px">Hi {$recipientName}, a leave request has been submitted and requires your attention.</p>
    <div style="background:#fff7ed;border:1px solid #fed7aa;border-radius:8px;padding:18px;margin:0 0 20px">
      <div style="font-size:18px;font-weight:700;color:#c2410c">{$empName}</div>
      <div style="font-size:14px;color:#9a3412;margin-top:4px">{$type} Leave — {$days} day(s)</div>
    </div>
    HTML;
  $body .= emailSection('From', $from, '#f97316');
  $body .= emailSection('To', $to, '#f97316');
  $body .= emailSection('Reason', $reason);
  $body .= $link;

  return emailWrapper("Leave Request: {$empName}", $body, "Please review and approve or reject this request in the system.");
}

// ── Template: Leave Actioned ─────────────────────────────
function tplLeaveActioned(array $leave, string $empName, string $action, string $reason = ''): string
{
  $approved = strtolower($action) === 'approved';
  $type = ucwords(str_replace('_', ' ', $leave['leave_type'] ?? ''));
  $from = !empty($leave['start_date']) ? date('d M Y', strtotime($leave['start_date'])) : '—';
  $to = $leave['end_date'] ? date('d M Y', strtotime($leave['end_date'])) : '—';
  $days = $leave['days_requested'] ?? '—';
  $color = $approved ? '#15803d' : '#dc2626';
  $bgColor = $approved ? '#f0fdf4' : '#fff1f2';
  $bdColor = $approved ? '#86efac' : '#fecdd3';
  $emoji = $approved ? '✅' : '❌';
  $label = $approved ? 'Approved' : 'Rejected';

  $body = <<<HTML
    <h2 style="margin:0 0 6px;font-size:20px;color:#111827">{$emoji} Leave Request {$label}</h2>
    <p style="color:#6b7280;margin:0 0 20px;font-size:14px">Hi {$empName}, your leave request has been reviewed.</p>
    <div style="background:{$bgColor};border:1px solid {$bdColor};border-radius:8px;padding:18px;margin:0 0 20px">
      <div style="font-size:20px;font-weight:700;color:{$color}">{$label}</div>
      <div style="font-size:14px;color:{$color};margin-top:4px">{$type} Leave — {$days} day(s)</div>
    </div>
    HTML;
  $body .= emailSection('Period', "{$from} → {$to}");
  if ($reason)
    $body .= emailSection('Note from Manager', htmlspecialchars($reason), $color);

  $footer = $approved ? "Please ensure you make the necessary arrangements before your leave." : "Please contact HR if you have any questions.";
  return emailWrapper("Leave {$label}: {$empName}", $body, $footer);
}

// ── Template: Low Stock Alert ────────────────────────────
/**
 * @param array $items  Each item: ['name', 'sku', 'qty_on_hand', 'min_qty', 'unit']
 */
function tplLowStock(array $items, string $recipientName, string $appUrl = ''): string
{
  $count = count($items);
  $noun  = $count === 1 ? 'item has' : 'items have';

  $rows = '';
  foreach ($items as $i) {
    $name    = htmlspecialchars($i['name'] ?? '');
    $sku     = htmlspecialchars($i['sku']  ?? '');
    $onHand  = number_format((float)($i['qty_on_hand'] ?? 0), 2);
    $minQty  = number_format((float)($i['min_qty']     ?? 0), 2);
    $unit    = htmlspecialchars($i['unit'] ?? 'each');
    $rows .= <<<ROW
<tr>
  <td style="padding:10px 12px;border-bottom:1px solid #f3f4f6;font-weight:600;font-size:13px">{$name}</td>
  <td style="padding:10px 12px;border-bottom:1px solid #f3f4f6;color:#6b7280;font-size:13px">{$sku}</td>
  <td style="padding:10px 12px;border-bottom:1px solid #f3f4f6;color:#dc2626;font-weight:700;font-size:13px">{$onHand} {$unit}</td>
  <td style="padding:10px 12px;border-bottom:1px solid #f3f4f6;color:#6b7280;font-size:13px">{$minQty} {$unit}</td>
</tr>
ROW;
  }

  $link = $appUrl ? emailButton('🔗 View Stock', $appUrl . '#stock') : '';

  $body = <<<BODY
<p style="font-size:15px;color:#111827;margin:0 0 4px">Hi {$recipientName},</p>
<p style="font-size:14px;color:#6b7280;margin:0 0 20px">
  The following {$noun} dropped below minimum stock level following a recent book-out:
</p>

<div style="background:#fff5f5;border:1.5px solid #fca5a5;border-radius:8px;padding:16px 0;margin-bottom:20px">
  <div style="padding:0 16px 10px;font-size:11px;font-weight:700;color:#991b1b;text-transform:uppercase;letter-spacing:.5px">
    ⚠ {$count} Low Stock {$noun}
  </div>
  <table width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse">
    <thead>
      <tr style="background:#fef2f2">
        <th style="padding:8px 12px;text-align:left;font-size:11px;font-weight:700;color:#6b7280;text-transform:uppercase;letter-spacing:.4px">Item</th>
        <th style="padding:8px 12px;text-align:left;font-size:11px;font-weight:700;color:#6b7280;text-transform:uppercase;letter-spacing:.4px">SKU</th>
        <th style="padding:8px 12px;text-align:left;font-size:11px;font-weight:700;color:#6b7280;text-transform:uppercase;letter-spacing:.4px">On Hand</th>
        <th style="padding:8px 12px;text-align:left;font-size:11px;font-weight:700;color:#6b7280;text-transform:uppercase;letter-spacing:.4px">Min</th>
      </tr>
    </thead>
    <tbody>{$rows}</tbody>
  </table>
</div>

<p style="font-size:13px;color:#6b7280;margin:0 0 16px">
  Please arrange replenishment to avoid disruption to operations.
</p>
{$link}
BODY;

  return emailWrapper("⚠ Low Stock Alert — {$count} Item(s)", $body, 'This alert was triggered automatically when stock dropped below the configured minimum quantity.');
}
// ── Template: Meeting Invite ─────────────────────────────
function tplMeetingInvite(array $m, string $recipientName, string $company, string $rsvpUrl = ''): string
{
    $title     = htmlspecialchars($m['title'] ?? '');
    $date      = !empty($m['meeting_date']) ? date('D, d M Y', strtotime($m['meeting_date'])) : '—';
    $time      = '';
    if (!empty($m['start_time'])) {
        $time = date('H:i', strtotime($m['start_time']));
        if (!empty($m['end_time'])) $time .= ' – ' . date('H:i', strtotime($m['end_time']));
    } else {
        $time = 'All Day';
    }
    $location  = htmlspecialchars($m['location'] ?? '');
    $desc      = htmlspecialchars($m['description'] ?? '');
    $priority  = ucfirst($m['priority'] ?? 'normal');
    $typeLabel = ucfirst($m['type'] ?? 'meeting');

    $rsvpButtons  = $rsvpUrl ? emailButton('📋 View Invitation & RSVP', $rsvpUrl) : '';
    $locationRow  = $location
        ? "<tr><td style=\"padding:5px 0;color:#6b7280;font-size:12px\">📍 Location</td><td style=\"padding:5px 0;font-size:14px;color:#374151\">{$location}</td></tr>"
        : '';
    $descSection  = $desc ? emailSection('Details', $desc) : '';

    $body = <<<BODY
<p style="font-size:15px;color:#111827;margin:0 0 4px">Hi {$recipientName},</p>
<p style="font-size:14px;color:#6b7280;margin:0 0 20px">You have been invited to the following {$typeLabel}. Please respond at your earliest convenience.</p>

<div style="background:#f0f4ff;border:1.5px solid #c7d7f8;border-radius:10px;padding:20px;margin-bottom:20px">
  <div style="font-size:19px;font-weight:700;color:#1b4b8a;margin-bottom:14px">{$title}</div>
  <table cellpadding="0" cellspacing="0" width="100%">
    <tr><td style="padding:5px 0;color:#6b7280;font-size:12px;width:90px">📅 Date</td><td style="padding:5px 0;font-size:14px;font-weight:600;color:#111827">{$date}</td></tr>
    <tr><td style="padding:5px 0;color:#6b7280;font-size:12px">⏰ Time</td><td style="padding:5px 0;font-size:14px;font-weight:600;color:#111827">{$time}</td></tr>
    {$locationRow}
  </table>
</div>

{$descSection}

<div style="background:#fef9c3;border:1px solid #fde047;border-radius:8px;padding:12px 16px;font-size:13px;color:#713f12;margin-bottom:20px">
  ⚡ Priority: {$priority} &nbsp;·&nbsp; This invitation is from {$company}.
</div>

{$rsvpButtons}

<p style="font-size:12px;color:#9ca3af;margin-top:16px">If you did not expect this invitation, you can safely ignore this email.</p>
BODY;

    return emailWrapper("📅 Meeting Invitation: {$title}", $body, "You received this invitation from {$company}.");
}

// ── Template: Meeting RSVP notification to organiser ────────
function tplMeetingRsvp(array $m, string $attendeeName, string $rsvpStatus, string $note, string $appUrl = ''): string
{
    $title = htmlspecialchars($m['title'] ?? '');
    $date  = !empty($m['meeting_date']) ? date('D, d M Y', strtotime($m['meeting_date'])) : '—';

    $statusMap = [
        'accepted'             => ['✅', 'Accepted',              '#16a34a', '#dcfce7'],
        'declined'             => ['❌', 'Declined',              '#dc2626', '#fee2e2'],
        'reschedule_requested' => ['🔄', 'Reschedule Requested',  '#0284c7', '#e0f2fe'],
    ];
    [$icon, $label, $color, $bg] = $statusMap[$rsvpStatus] ?? ['📋', $rsvpStatus, '#6b7280', '#f3f4f6'];

    $link        = $appUrl ? emailButton('🗓 View Meeting', $appUrl . '#meetings') : '';
    $noteSection = $note ? emailSection('Their Note', htmlspecialchars($note), $color) : '';

    $body = <<<BODY
<p style="font-size:15px;color:#111827;margin:0 0 20px">
  <strong>{$attendeeName}</strong> has responded to your meeting invitation.
</p>

<div style="background:{$bg};border:2px solid {$color};border-radius:10px;padding:20px;margin-bottom:20px;text-align:center">
  <div style="font-size:2rem;margin-bottom:6px">{$icon}</div>
  <div style="font-size:18px;font-weight:700;color:{$color}">{$label}</div>
  <div style="font-size:13px;color:#6b7280;margin-top:4px">{$title} · {$date}</div>
</div>

{$noteSection}

{$link}
BODY;

    return emailWrapper("📅 RSVP {$label}: {$title}", $body, 'This notification was sent automatically by Elegant Work.');
}

// ── Template: Daily Digest ───────────────────────────────
/**
 * @param string $recipientName
 * @param array  $sections  Each: ['title'=>'', 'icon'=>'', 'color'=>'', 'items'=>[['label'=>'','sub'=>'','urgent'=>false]]]
 * @param array  $missed    ['label','sub']
 * @param string $appUrl
 * @param string $dateLabel e.g. "Monday, 24 March 2026"
 */
function tplDailyDigest(string $recipientName, array $sections, array $missed, string $appUrl, string $dateLabel): string
{
    $hasContent = false;
    $sectionsHtml = '';

    foreach ($sections as $sec) {
        if (empty($sec['items'])) continue;
        $hasContent = true;
        $rows = '';
        foreach ($sec['items'] as $it) {
            $label   = htmlspecialchars($it['label'] ?? '');
            $sub     = htmlspecialchars($it['sub']   ?? '');
            $urgent  = !empty($it['urgent']);
            $rows .= "<tr>
              <td style='padding:8px 0;border-bottom:1px solid #f3f4f6;vertical-align:top'>
                <div style='font-size:13px;font-weight:600;color:" . ($urgent ? '#dc2626' : '#111827') . "'>{$label}</div>
                " . ($sub ? "<div style='font-size:11px;color:#6b7280;margin-top:2px'>{$sub}</div>" : '') . "
              </td>
            </tr>";
        }
        $count = count($sec['items']);
        $sectionsHtml .= "<div style='margin-bottom:20px'>
            <div style='display:flex;align-items:center;gap:8px;margin-bottom:10px;padding-bottom:6px;border-bottom:2px solid {$sec['color']}'>
              <span style='font-size:1.1rem'>{$sec['icon']}</span>
              <span style='font-weight:700;font-size:14px;color:{$sec['color']}'>{$sec['title']}</span>
              <span style='font-size:11px;color:#9ca3af;margin-left:auto'>{$count} item" . ($count!==1?'s':'') . "</span>
            </div>
            <table width='100%' cellpadding='0' cellspacing='0'>{$rows}</table>
          </div>";
    }

    $missedHtml = '';
    if (!empty($missed)) {
        $missedRows = '';
        foreach ($missed as $it) {
            $label = htmlspecialchars($it['label'] ?? '');
            $sub   = htmlspecialchars($it['sub']   ?? '');
            $missedRows .= "<tr><td style='padding:6px 0;border-bottom:1px solid #fecdd3'>
              <div style='font-size:13px;font-weight:600;color:#dc2626'>{$label}</div>
              " . ($sub ? "<div style='font-size:11px;color:#ef4444;margin-top:1px'>{$sub}</div>" : '') . "
            </td></tr>";
        }
        $mc = count($missed);
        $missedHtml = "<div style='background:#fff5f5;border:1.5px solid #fca5a5;border-radius:8px;padding:14px 16px;margin-top:20px'>
          <div style='font-weight:700;font-size:13px;color:#dc2626;margin-bottom:8px'>⚠ Missed / Overdue ({$mc})</div>
          <table width='100%' cellpadding='0' cellspacing='0'>{$missedRows}</table>
        </div>";
    }

    if (!$hasContent && empty($missed)) {
        $sectionsHtml = "<div style='text-align:center;padding:20px;color:#6b7280;font-size:14px'>🎉 Nothing scheduled for today — enjoy your day!</div>";
    }

    $link = $appUrl ? emailButton('📅 Open App', $appUrl) : '';

    $body = <<<BODY
<p style="font-size:15px;color:#111827;margin:0 0 4px">Good morning, {$recipientName}!</p>
<p style="font-size:13px;color:#6b7280;margin:0 0 20px">Here's your daily summary for <strong>{$dateLabel}</strong>.</p>

{$sectionsHtml}
{$missedHtml}
{$link}
BODY;

    return emailWrapper("📅 Your Day — {$dateLabel}", $body, "You are receiving this because you have items scheduled for today. This email is sent each morning by Elegant Work.");
}