<?php

namespace App\Livewire\Projects\Tabs;

use App\Jobs\ProjectReportGeneratorJob;
use App\Jobs\ProjectTestReportGeneratorJob;
use App\Models\Project;
use App\Models\ProjectReport;
use Carbon\Carbon;
use Illuminate\Support\Str;
use Livewire\Attributes\Reactive;
use Livewire\Component;
use Livewire\WithPagination;

class Report extends Component
{
    use WithPagination;

    public $formData = [
        'end_date' => '',
        'offset' => 7
    ];
    public Project $project;

    public $search = "";


    public $showReportModal = false;
    public $showTestReportModal = false;

    public function mount()
    {
        $this->formData['end_date'] = Carbon::yesterday()->toDateString();
    }

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

    public function openCreateTestReportModal()
    {
        $this->showTestReportModal = true;
    }


    private function resetFormData()
    {
        $this->formData['end_date'] = Carbon::yesterday()->toDateString();
        $this->formData['offset'] = 7;
    }

    public function saveProjectReport()
    {
        $this->validate([
            'formData.end_date' => ['required','date','before:today'],
            'formData.offset' => 'required|integer|min:1|max:1000',
//            'formData'      => [new AllMosaicsPresentRule($this->project->id)],
        ]);

        $newReport = Project::find($this->project->id)
            ->reports()->create([
                'name' => ProjectReport::projectReportNameFormat(new Carbon($this->formData['end_date']),(int) $this->formData['offset']),
                'end_date' => $this->formData['end_date'],
                'offset' => $this->formData['offset'],
                'path' => 'reports/'.ProjectReport::getFileName($this->formData['end_date'],$this->formData['offset']).'.docx',
            ]);

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

        $this->showReportModal = false;

    }

    public function createProjectTestReport()
    {
       $this->project->scheduleTestReport();

        $this->dispatch('refresh');

        $this->showTestReportModal = false;

    }

    public function getDateRangeProperty()
    {
        if (!$this->formData['end_date'] || !$this->formData['offset']) {
            return '<span class="text-red-500">Please give a correct date or offset</span>';
        }
        $start = (new Carbon($this->formData['end_date']))->subDays($this->formData['offset']-1);
        $end = new Carbon($this->formData['end_date']);
        return 'from '.$start->format('Y-m-d').' to '.$end->format('Y-m-d');
    }

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

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


    public function render()
    {
        $query = Project::find($this->project->id)
            ->reports()
            ->with('project')
            ->orderBy('end_date', 'desc')
            ->orderBy('offset', 'desc');
        $query = $this->applySearch($query);
        $reports = $query->paginate(10, pageName: 'reportPage');

        logger(sprintf('%s %s', __CLASS__, now()));
        return view('livewire.projects.tabs.report')
            ->with(compact('reports'));
    }

    public function getMissingMosaicsInFileSystem(Carbon $endDate,int $offset = 7)
    {
        $this->project->getMosaicsFor($endDate,$offset);
        return redirect()->route('project.show',[$this->project->name,'mosaics']);

    }
}
