@php
    use App\General\SettingsClass;
    use Illuminate\Support\Facades\DB;
    use App\Models\User;
    use App\Models\Adminsettings;

    $logoPath = null;
    $companyName = env('APP_NAME', 'WMS');
    $companyAddress = '';
    $companyCity = '';
    $companyState = '';
    $companyPostCode = '';
    $companyCountry = '';
    $companyPhone = 'Contact Information';
    $companyEmail = env('EMAIL_ADDRESS', 'support@example.com');

    // Get admin settings data
    $admin = User::where('user_type', config('constants.user_types.admin'))->first();
    if ($admin) {
        $settings = DB::table('adminsettings')->where('customer_id', $admin->id)->get();

        // Transform into key-value pairs for easier access
        $settingsData = [];
        foreach ($settings as $setting) {
            $settingsData[$setting->key] = $setting->value;
        }

        // Get logo
        if (isset($settingsData['brand_logo_dark'])) {
            $logoPath = $settingsData['brand_logo_dark'];
        }

        // Get company information
        if (isset($settingsData['company_company_name'])) {
            $companyName = $settingsData['company_company_name'];
        }
        if (isset($settingsData['company_company_address'])) {
            $companyAddress = $settingsData['company_company_address'];
        }

        if (isset($settingsData['company_company_city'])) {
            $companyCity = $settingsData['company_company_city'];
        }

        if (isset($settingsData['company_company_state'])) {
            $companyState = $settingsData['company_company_state'];
        }

        if (isset($settingsData['company_company_post_code'])) {
            $companyPostCode = $settingsData['company_company_post_code'];
        }

        if (isset($settingsData['company_company_country'])) {
            $companyCountry = $settingsData['company_company_country'];
        }

        if (isset($settingsData['company_company_telephone'])) {
            $companyPhone = $settingsData['company_company_telephone'];
        }

        if (isset($settingsData['company_company_email'])) {
            $companyEmail = $settingsData['company_company_email'];
        }
    }

    // Get system date and time format settings
    $systemDateFormat = 'd-m-Y'; // Default format
    $systemTimeFormat = 'H:i'; // Default 24-hour format

    if ($admin) {
        $dateSetting = Adminsettings::where('customer_id', $admin->id)->where('key', 'system_date_format')->first();

        $timeSetting = Adminsettings::where('customer_id', $admin->id)->where('key', 'system_time_format')->first();

        if ($dateSetting && $dateSetting->value) {
            // Convert system format to Carbon format
            $formatMap = [
                'mm-dd-yyyy' => 'm-d-Y',
                'dd-mm-yyyy' => 'd-m-Y',
                'yyyy-mm-dd' => 'Y-m-d',
                'mm/dd/yyyy' => 'm/d/Y',
                'dd/mm/yyyy' => 'd/m/Y',
                'yyyy/mm/dd' => 'Y/m/d',
            ];
            $systemDateFormat = $formatMap[strtolower($dateSetting->value)] ?? 'd-m-Y';
        }

        if ($timeSetting && $timeSetting->value) {
            // Check if the format contains AM/PM or if user prefers 12-hour format
            $value = strtoupper($timeSetting->value);
            if (
                str_contains($value, 'AM') ||
                str_contains($value, 'PM') ||
                str_contains($value, '12') ||
                str_contains($value, 'HOUR')
            ) {
                $systemTimeFormat = 'g:i A'; // 12-hour format with AM/PM
            }
        }
    }

    // Format full address
    $fullAddress = $companyAddress;
    if (!empty($companyCity)) {
        $fullAddress .= ', ' . $companyCity;
    }
    if (!empty($companyState)) {
        $fullAddress .= ', ' . $companyState;
    }
    if (!empty($companyPostCode)) {
        $fullAddress .= ' ' . $companyPostCode;
    }
    if (!empty($companyCountry)) {
        $fullAddress .= ', ' . $companyCountry;
    }
    // Set defaults for variables that might not be provided
    if (!isset($subject)) {
        $subject = 'Helpdesk Ticket Update';
    }

    // Default status configuration in case it's not provided
if (!isset($status_config)) {
    $status_config = [
        'status_text' => 'Unknown',
        'color' => '#6B7280', // Gray
        'background' => 'linear-gradient(135deg, #F3F4F6 0%, #E5E7EB 100%)',
        'icon' => '📄',
        'message' => 'Ticket status information.',
        ];
    }
