<?php

namespace App\Livewire\Projects;

use App\Models\Project;
use App\Models\ProjectMailing;
use Livewire\Attributes\Lazy;
use Livewire\Component;
use Livewire\WithPagination;

#[Lazy]
class MailingManager extends Component
{
    use WithPagination;

    public $project;
    public $mailingDetailsModal = false;

    public $formData = [

    ];

    public $search = '';

    public $active_mailing = null;
    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)
    {
        if ($this->search) {
            $query->where('subject', 'like', '%'.$this->search.'%');
        }
        return $query;
    }

    public function placeholder()
    {
        return view('livewire.projects.mailing-manager-placeholder');
    }

    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.mailing-manager', [
            'mailings' => $mailings,
        ]);
    }
}
