<?php
/**
 * Email template: Weekly site health summary
 * Sent Monday mornings to every active ai_monitor_subscriptions row.
 *
 * Render API mirrors the spec — returns BOTH bodies as an array so the
 * caller can drop the result straight into the email queue:
 *
 *   $rendered = render_weekly_summary($data);
 *   // $rendered['html'], $rendered['text']
 *
 * Expected $data shape:
 *   [
 *     'week_of'      => '2026-04-27',         // Monday of the reporting week
 *     'sites'        => [                     // one row per site
 *        [
 *          'site_name'   => 'foo.com',
 *          'domain'      => 'foo.com',
 *          'whois'       => ['status' => 'ok'|'expiring'|'expired'|'unparsed'|'skipped',
 *                            'days_left' => int|null, 'apex' => string|null],
 *          'ssl'         => ['status' => 'ok'|'expiring'|'expired'|'unreachable',
 *                            'days_left' => int|null],
 *          'dns'         => ['status' => 'ok'|'cdn'|'mismatch'|'nxdomain'|'skipped',
 *                            'ips' => string[], 'cdn' => string|null],
 *        ], ...
 *     ],
 *     'issues_opened'   => int,
 *     'issues_resolved' => int,
 *     'top_issues'      => [                  // up to 5
 *        ['severity' => 'critical', 'title' => '...', 'site' => '...'], ...
 *     ],
 *     'advisories'      => string[],          // plain-English bullets
 *     'dashboard_url'   => 'https://...',
 *   ]
 *
 * Returns: ['html' => string, 'text' => string]
 */
