<?php

namespace App\Livewire\Projects\Tabs;

use App\Models\Project;
use App\Rules\DownloadDateRangeRule;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Livewire\Component;
use Livewire\WithPagination;

class Download extends Component
{
    use WithPagination;

    public Project $project;

    public $formData;

    public $showDownloadModal = false;

    public $search = '';

    public $listeners = [
        'Badge:refresh' => '$refresh',
    ];



    public function mount(Project $project)
    {
        $this->path = $project->download_path;
        $this->formData = [
            'dateRange' => sprintf('%s to %s',
                now()->subDays(6)->format('Y/m/d'),
                now()->format('Y/m/d')
            )
        ];
    }

    public function update($property)
    {
        if ($property === 'search') {
            $this->resetPage('downloadPage');
        }
    }

    public function openDownloadModal()
    {
        $this->showDownloadModal = true;
    }

    public function saveDownloads()
    {
        $this->validate([
            'formData.dateRange' => [
                'required',
                new DownloadDateRangeRule(),
            ]
        ]);

        $dateRange = explode(' to ', $this->formData['dateRange']);

        $period = CarbonPeriod::create(
            Carbon::parse($dateRange[0]),
            Carbon::parse($dateRange[1])
        );

        collect($period)->each(function ($date) {
            $this->project->startDownload($date);
        });

        $this->showDownloadModal = false;
    }

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


    public function render()
    {
        $query = $this->project->downloads()->orderBy('name', 'desc');
        $query = $this->applySearch($query);
        $downloads = $query->paginate(10, pageName: 'downloadPage');

        logger(sprintf('%s %s', __CLASS__, now()));
        return view('livewire.projects.tabs.download',
            compact('downloads')
        );
    }
}
