<?php

namespace App\Models;

use App\Events\ProjectReportStatus;
use App\Traits\HasStatus;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

class ProjectReport extends Model
{
    use HasStatus;
    protected $casts = [ 'end_date' => 'datetime'];
    protected $fillable = ['name', 'path', 'week', 'year','status', 'end_date','offset'];
    public function project()
    {
        return $this->belongsTo(Project::class);
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->token)) {
                $model->token = Str::random(32); // Generates a random string of 60 characters
            }
        });
    }


    public function getFileNameAttribute(): string
    {
       return static::getFileName($this->end_date,$this->offset);
    }
    public static function getFileName(Carbon $endDate, int $offset): string
    {
        return 'period_'.$endDate->copy()->subDays($offset).'_'.$endDate;
    }

    public static function projectReportNameFormat(Carbon $endDate,int $offset):string
    {
        return 'Report from '.$endDate->copy()->subDays($offset)->toDateString().' to '.$endDate->toDateString();
    }

    public function getFullPathName()
    {
        return storage_path('app/'.$this->project->download_path.'/'.$this->path);
    }

    public function getReportDate():string
    {
        // TODO remove year and week
        return $this->end_date->format('Y-m-d');
    }

    public static function getReportDateForYearAndWeek(Project $project, $year, $week)
    {
        $date = Carbon::now()->setISODate($year, $week);

        $dayOfWeek = Carbon::parse($project->mail_day)->subDay(2)->dayOfWeek;
        if ($dayOfWeek == 6) {
            $reportDay = $date->startOfWeek()->subDay();
        } else {
            $reportDay = $date->startOfWeek()->addDays($dayOfWeek);
        }

        return $reportDay;
    }

    public function documentExists()
    {
        return File::exists($this->getFullPathName());
    }

    public function deleteMe()
    {
        if ($this->documentExists()) {
            File::delete($this->getFullPathName());
        }
        $this->delete();
    }

    protected static function booted(): void
    {
        parent::booted();
        static::updated(function (ProjectReport $projectReport) {
            event(new ProjectReportStatus($projectReport));
        });
    }


    public function updateStatistics()
    {
        $this->increment('download_count');
        $this->log .= "\n".Carbon::now()->toDateTimeString().' - ' . request()->ip();
        $this->save();
    }
}
