<?php

namespace App\Livewire\Admin\Blogs;

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Blog;
use Illuminate\Support\Str;

class BlogCreate extends Component
{
    use WithFileUploads;

    public $title;
    public $content;
    public $image;
    public $hero_image;
    public $publish_date;
    public $status = 1;

    protected $rules = [
        'title' => 'required|string|max:255',
        'content' => 'required|string',
        'publish_date' => 'required|date',
        'image' => 'required|image|mimes:jpg,jpeg,png,webp|max:2048',
        'hero_image' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',
    ];

    public function save()
    {
        $this->validate();

        /* =========================
           SAFE & UNIQUE SLUG
           ========================= */
        $slug = Str::slug($this->title);
        $count = Blog::where('slug', 'LIKE', $slug . '%')->count();

        if ($count > 0) {
            $slug .= '-' . ($count + 1);
        }

        /* =========================
           UPLOAD DIRECTORY
           ========================= */
        $uploadPath = public_path('uploads/blogs');
        if (!is_dir($uploadPath)) {
            mkdir($uploadPath, 0777, true);
        }

        /* =========================
           HERO IMAGE
           ========================= */
        $heroImagePath = null;

        if ($this->hero_image) {
            $heroFileName = time() . '_hero_' . uniqid() . '.' .
                $this->hero_image->getClientOriginalExtension();

            copy(
                $this->hero_image->getRealPath(),
                $uploadPath . '/' . $heroFileName
            );

            $heroImagePath = 'uploads/blogs/' . $heroFileName;
        }

        /* =========================
           FEATURED IMAGE
           ========================= */
        $featuredFileName = time() . '_featured_' . uniqid() . '.' .
            $this->image->getClientOriginalExtension();

        copy(
            $this->image->getRealPath(),
            $uploadPath . '/' . $featuredFileName
        );

        /* =========================
           SAVE BLOG
           ========================= */
        Blog::create([
            'title' => $this->title,
            'slug' => $slug,
            'content' => $this->content,
            'featured_image' => 'uploads/blogs/' . $featuredFileName,
            'hero_image' => $heroImagePath,
            'publish_date' => $this->publish_date,
            'status' => $this->status,
        ]);

        session()->flash('success', 'Blog created successfully 🎉');

        // ✅ CORRECT LIVEWIRE REDIRECT
        return redirect()->route('admin.blogs');
    }

    public function render()
    {
        return view('livewire.admin.blogs.blog-create')
            ->layout('layouts.admin'); // ✅ layout ONLY HERE
    }
}