function render_weekly_summary(array $data): array {
    $week_of         = htmlspecialchars($data['week_of'] ?? date('Y-m-d'), ENT_QUOTES, 'UTF-8');
    $sites           = $data['sites'] ?? [];
    $issues_opened   = (int)($data['issues_opened'] ?? 0);
    $issues_resolved = (int)($data['issues_resolved'] ?? 0);
    $top_issues      = $data['top_issues'] ?? [];
    $advisories      = $data['advisories'] ?? [];
    $dashboard_url   = htmlspecialchars($data['dashboard_url'] ?? '#', ENT_QUOTES, 'UTF-8');

    // ----- Status formatters (HTML) ------------------------------------
    $domain_cell = static function (array $whois): array {
        $status    = $whois['status'] ?? 'skipped';
        $daysLeft  = $whois['days_left'] ?? null;
        if ($status === 'ok' && $daysLeft !== null) {
            $color = $daysLeft >= 60 ? '#198754' : ($daysLeft >= 30 ? '#fd7e14' : '#dc3545');
            return ['text' => "expires in {$daysLeft} days", 'color' => $color];
        }
        if ($status === 'expiring' && $daysLeft !== null) {
            $color = $daysLeft >= 30 ? '#fd7e14' : '#dc3545';
            return ['text' => "expires in {$daysLeft} days", 'color' => $color];
        }
        if ($status === 'expired') {
            $abs = $daysLeft !== null ? abs((int)$daysLeft) : 0;
            return ['text' => "EXPIRED {$abs} days ago", 'color' => '#dc3545'];
        }
        if ($status === 'unparsed') return ['text' => 'WHOIS unavailable', 'color' => '#6c757d'];
        return ['text' => 'WHOIS skipped', 'color' => '#6c757d'];
    };
    $ssl_cell = static function (array $ssl): array {
        $status   = $ssl['status'] ?? 'unreachable';
        $daysLeft = $ssl['days_left'] ?? null;
        if ($status === 'ok' && $daysLeft !== null) {
            $color = $daysLeft >= 30 ? '#198754' : ($daysLeft >= 14 ? '#fd7e14' : '#dc3545');
            $tag = $daysLeft < 30 ? ' — RENEW SOON' : '';
            return ['text' => "expires in {$daysLeft} days{$tag}", 'color' => $color];
        }
        if ($status === 'expiring' && $daysLeft !== null) {
            $color = $daysLeft >= 14 ? '#fd7e14' : '#dc3545';
            return ['text' => "expires in {$daysLeft} days — RENEW SOON", 'color' => $color];
        }
        if ($status === 'expired') {
            $abs = $daysLeft !== null ? abs((int)$daysLeft) : 0;
            return ['text' => "EXPIRED {$abs} days ago", 'color' => '#dc3545'];
        }
        return ['text' => 'no certificate reachable', 'color' => '#6c757d'];
    };
    $dns_cell = static function (array $dns): array {
        $status = $dns['status'] ?? 'skipped';
        $ips    = is_array($dns['ips'] ?? null) ? $dns['ips'] : [];
        $first  = $ips[0] ?? '';
        if ($status === 'ok')       return ['text' => "OK — resolves to {$first}", 'color' => '#198754'];
        if ($status === 'cdn')      return ['text' => "OK — behind " . ($dns['cdn'] ?? 'CDN'), 'color' => '#198754'];
        if ($status === 'mismatch') return ['text' => "WRONG TARGET — " . ($first ?: 'unexpected IP'), 'color' => '#dc3545'];
        if ($status === 'nxdomain') return ['text' => 'FAILED — does not resolve', 'color' => '#dc3545'];
        return ['text' => 'skipped', 'color' => '#6c757d'];
    };

    // ----- Per-site rows (HTML) ----------------------------------------
    $rows_html = '';
    foreach ($sites as $idx => $site) {
        $site_name = htmlspecialchars((string)($site['site_name'] ?? ($site['domain'] ?? '?')), ENT_QUOTES, 'UTF-8');
        $domain    = htmlspecialchars((string)($site['domain'] ?? ''), ENT_QUOTES, 'UTF-8');
        $d = $domain_cell(is_array($site['whois'] ?? null) ? $site['whois'] : []);
        $s = $ssl_cell(is_array($site['ssl']   ?? null) ? $site['ssl']   : []);
        $n = $dns_cell(is_array($site['dns']   ?? null) ? $site['dns']   : []);

        $border = $idx > 0 ? 'border-top:1px solid #e9ecef;' : '';
        $d_text = htmlspecialchars($d['text'], ENT_QUOTES, 'UTF-8');
        $s_text = htmlspecialchars($s['text'], ENT_QUOTES, 'UTF-8');
        $n_text = htmlspecialchars($n['text'], ENT_QUOTES, 'UTF-8');

        $rows_html .= <<<ROW
<tr>
<td style="padding:14px 16px; {$border}">
    <div style="font-size:14px; font-weight:600; color:#212529; margin-bottom:6px;">{$site_name}</div>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
    <tr>
        <td style="font-size:12px; color:#6c757d; padding:2px 0; width:80px;">Domain:</td>
        <td style="font-size:13px; color:{$d['color']}; padding:2px 0; font-weight:500;">{$d_text}</td>
    </tr>
    <tr>
        <td style="font-size:12px; color:#6c757d; padding:2px 0;">SSL:</td>
        <td style="font-size:13px; color:{$s['color']}; padding:2px 0; font-weight:500;">{$s_text}</td>
    </tr>
    <tr>
        <td style="font-size:12px; color:#6c757d; padding:2px 0;">DNS:</td>
        <td style="font-size:13px; color:{$n['color']}; padding:2px 0; font-weight:500;">{$n_text}</td>
    </tr>
    </table>
</td>
</tr>
ROW;
    }
    if ($rows_html === '') {
        $rows_html = '<tr><td style="padding:16px; font-size:13px; color:#6c757d;">No sites under this subscription.</td></tr>';
    }

    // ----- Top issues block (HTML) -------------------------------------
    $sev_colors = [
        'critical' => '#dc3545',
        'warning'  => '#fd7e14',
        'info'     => '#0d6efd',
    ];
    $issues_html = '';
    foreach ($top_issues as $i => $iss) {
        $sev   = strtolower(trim((string)($iss['severity'] ?? 'info')));
        $bg    = $sev_colors[$sev] ?? $sev_colors['info'];
        $sev_l = htmlspecialchars(ucfirst($sev), ENT_QUOTES, 'UTF-8');
        $title = htmlspecialchars((string)($iss['title'] ?? ''), ENT_QUOTES, 'UTF-8');
        $isite = htmlspecialchars((string)($iss['site']  ?? ''), ENT_QUOTES, 'UTF-8');
        $border = $i > 0 ? 'border-top:1px solid #e9ecef;' : '';
        $issues_html .= <<<I
<tr>
<td style="padding:10px 14px; {$border}">
    <span style="display:inline-block; padding:2px 8px; border-radius:3px; font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:0.4px; color:#fff; background-color:{$bg}; margin-right:8px;">{$sev_l}</span>
    <span style="font-size:13px; color:#212529; font-weight:500;">{$title}</span>
    <div style="margin-top:4px; font-size:12px; color:#6c757d;">{$isite}</div>
</td>
</tr>
I;
    }
    if ($issues_html === '') {
        $issues_html = '<tr><td style="padding:14px; font-size:13px; color:#6c757d;">No issues this week — nice.</td></tr>';
    }

    // ----- Advisories (HTML) -------------------------------------------
    $advisories_html = '';
    foreach ($advisories as $adv) {
        $advisories_html .= '<li style="font-size:13px; color:#495057; line-height:1.6; margin-bottom:6px;">'
            . htmlspecialchars((string)$adv, ENT_QUOTES, 'UTF-8') . '</li>';
    }
    if ($advisories_html === '') {
        $advisories_html = '<li style="font-size:13px; color:#6c757d; line-height:1.6;">No advisories this week — everything looks healthy.</li>';
    }

    $issues_label = "{$issues_opened} issue" . ($issues_opened === 1 ? '' : 's')
                  . " opened this week, {$issues_resolved} resolved.";

    $html = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weekly Site Health Summary</title>
</head>
<body style="margin:0; padding:0; background-color:#f4f5f7; font-family:Arial, Helvetica, sans-serif; -webkit-text-size-adjust:100%; -ms-text-size-adjust:100%;">

<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f4f5f7;">
<tr><td align="center" style="padding:24px 16px;">

<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width:600px; width:100%; background-color:#ffffff; border-radius:8px; overflow:hidden; box-shadow:0 1px 3px rgba(0,0,0,0.08);">

<!-- Header -->
<tr>
<td style="background-color:#1a1a2e; padding:24px 32px;">
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
    <tr>
        <td style="color:#ffffff; font-size:20px; font-weight:bold; letter-spacing:0.5px;">WHP AI Monitor</td>
        <td align="right" style="color:#a0a0b8; font-size:13px;">Weekly Summary</td>
    </tr>
    </table>
</td>
</tr>

<!-- Title -->
<tr>
<td style="padding:28px 32px 8px 32px;">
    <h1 style="margin:0; font-size:20px; font-weight:700; color:#212529; line-height:1.4;">Weekly Site Health Summary</h1>
    <div style="margin-top:6px; font-size:13px; color:#6c757d;">Week of {$week_of}</div>
</td>
</tr>

<!-- Per-site grid -->
<tr>
<td style="padding:20px 32px 8px 32px;">
    <h2 style="margin:0 0 10px 0; font-size:14px; font-weight:700; color:#495057; text-transform:uppercase; letter-spacing:0.3px;">Sites</h2>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f8f9fa; border-radius:6px; border:1px solid #e9ecef;">
    {$rows_html}
    </table>
</td>
</tr>

<!-- Issues block -->
<tr>
<td style="padding:20px 32px 8px 32px;">
    <h2 style="margin:0 0 10px 0; font-size:14px; font-weight:700; color:#495057; text-transform:uppercase; letter-spacing:0.3px;">Issues This Week</h2>
    <p style="margin:0 0 10px 0; font-size:13px; color:#495057;">{$issues_label}</p>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f8f9fa; border-radius:6px; border:1px solid #e9ecef;">
    {$issues_html}
    </table>
</td>
</tr>

<!-- Advisories -->
<tr>
<td style="padding:20px 32px 8px 32px;">
    <h2 style="margin:0 0 10px 0; font-size:14px; font-weight:700; color:#495057; text-transform:uppercase; letter-spacing:0.3px;">Advisories</h2>
    <ul style="margin:0; padding-left:20px;">
    {$advisories_html}
    </ul>
</td>
</tr>

<!-- Button -->
<tr>
<td align="center" style="padding:24px 32px 32px 32px;">
    <a href="{$dashboard_url}" style="display:inline-block; padding:12px 28px; background-color:#1a1a2e; color:#ffffff; font-size:14px; font-weight:600; text-decoration:none; border-radius:6px;">Open Monitoring Panel</a>
</td>
</tr>

<!-- Footer -->
<tr>
<td style="background-color:#f8f9fa; padding:20px 32px; border-top:1px solid #e9ecef;">
    <p style="margin:0; font-size:12px; color:#868e96; line-height:1.5; text-align:center;">You're receiving this weekly summary because you have AI monitoring enabled.</p>
</td>
</tr>

</table>

</td></tr>
</table>

</body>
</html>
HTML;

    // ----- Plain-text body ---------------------------------------------
    $textLines = [];
    $textLines[] = "Weekly Site Health Summary -- week of " . ($data['week_of'] ?? date('Y-m-d'));
    $textLines[] = str_repeat('=', 60);
    $textLines[] = '';
    $textLines[] = 'SITES';
    $textLines[] = str_repeat('-', 60);
    foreach ($sites as $site) {
        $textLines[] = (string)($site['site_name'] ?? ($site['domain'] ?? '?'));
        $d = $domain_cell(is_array($site['whois'] ?? null) ? $site['whois'] : []);
        $s = $ssl_cell(is_array($site['ssl']   ?? null) ? $site['ssl']   : []);
        $n = $dns_cell(is_array($site['dns']   ?? null) ? $site['dns']   : []);
        $textLines[] = '  Domain: ' . $d['text'];
        $textLines[] = '  SSL:    ' . $s['text'];
        $textLines[] = '  DNS:    ' . $n['text'];
        $textLines[] = '';
    }
    $textLines[] = 'ISSUES THIS WEEK';
    $textLines[] = str_repeat('-', 60);
    $textLines[] = "{$issues_opened} opened, {$issues_resolved} resolved.";
    foreach ($top_issues as $iss) {
        $sev = strtoupper((string)($iss['severity'] ?? 'info'));
        $textLines[] = "  [{$sev}] " . (string)($iss['title'] ?? '') . ' (' . (string)($iss['site'] ?? '') . ')';
    }
    if (empty($top_issues)) {
        $textLines[] = '  None.';
    }
    $textLines[] = '';
    $textLines[] = 'ADVISORIES';
    $textLines[] = str_repeat('-', 60);
    if (empty($advisories)) {
        $textLines[] = '  No advisories — everything looks healthy.';
    } else {
        foreach ($advisories as $adv) {
            $textLines[] = '  - ' . (string)$adv;
        }
    }
    $textLines[] = '';
    $textLines[] = 'Open the panel: ' . ($data['dashboard_url'] ?? '');

    return [
        'html' => $html,
        'text' => implode("\n", $textLines),
    ];
}
