<?php

namespace App\Services;

use App\Models\Contract;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;

class InvoiceMailService
{
    /**
     * Send an invoice email to the contract's recipients.
     *
     * Respects: eracun, send_xml, send_invoice_to_email flags.
     * When $testMode is true, sends only to the configured test address.
     *
     * @param Contract $contract
     * @param array    $invoiceData   Full invoice data from Minimax (including ID)
     * @param string   $pdfContent   Raw PDF binary (optional, fetched if null)
     * @param string   $xmlContent   Raw XML binary (optional)
     * @param bool     $testMode
     * @param string   $account
     */
    public function sendInvoice(
        Contract $contract,
        array $invoiceData,
        ?string $pdfContent,
        ?string $xmlContent,
        bool $testMode,
        string $account,
    ): void {
        // Check flags
        if (!$contract->send_invoice_to_email) {
            return;
        }

        $recipients = $contract->primary_email ?? [];

        if (empty($recipients)) {
            \Illuminate\Support\Facades\Log::warning("No recipients for contract {$contract->contract_no} — skipping email.");
            return;
        }

        if ($testMode) {
            $recipients = [config('mail.test_address', env('MAIL_TEST_ADDRESS', 'test@inoffice.local'))];
        }

        $cc  = $contract->email_cc ?? [];
        $bcc = $contract->email_bcc ?? [];

        // Choose template based on payment type
        $view = $contract->payment === 'year'
            ? 'emails.issuedInvoiceMailYear'
            : 'emails.issuedInvoiceMail';

        $invoiceNo = $invoiceData['InvoiceNumber'] ?? $invoiceData['IssuedInvoiceId'] ?? '?';
        $subject   = "Račun br. {$invoiceNo} — {$contract->customer_name}";

        Mail::send(
            $view,
            ['contract' => $contract, 'invoice' => $invoiceData, 'testMode' => $testMode],
            function ($message) use ($recipients, $cc, $bcc, $subject, $pdfContent, $xmlContent, $invoiceNo, $contract) {
                $message->to($recipients)
                    ->subject($subject);

                if (!empty($cc)) {
                    $message->cc($cc);
                }
                if (!empty($bcc)) {
                    $message->bcc($bcc);
                }

                // Attach PDF
                if ($pdfContent) {
                    $filename = "racun_{$invoiceNo}.pdf";
                    $message->attachData($pdfContent, $filename, ['mime' => 'application/pdf']);
                }

                // Attach XML (e-račun) if enabled
                if ($xmlContent && $contract->send_xml) {
                    $filename = "racun_{$invoiceNo}.xml";
                    $message->attachData($xmlContent, $filename, ['mime' => 'application/xml']);
                }
            }
        );
    }

    /**
     * Send a generic alert/notification email to contract recipients.
     *
     * @param Contract    $contract
     * @param string      $subject
     * @param string      $template    Blade view name (e.g. 'emails.expireContracts')
     * @param array       $data        Extra data passed to the view
     * @param bool        $testMode
     * @param string|null $excludeEmail  Skip contract if primary email matches this
     * @param string|null $includeEmail  Only send if primary email matches this
     */
    public function sendAlert(
        Contract $contract,
        string $subject,
        string $template,
        array $data = [],
        bool $testMode = false,
        ?string $excludeEmail = null,
        ?string $includeEmail = null,
    ): bool {
        $recipients = $contract->primary_email ?? [];

        if (empty($recipients)) {
            return false;
        }

        // Apply include/exclude filters
        if ($includeEmail && !in_array($includeEmail, $recipients)) {
            return false;
        }
        if ($excludeEmail && in_array($excludeEmail, $recipients)) {
            return false;
        }

        $to = $testMode
            ? [config('mail.test_address', env('MAIL_TEST_ADDRESS', 'test@inoffice.local'))]
            : $recipients;

        $cc  = $contract->email_cc ?? [];
        $bcc = $contract->email_bcc ?? [];

        $viewData = array_merge(['contract' => $contract, 'testMode' => $testMode], $data);

        Mail::send($template, $viewData, function ($message) use ($to, $cc, $bcc, $subject, $testMode) {
            $message->to($to)->subject($subject);
            if (!$testMode) {
                if (!empty($cc)) $message->cc($cc);
                if (!empty($bcc)) $message->bcc($bcc);
            }
        });

        return true;
    }
}
