<?php

namespace App\Livewire\Forms;

use App\Models\ProjectMailing;
use App\Models\ProjectReport;
use Illuminate\Support\Facades\Mail;
use Livewire\Attributes\Rule;
use Livewire\Form;

class MailingForm extends Form
{
    #[Rule('required|min:3')]
    public string $subject = '';

    #[Rule('required')]
    public string $message = '';

    #[Rule('required')]
    public array $recipients = [];

    #[Rule('required')]
    public ProjectReport $report;

    public function setReport(ProjectReport $report)
    {
        $this->report = $report;
        $this->subject = $report->project->mail_subject;
        $this->message = $report->project->mail_template;
        $this->recipients = $this->report->project->emailRecipients()->get(['email', 'name'])->toArray();


    }

    public function save()
    {
        $this->validate();
        self::saveAndSendMailing($this->report, $this->subject, $this->message, $this->recipients);

        $this->setReport($this->report);
    }

    public static function saveAndSendMailing($report, $subject, $message, $recipients) {
        if ($report->documentExists()) {
            $mailing = $report->project->mailings()->create([
                'subject'   => $subject,
                'message'   => $message,
                'report_id' => $report->id,
            ]);

            // Attach main report
            $mailing->attachments()->create([
                'name' => $report->name,
                'path' => $report->path,
            ]);

            // For cane_supply projects, also attach latest KPI Excel file
            if ($report->project->client_type === 'cane_supply') {
                $kpiFile = $report->project->getLatestKpiFile();
                if ($kpiFile) {
                    $mailing->attachments()->create([
                        'name' => 'KPI Data - ' . basename($kpiFile),
                        'path' => $kpiFile,
                    ]);
                }
            }

            $mailing->recipients()->createMany($recipients);
            Mail::to($mailing->recipients()->pluck('email')->toArray())
                ->send(new \App\Mail\ReportMailer($mailing, $report));
        } else {
            self::sendReportNotFoundNotificationToAdmin($report);
        }
    }

    private static function sendReportNotFoundNotificationToAdmin($report) {
        Mail::to(config('mail.from.address'))
            ->send(new \App\Mail\ReportNotFound($report));
    }
}
