<?php

namespace App\Services\Whmcs;

use App\Models\SupportAgent;
use App\Models\Ticket;
use Carbon\Carbon;

/**
 * Substitutes {variable} placeholders in agent header/footer templates with
 * per-ticket values. See SupportAgent::TEMPLATE_VARIABLES for the full list.
 */
class TemplateRenderer
{
    public function render(string $template, Ticket $ticket, SupportAgent $agent): string
    {
        if ($template === '') return '';

        // {day_greeting} retired — strip the var AND adjacent in-line
        // punctuation/whitespace (e.g. "{day_greeting}!", "Hi! {day_greeting},
        // ") so we don't leave orphan "!" or "," behind. Crucially, do NOT
        // consume the newline after the variable — losing newlines collapses
        // the header onto the body line. The blank-line collapsing pass at
        // the end handles any extra vertical gap we leave behind.
        $template = preg_replace('/[ \t]*\{day_greeting\}[\p{P} \t]*/u', '', $template);

        $vars = $this->buildVars($ticket, $agent);
        $rendered = strtr($template, $vars);

        // Belt-and-braces: drop lines that ended up containing only whitespace
        // plus punctuation (defensive against weird custom templates).
        $lines = preg_split('/\r?\n/', $rendered);
        $lines = array_map(function ($ln) {
            return preg_match('/^[\s\p{P}]*$/u', $ln) && trim($ln) !== '' ? '' : $ln;
        }, $lines);

        $out = implode("\n", $lines);
        return preg_replace("/\n{3,}/", "\n\n", $out);
    }

    private function buildVars(Ticket $ticket, SupportAgent $agent): array
    {
        $now = Carbon::now('Asia/Dhaka');
        $name = trim((string) $ticket->customer_name);
        $first = self::extractFirstName($name);

        return [
            '{customer_name}'        => $name ?: 'Valued Customer',
            '{customer_first_name}'  => $first,
            '{ticket_number}'        => (string) $ticket->whmcs_ticket_num,
            '{ticket_subject}'       => (string) $ticket->subject,
            '{agent_name}'           => (string) $agent->display_name,
            '{company}'              => 'HostSeba',
            '{date}'                 => $now->format('j F Y'),
            // {day_greeting} retired — was producing "Good Morning" lines that
            // made replies look canned/AI. Substituted to empty for back-compat
            // with any existing template rows that still reference it (any
            // trailing punctuation/blank line is collapsed by HumanizedReplyDrafter
            // when it stitches header → body → footer).
            '{day_greeting}'         => '',
        ];
    }

    /**
     * Extract a customer's actual first/given name from the raw WHMCS
     * `customer_name` string. Handles the three Bangladeshi naming patterns
     * we kept getting wrong:
     *
     *   "Md Abdus Sobhan"          → "Abdus"   (drops "Md" honorific)
     *   "MD MARUF AHMED"           → "Maruf"   (drops "MD", title-cases)
     *   "BIBHASH KUMAR SAHA ROY"   → "Bibhash" (title-cases ALL-CAPS)
     *   "Elen Alfred"              → "Elen"    (already title-cased — pass through)
     *
     * Falls back to "there" for empty / one-honorific-only names so the
     * greeting still renders ("Dear there," is the standard fallback).
     */
    public static function extractFirstName(string $rawName): string
    {
        $name = trim($rawName);
        if ($name === '') return 'there';

        // Collapse whitespace ("MD MARUF  AHMED" has a double-space).
        $parts = preg_split('/\s+/', $name) ?: [];

        // Drop common Bangladeshi / English honorifics at the start. Case-
        // insensitive, tolerant of trailing dots ("Md." / "Mr.").
        $honorifics = [
            'md', 'md.', 'mohammad', 'muhammad', 'mohd', 'mohd.',
            'mst', 'mst.', 'most', 'most.',
            'mr', 'mr.', 'mrs', 'mrs.', 'ms', 'ms.', 'miss',
            'dr', 'dr.', 'engr', 'engr.', 'prof', 'prof.',
            'sk', 'sk.',
        ];
        while (! empty($parts) && in_array(strtolower($parts[0]), $honorifics, true)) {
            array_shift($parts);
        }

        $first = $parts[0] ?? '';
        if ($first === '') return 'there';

        // Title-case so ALL-CAPS WHMCS entries (very common from BD
        // customers typing in Caps Lock) render as "Raiyan" not "RAIYAN".
        // mb_convert_case handles non-ASCII bytes safely; Bangla script
        // (which has no case anyway) passes through untouched.
        return mb_convert_case($first, MB_CASE_TITLE, 'UTF-8');
    }
}