@endphp

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>{{ $subject }}</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap"
        rel="stylesheet">
    <style>
        * {
            padding: 0;
            margin: 0;
            font-family: 'Inter', sans-serif !important;
            box-sizing: border-box;
        }

        body {
            background-color: #f8f9fa;
            padding: 20px 0;
        }

        #email-body {
            min-width: 600px;
            width: 600px;
            max-width: 600px;
            margin: 0 auto;
            background-color: #ffffff;
            font-family: 'Inter', sans-serif !important;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            overflow: hidden;
        }

        #email-footer {
            margin-top: 20px;
        }

        #email-header {
            padding: 18px 25px;
            background: #fff !important;
            text-align: left;
            position: relative;
        }

        #email-header::after {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100%;
            background: #fff !important;
            transform: skew(-15deg);
            transform-origin: top right;
        }

        #email-header img {
            height: 54px;
            width: auto;
            display: inline-block;
        }

        #email-header h2 {
            color: {{ $status_config['color'] }};
            margin: 0;
            font-weight: 700;
            font-size: 24px;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        #email-content {
            padding: 42px 34px;
            color: #333333;
        }

        .greeting-section {
            font-size: 14px;
            margin-bottom: 18px;
            color: #6b7280;
        }

        .greeting-section strong {
            color: #1f2937;
            font-weight: 600;
        }

        .notification-title {
            font-size: 22px;
            font-weight: 700;
            margin-bottom: 20px;
            color: {{ $status_config['color'] }};
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .notification-title::before {
            content: "{{ $status_config['icon'] }}";
            font-size: 24px;
        }

        .alert-box {
            background: {{ $status_config['background'] }};
            border: 1px solid {{ $status_config['color'] }};
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 24px;
            position: relative;
        }

        .alert-box::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            width: 4px;
            background: {{ $status_config['color'] }};
            border-radius: 4px 0 0 4px;
        }

        .alert-box p {
            margin: 0;
            font-size: 14px;
            color: {{ $status_config['color'] }};
            font-weight: 500;
        }

        .info-card {
            background: #f9fafb;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            position: relative;
            transition: transform 0.2s ease;
        }

        .info-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .info-card h3 {
            color: #1f2937;
            margin-bottom: 12px;
            font-weight: 600;
            font-size: 16px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .ticket-details h3::before {
            content: '🎫';
            font-size: 18px;
        }

        .customer-details h3::before {
            content: '👤';
            font-size: 18px;
        }

        .info-card p {
            margin-bottom: 8px;
            font-size: 14px;
            color: #374151;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .info-card p:last-child {
            margin-bottom: 0;
        }

        .info-card strong {
            font-weight: 600;
            color: #1f2937;
            min-width: 120px;
        }

        .info-value {
            font-weight: 500;
            color: #4b5563;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            background: {{ $status_config['background'] }};
            color: {{ $status_config['color'] }};
            border: 1px solid {{ $status_config['color'] }};
        }

        .email-content-area p {
            font-size: 14px;
            margin-bottom: 15px;
            line-height: 1.6;
            color: #4b5563;
        }

        .conversation-wrapper {
            margin-top: 20px;
            margin-bottom: 20px;
            height: 300px;
            overflow: auto;
            min-height: 300px;
        }

        .conversation-item {
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            background-color: #fff;
        }

        .conversation-item:last-child {
            border-color: {{ $status_config['color'] }};
            background-color: {{ $status_config['background'] }};
        }

        /* Admin message styles */
        .conversation-item.admin-message {
            border-left: 4px solid #3B82F6;
            /* Blue border */
            background-color: #EFF6FF;
            /* Light blue background */
        }

        /* Customer message styles */
        .conversation-item.customer-message {
            border-left: 4px solid #10B981;
            /* Green border */
            background-color: #ECFDF5;
            /* Light green background */
        }

        .conversation-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            padding-bottom: 8px;
            border-bottom: 1px solid #e5e7eb;
            font-size: 13px;
        }

        .conversation-sender {
            font-weight: 600;
            color: #374151;
            display: flex;
            align-items: center;
        }

        .admin-message .conversation-sender {
            color: #1E40AF;
            /* Darker blue for admin names */
        }

        .customer-message .conversation-sender {
            color: #047857;
            /* Darker green for customer names */
        }

        .sender-badge {
            font-size: 10px;
            font-weight: 600;
            padding: 2px 6px;
            border-radius: 10px;
            margin-left: 8px;
            text-transform: uppercase;
        }

        .admin-badge {
            background-color: #DBEAFE;
            color: #1E40AF;
        }

        .customer-badge {
            background-color: #D1FAE5;
            color: #047857;
        }

        .conversation-time {
            color: #6b7280;
        }

        .conversation-body {
            color: #1f2937;
            font-size: 14px;
            line-height: 1.6;
        }

        .conversation-attachment {
            margin-top: 10px;
            padding: 8px 12px;
            background-color: #f3f4f6;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            font-size: 13px;
        }

        .attachment-link {
            display: flex;
            align-items: center;
            color: #4f46e5;
            text-decoration: none;
            font-weight: 500;
            transition: color 0.2s;
        }

        .attachment-link:hover {
            color: #4338ca;
            text-decoration: underline;
        }

        .attachment-icon {
            margin-right: 6px;
            font-size: 16px;
        }

        .footer-text {
            text-align: center;
            font-size: 12px;
            color: #6b7280;
            margin-top: 30px;
            padding-top: 15px;
            border-top: 1px solid #e5e7eb;
        }

        .footer-links {
            text-align: center;
            font-size: 12px;
            margin-top: 10px;
        }

        .footer-links a {
            color: #6b7280;
            text-decoration: none;
            margin: 0 10px;
        }

        .footer-links a:hover {
            text-decoration: underline;
        }

        .company-details {
            text-align: center;
            padding: 20px 0;
            background-color: #ffffff;
        }

        .company-title {
            font-size: 14px;
            font-weight: 600;
            color: #374151;
            margin-bottom: 5px;
        }

        .company-address-contact {
            color: #6b7280;
            font-size: 12px;
            line-height: 1.4;
        }

        #tagline-section {
            background-color: #EDEDED;
            padding: 16px;
            text-align: center;
            font-size: 13px;
            color: #6b7280;
        }

        .small-tagline {
            font-size: 13px;
            color: #6b7280;
            margin-bottom: 4px;
        }

        .big-tagline {
            font-size: 14px;
            color: #374151;
        }

        .big-tagline a {
            color: #787f83;
            font-weight: 700;
            text-decoration: none;
        }

        .footer-logo {
            height: 30px;
            margin-bottom: 8px;
        }
    </style>
