<?php

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Post;
use App\Models\Category;
use Illuminate\Support\Str;

return new class extends Component
{
    use WithFileUploads;

    public $title = '';
    public $slug = '';
    public $category_id = '';
    public $content = '';
    public $image_file;
    public $image_url = '';
    public $image_caption = '';
    public $status = 'published';
    public $is_featured = false;
    public $is_breaking = false;
    public $meta_title = '';
    public $meta_description = '';
    public $meta_keywords = '';

    public function render()
    {
        return $this->view()->layout('layouts::auth');
    }

    public function updatedTitle($value)
    {
        $this->slug = Str::slug($value);
    }

    public function save()
    {
        $this->validate([
            'title' => 'required|min:5',
            'slug' => 'required|unique:posts,slug',
            'category_id' => 'required|exists:categories,id',
            'content' => 'required',
            'image_file' => 'nullable|image|max:2048',
            'image_caption' => 'nullable|string|max:255',
            'status' => 'required|in:draft,published',
            'is_featured' => 'boolean',
            'is_breaking' => 'boolean',
        ]);

        $featured_image = $this->image_url;
        if ($this->image_file) {
            $featured_image = $this->image_file->store('posts', 'public');
        }

        Post::create([
            'title' => $this->title,
            'slug' => $this->slug,
            'category_id' => $this->category_id,
            'content' => $this->content,
            'featured_image' => $featured_image,
            'image_caption' => $this->image_caption,
            'status' => $this->status,
            'is_featured' => $this->is_featured,
            'is_breaking' => $this->is_breaking,
            'meta_title' => $this->meta_title,
            'meta_description' => $this->meta_description,
            'meta_keywords' => $this->meta_keywords,
        ]);

        session()->flash('message', 'Post created successfully.');
        return $this->redirect(route('admin.blog'), navigate: true);
    }

    public function with()
    {
        return [
            'categories' => Category::orderBy('name')->get(),
        ];
    }

    protected function view($data = [])
    {
        return app('view')->file('D:\02-my freelance\00-DR_Padhi\DR_PADHI\storage\framework/views/livewire/views/0ad5d84e.blade.php', $data);
    }
};
