<?php

namespace App\Livewire;

use App\Models\Episode;
use App\Models\User;
use App\Models\UserDownload;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class DownloadsFree extends Component
{
    public $episodeId = 0;

    public $downloadsLeft = 5;

    public $granted = 0;

    public $override = false;

    public $interpolated = false;

    public function mount(Episode $episode, $interpolated = false)
    {
        $this->episodeId = $episode->id;
        $this->interpolated = $interpolated;
        $user = Auth::user()->id;

        if (Auth::check()) {
            $this->downloadsLeft = (int) User::where('id', $user)->firstOrFail()->downloads_left;
        }

        if ($this->downloadsLeft === 0) {
            $this->granted = 3;
        }

        if ($episode->created_at >= Carbon::now()->subDays(7)) {
            $this->granted = 4;
        }

        $alreadyDownloaded = UserDownload::where('user_id', $user)
            ->where('episode_id', $this->episodeId)
            ->where('interpolated', $this->interpolated)
            ->first();

        if ($alreadyDownloaded) {
            // Check timestamp
            if (Carbon::parse($alreadyDownloaded->created_at)->addHours(6) <= Carbon::now()) {
                // Already expired
                $alreadyDownloaded->delete();

                return;
            }

            $this->override = true;
        }
    }

    public function generate()
    {
        $user = User::where('id', Auth::user()->id)->firstOrFail();

        if ($user->downloads_left <= 0) {
            // Daily limit reached
            $this->granted = 3;

            return;
        }

        $user->downloads_left -= 1;
        $user->save();

        $this->downloadsLeft -= 1;
        $this->granted = 1;

        UserDownload::create([
            'user_id' => $user->id,
            'episode_id' => $this->episodeId,
            'interpolated' => $this->interpolated,
        ]);
    }

    public function render()
    {
        return view('livewire.downloads-free');
    }
}
