<?php

namespace App\Livewire\Announcements;

use App\Models\{Announcements,Categories};

use Illuminate\Http\Request;
use Illuminate\Support\{Str,Carbon};
use Illuminate\Support\Facades\Auth;

use Livewire\Attributes\{Rule, Validate};

use Filament\Notifications\Notification;

use Livewire\Component;

class Edit extends Component
{
    public $id = '';

    #[Rule('required', message: "Please enter a title for the announcement.")]
    public $title = '';

    public $slug = '';
    public $image = '';

    #[Rule('required', message: "Please enter the content for the announcement.")]
    public $content = '';


    public $draft = '';
    public $private = '';

    #[Rule('numeric', message: "Please select a correct category.")]
    #[Validate('required')]
    public $parent_category = '';

    public function update()
    {
        $this->validate();
        if($this->slug)
        {
            $slug = Str::of($this->slug)->slug('-');
        } else {
            $slug = Str::of($this->title)->slug('-');
        }
        Announcements::where('id', '=', $this->id)->update([
            'parent_category' => $this->parent_category,
            'title' => $this->title,
            'slug' => $slug,
            'image' => $this->image,
            'content' => $this->content,
            'tags'  => '',
            'draft' => $this->draft,
            'private' => $this->private,
            'author_id' => Auth::user()->id,
            'updated_at' => Carbon::now(),
        ]);
        $this->redirect('/' . $this->id . '-' . $this->slug);
        $this->reset();
    }

    public function mount($id, $slug)
    {
        $announcement = Announcements::where('id', '=', $id)->where('slug', '=', $slug)->first();
        $this->id            = $announcement->id;
        $this->title            = $announcement->title;
        $this->slug             = $announcement->slug;
        $this->image            = $announcement->image;
        $this->content          = $announcement->content;
        $this->draft            = $announcement->draft;
        $this->private          = $announcement->private;
        $this->parent_category  = $announcement->parent_category;
    }

    public function render()
    {

        $categories = Categories::all()->where('type', '=', 'announcements');
        return view('livewire.announcements.edit',[
            'categories' => $categories,
        ]);
    }
}
