<?php

namespace App\Livewire\Projects\Tabs;

use App\Mail\ReportMailer;
use App\Models\Project;
use App\Models\ProjectMailing;
use Livewire\Component;
use Livewire\WithPagination;

class Mailings extends Component
{
    use WithPagination;

    public Project $project;
    public $mailingDetailsModal = false;

    public $formData = [

    ];

    public $search = '';

    public $active_mailing = null;

    protected $listeners = [
        'Badge:refresh' => '$refresh',
    ];
    public function mount(Project $project)
    {
        $this->project = $project;
        $this->resetFormData();
    }



    public function showMailingDetailsModal(ProjectMailing $mailing)
    {

        $this->formData = $mailing->toArray();
        $this->formData['attachments'] = $mailing->attachments->toArray();

        $this->formData['recipients'] = $mailing->recipients->toArray();
        $this->mailingDetailsModal = true;
    }

    public function closeMailingDetailsModal()
    {
        $this->mailingDetailsModal = false;
        $this->resetFormData();
    }

    private function resetFormData()
    {
        $this->formData = [
            'subject' => '',
            'message' => '',
            'created_at' => '',
            'attachments' => [],
            'recipients' => [],
        ];
    }

    private function applySearch($query)
    {
        return $query->when($this->search !== '', function ($q){
            $q->where('subject', 'like', '%'.$this->search.'%');
        });
    }

    public function render()
    {
        $query = $this->project
            ->mailings()
            ->orderBy('created_at', 'desc');

        $query = $this->applySearch($query);

        $mailings = $query->paginate(10, pageName: 'mailingPage');
        return view('livewire.projects.tabs.mailings', [
            'mailings' => $mailings,
        ]);
    }

    public function getMailPreview($formData):? string
    {
        if(array_key_exists('id',$formData)){
            try {
                return (new ReportMailer(ProjectMailing::find($formData['id'])))->render();
            } catch (\ReflectionException $e) {
                logger('No Idea what "ReflectionException" means... but got triggered.');
            }
        }
        return null;
    }

    public function getPreviewRoute($formData):?string
    {
        if(array_key_exists('id',$formData)){
            return route('mail',[$formData['id']]);
        }
        return null;
    }
}
