<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Article;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class AdminArticleController extends Controller
{
    public function index()
    {
        return view('admin.articles.index', [
            'articles' => Article::latest('published_at')->paginate(15),
        ]);
    }

    public function create()
    {
        return view('admin.articles.form', [
            'article' => new Article([
                'category'     => 'Insight',
                'author'       => 'Brokam International',
                'published_at' => date('Y-m-d'),
                'published'    => true,
            ]),
        ]);
    }

    public function store(Request $request)
    {
        Article::create($this->validateData($request));

        return redirect()->route('admin.articles.index')->with('status', 'Article created.');
    }

    public function edit(Article $article)
    {
        return view('admin.articles.form', ['article' => $article]);
    }

    public function update(Request $request, Article $article)
    {
        $article->update($this->validateData($request, $article));

        return redirect()->route('admin.articles.index')->with('status', 'Article updated.');
    }

    public function destroy(Article $article)
    {
        $article->delete();

        return redirect()->route('admin.articles.index')->with('status', 'Article deleted.');
    }

    private function validateData(Request $request, ?Article $article = null): array
    {
        $validated = $request->validate([
            'title'        => ['required', 'string', 'max:180'],
            'slug'         => ['nullable', 'string', 'max:200', 'alpha_dash', Rule::unique('articles', 'slug')->ignore($article)],
            'category'     => ['required', Rule::in(['News', 'Insight', 'Press'])],
            'author'       => ['nullable', 'string', 'max:120'],
            'excerpt'      => ['required', 'string', 'max:500'],
            'body'         => ['required', 'string'],
            'published_at' => ['nullable', 'date'],
            'featured'     => ['nullable', 'boolean'],
            'published'    => ['nullable', 'boolean'],
        ]);

        $validated['slug'] = ($validated['slug'] ?? null) ?: $this->uniqueSlug($validated['title'], $article);
        $validated['featured'] = $request->boolean('featured');
        $validated['published'] = $request->boolean('published');

        return $validated;
    }

    private function uniqueSlug(string $title, ?Article $article): string
    {
        $base = Str::slug($title);
        $slug = $base;
        $i = 2;
        while (Article::where('slug', $slug)->when($article, fn ($q) => $q->where('id', '!=', $article->id))->exists()) {
            $slug = $base . '-' . $i++;
        }
        return $slug;
    }
}
