<?php

namespace App\Livewire\Projects;

use App\Jobs\ProjectReportGeneratorJob;
use App\Models\Project;
use App\Models\ProjectReport;
use App\Rules\AllMosaicsPresentRule;
use Illuminate\Database\Query\Builder;
use Livewire\Attributes\Lazy;
use Livewire\Component;
use Livewire\WithPagination;
#[Lazy]
class ReportManager extends Component
{
    use WithPagination;

    public $formData = [];
    public $project_id;

    public $search = "";

    public $showReportModal = false;

    public $listeners = ['refresh' => '$refresh'];

    public function openCreateReportModal()
    {
        $this->resetFormData();
        $this->showReportModal = true;
    }

    public function mount(Project $project)
    {
        $this->project_id = $project->id;
    }


    private function resetFormData()
    {
        $this->formData['week'] = now()->weekOfYear;
        $this->formData['year'] = now()->year;
    }

    public function saveProjectReport()
    {
        $this->validate([
            'formData.week' => ['required', 'integer', 'min:1', 'max:53'],
            'formData.year' => 'required|integer|min:2020|max:'.now()->addYear()->year,
//            'formData'      => [new AllMosaicsPresentRule($this->project_id)],
        ]);

        $newReport = Project::find($this->project_id)
            ->reports()->create([
                'name' => 'Report for week '.$this->formData['week'].' of '.$this->formData['year'],
                'week' => $this->formData['week'],
                'year' => $this->formData['year'],
                'path' => 'reports/week_'.$this->formData['week'].'_'.$this->formData['year'].'.docx',
            ]);

        ProjectReportGeneratorJob::dispatch($newReport);
        $this->dispatch('refresh');

        $this->showReportModal = false;

    }

    public function getDateRangeProperty()
    {
        if (empty($this->formData['week']) || strlen($this->formData['year']) !== 4) {
            return '<span class="text-red-500">Invalid week or year</span>';
        }
        // @TODO dit moet gecorrigeerd voor de project settings;
        $begin = now()
            ->setISODate($this->formData['year'], $this->formData['week'])
            ->startOfWeek();
        $end = now()
            ->setISODate($this->formData['year'], $this->formData['week'])
            ->endOfWeek();
        return $begin->format('Y-m-d').' - '.$end->format('Y-m-d');
    }

    public function deleteReport(ProjectReport $report)
    {
        $report->deleteMe();
        $this->dispatch('refresh');
    }

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

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

    public function render()
    {
        $query = Project::find($this->project_id)
            ->reports()
            ->orderBy('year', 'desc')
            ->orderBy('week', 'desc');
        $query = $this->applySearch($query);
        $reports = $query->paginate(10, pageName: 'reportPage');

        return view('livewire.projects.report-manager')
            ->with(compact('reports'));
    }
}
