<?php

namespace App\View\Components;

use App\Models\Entry;
use App\Models\News;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;

class SubmitEntryStatus extends Component
{
    /**
     * Create a new component instance.
     */
    public function __construct(
        public string $section,
        public bool $isEdit,
        public ?string $currentState,
        public null|string|Entry|News $entry = null,
        public bool $news = false
    )
    {
        if( $this->entry === null ){
            if( $news )
                $this->entry = 'App\Models\News';
            else
                $this->entry = 'App\Models\Entry';
        }
    }

    public function availableStates(): array
    {

        $labelPublished = $this->isEdit && $this->currentState === 'published' ? "Keep it published" : "Publish it now";
        $labelPending = $this->isEdit && $this->currentState === 'pending' ? "Keep it to submissions queue" : "Add to submissions queue";
        $labelDraft = $this->isEdit && $this->currentState === 'draft' ? "Keep it into my drafts" : "Save into my drafts";
        $labelHidden = $this->isEdit && $this->currentState === 'hidden' ? "Keep it hidden" : "Hide this entry";
        $labelLocked = $this->isEdit && $this->currentState === 'locked' ? "Keep it locked" : "Lock this entry";

        $states = [
            'draft' => $labelDraft,
            'pending' => $labelPending,
        ];

        if( $this->isEdit ) {

            $isAuthor = $this->entry->user_id === \Auth::user()->user_id;
            if( $isAuthor && ( \Auth::user()->can('skip-queue', $this->entry) || $this->currentState === 'published' ) )
                $states['published'] = $labelPublished;
            else if( \Auth::user()->can('moderate', $this->entry) )
                $states['published'] = $labelPublished;
            if( \Auth::user()->can('moderate', $this->entry) && \Auth::user()->can('view-hidden', $this->entry) )
                $states['hidden'] = $labelHidden;
            if(\Auth::user()->can('moderate', $this->entry) && \Auth::user()->can('view-locked', $this->entry) )
                $states['locked'] = $labelLocked;

        } else {
            if( \Auth::user()->can('skip-queue', $this->entry ) ){
                $states['published'] = $labelPublished;
            }
        }

        return $states;
    }

    public function defaultState(): string
    {
        $availableStates = array_keys( $this->availableStates() );
        return in_array('published', $availableStates) ? 'published' : ( in_array('pending', $availableStates) ? 'pending' : 'draft' );
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View|Closure|string
    {
        return view('components.submit-entry-status', [ 'states' => $this->availableStates(), 'defaultState' => $this->defaultState(), 'section' => $this->section ]);
    }
}