</head>

<body>
    <div id="email-body">
        <div id="email-header">
            @if (!empty($logoPath) && file_exists(public_path($logoPath)))
                <img src="{{ url($logoPath) }}" alt="WMS Logo" />
            @else
                <h2>{{ $companyName }}</h2>
            @endif
        </div>

        <div id="email-content">
            <div class="greeting-section">
                <p>
                    @if ($recipient == 'customer')
                        Hello, <strong>{{ $ticket->name }}</strong>
                    @else
                        <strong>Admin Support Team Alert</strong>
                    @endif
                </p>
            </div>

            <h2 class="notification-title">
                @if ($recipient == 'customer')
                    @if (isset($adminCreated) && $adminCreated)
                        New Support Ticket Created for You: {{ $status_config['status_text'] }}
                    @else
                        Your Ticket Update: {{ $status_config['status_text'] }}
                    @endif
                @else
                    New Support Ticket Update: {{ $status_config['status_text'] }}
                @endif
            </h2>

            <div class="alert-box">
                <p>
                    @if ($recipient == 'customer')
                        @if (isset($adminCreated) && $adminCreated)
                            <strong>Welcome!</strong> Our support team has created a ticket on your behalf to help
                            resolve your issue. Please review the details below and feel free to respond with any
                            additional information.
                        @else
                            {{ $status_config['message'] }}
                        @endif
                    @else
                        This ticket requires your attention. A new reply has been added to ticket
                        {{ $ticket->ticket_id }}.
                    @endif
                </p>
            </div>

            @if (isset($adminCreated) && $adminCreated && $recipient == 'customer')
                <div class="info-card" style="background: #f0f9ff; border-color: #0284c7;">
                    <h3 style="color: #0284c7;">📋 Ticket Created by Support Team</h3>
                    <p style="color: #0369a1; margin: 0;">
                        This ticket was created by our support team to assist you. You can reply to this email or use
                        the ticket system to provide additional information or ask questions.
                    </p>
                </div>
            @endif

            <div class="info-card ticket-details">
                <h3>Ticket Information</h3>
                <p>
                    <strong>Ticket ID:</strong>
                    <span class="info-value">{{ $ticket->ticket_id }}</span>
                </p>
                <p>
                    <strong>Subject:</strong>
                    <span class="info-value">{{ $ticket->subject }}</span>
                </p>
                <p>
                    <strong>Category:</strong>
                    <span
                        class="info-value">{{ $ticket->getRelation('category') ? $ticket->getRelation('category')->name : 'N/A' }}</span>
                </p>
                <p>
                    <strong>Status:</strong>
                    <span class="status-badge">{{ $status_config['status_text'] }}</span>
                </p>
                <p>
                    <strong>Created:</strong>
                    <span class="info-value">
                        @if (isset($formattedTicket))
                            {{ $formattedTicket['created_at'] }}
                        @else
                            {{ $ticket->created_at->format($systemDateFormat . ' ' . $systemTimeFormat) }}
                        @endif
                    </span>
                </p>
            </div>

            @if ($recipient == 'admin')
                <div class="info-card customer-details">
                    <h3>Customer Information</h3>
                    <p>
                        <strong>Name:</strong>
                        <span class="info-value">{{ $ticket->name }}</span>
                    </p>
                    <p>
                        <strong>Email:</strong>
                        <span class="info-value">{{ $ticket->email }}</span>
                    </p>
                </div>
            @endif

            <div class="email-content-area">
                <h3 style="margin-bottom: 15px; color: #1f2937;">Ticket Conversation</h3>

                <div class="conversation-wrapper">
                    @if (isset($conversations))
                        @foreach ($conversations as $conversation)
                            @php
                                $isAdmin =
                                    isset($conversation['sender_user']) &&
                                    $conversation['sender_user']['user_type'] == config('constants.user_types.admin');
                                $isCustomer =
                                    isset($conversation['sender_user']) &&
                                    $conversation['sender_user']['user_type'] ==
                                        config('constants.user_types.customer');
                                $messageClass = $isAdmin ? 'admin-message' : 'customer-message';
                                $badgeClass = $isAdmin ? 'admin-badge' : 'customer-badge';
                                $badgeText = $isAdmin ? 'ADMIN' : 'CUSTOMER';
                            @endphp
                            <div class="conversation-item {{ $messageClass }}">
                                <div class="conversation-header">
                                    <span class="conversation-sender">
                                        {{ isset($conversation['sender_user']) ? $conversation['sender_user']['name'] : 'Unknown User' }}
                                        <span class="sender-badge {{ $badgeClass }}">{{ $badgeText }}</span>
                                    </span>
                                    <span class="conversation-time">
                                        {{ $conversation['created_at'] }}
                                    </span>
                                </div>
                                <div class="conversation-body">
                                    {{ $conversation['descriptions'] }}
                                </div>
                                @if ($conversation['attachments'])
                                    <div class="conversation-attachment">
                                        <a href="{{ url($conversation['attachments']) }}" class="attachment-link"
                                            target="_blank">
                                            <span class="attachment-icon">📎</span>
                                            Preview Attachment
                                        </a>
                                    </div>
                                @endif
                            </div>
                        @endforeach
                    @else
                        @foreach ($ticket->conversations->sortByDesc('created_at') as $conversation)
                            @php
                                $isAdmin =
                                    $conversation->senderUser &&
                                    $conversation->senderUser->user_type == config('constants.user_types.admin');
                                $isCustomer =
                                    $conversation->senderUser &&
                                    $conversation->senderUser->user_type == config('constants.user_types.customer');
                                $messageClass = $isAdmin ? 'admin-message' : 'customer-message';
                                $badgeClass = $isAdmin ? 'admin-badge' : 'customer-badge';
                                $badgeText = $isAdmin ? 'ADMIN' : 'CUSTOMER';
                            @endphp
                            <div class="conversation-item {{ $messageClass }}">
                                <div class="conversation-header">
                                    <span class="conversation-sender">
                                        {{ $conversation->senderUser ? $conversation->senderUser->name : 'Unknown User' }}
                                        <span class="sender-badge {{ $badgeClass }}">{{ $badgeText }}</span>
                                    </span>
                                    <span class="conversation-time">
                                        {{ $conversation->created_at->format($systemDateFormat . ' ' . $systemTimeFormat) }}
                                    </span>
                                </div>
                                <div class="conversation-body">
                                    {{ $conversation->descriptions }}
                                </div>
                                @if ($conversation->attachments)
                                    <div class="conversation-attachment">
                                        <a href="{{ url($conversation->attachments) }}" class="attachment-link"
                                            target="_blank">
                                            <span class="attachment-icon">📎</span>
                                            Preview Attachment
                                        </a>
                                    </div>
                                @endif
                            </div>
                        @endforeach
                    @endif
                </div>

                <p style="margin-top: 20px;">
                    @if ($recipient == 'customer')
                        You can view the full ticket details and respond by logging into your account.
                    @else
                        Please login to the admin panel to respond to this ticket.
                    @endif
                </p>
            </div>

            <div id="email-footer">
                <div id="tagline-section">
                    <p class="small-tagline">This is an auto-generated email. Please do not reply.</p>
                    <p class="big-tagline">For questions or support, contact
                        <a href="mailto:{{ $companyEmail }}">{{ $companyEmail }}</a>
                    </p>
                </div>

                <div class="company-details">
                    @if (!empty($logoPath) && file_exists(public_path($logoPath)))
                        <img src="{{ url($logoPath) }}" class="footer-logo" alt="Logo">
                    @endif
                    <div class="company-title">{{ $companyName }}</div>
                    <div class="company-address-contact">
                        {{ $fullAddress }}<br>
                        Call: {{ $companyPhone }}
                    </div>
                </div>
            </div>

        </div>
</body>

</html>
