<?php

namespace App\Http\Controllers;

use App\Models\Article;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Str;

class ArticleController extends Controller
{
    /** Public API: Fetch all published articles */
    public function apiIndex()
    {
        $articles = Article::where('is_published', true)
            ->orderBy('created_at', 'desc')
            ->get();
        return response()->json($articles);
    }

    /** Public API: Fetch a single article by slug */
    public function apiShow($slug)
    {
        $article = Article::where('slug', $slug)
            ->where('is_published', true)
            ->firstOrFail();
        return response()->json($article);
    }

    /** Admin: List articles */
    public function index()
    {
        $articles = Article::orderBy('created_at', 'desc')->get();
        return Inertia::render('Admin/Articles/Index', [
            'articles' => $articles
        ]);
    }

    /** Admin: Create article form */
    public function create()
    {
        return Inertia::render('Admin/Articles/Form', [
            'article' => null
        ]);
    }

    /** Admin: Store new article */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'excerpt' => 'nullable|string',
            'content' => 'nullable|string',
            'category' => 'nullable|string|max:100',
            'read_time' => 'nullable|string|max:50',
            'is_published' => 'boolean',
            'cover_image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:5120',
        ]);

        $article = new Article($validated);
        $article->slug = Str::slug($validated['title']) . '-' . rand(1000, 9999);
        $article->is_published = $request->input('is_published', true);

        if ($request->hasFile('cover_image')) {
            $file = $request->file('cover_image');
            $filename = 'article-' . time() . '-' . rand(1000, 9999) . '.' . $file->getClientOriginalExtension();
            $path = base_path('../public/images');
            if (!is_dir($path)) {
                mkdir($path, 0775, true);
            }
            $file->move(realpath($path) ?: $path, $filename);
            $article->cover_image = '/images/' . $filename;
        }

        $article->save();

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

    /** Admin: Edit article form */
    public function edit(Article $article)
    {
        return Inertia::render('Admin/Articles/Form', [
            'article' => $article
        ]);
    }

    /** Admin: Update article */
    public function update(Request $request, Article $article)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'excerpt' => 'nullable|string',
            'content' => 'nullable|string',
            'category' => 'nullable|string|max:100',
            'read_time' => 'nullable|string|max:50',
            'is_published' => 'boolean',
            'cover_image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:5120',
        ]);

        if (isset($validated['title']) && $validated['title'] !== $article->title) {
            $validated['slug'] = Str::slug($validated['title']) . '-' . rand(1000, 9999);
        }

        if ($request->hasFile('cover_image')) {
            $file = $request->file('cover_image');
            $filename = 'article-' . time() . '-' . rand(1000, 9999) . '.' . $file->getClientOriginalExtension();
            $path = base_path('../public/images');
            if (!is_dir($path)) {
                mkdir($path, 0775, true);
            }
            $file->move(realpath($path) ?: $path, $filename);
            $validated['cover_image'] = '/images/' . $filename;
        }

        $article->update($validated);

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

    /** Admin: Delete article */
    public function destroy(Article $article)
    {
        $article->delete();
        return redirect()->route('admin.articles.index')->with('success', 'Article deleted successfully.');
    }
}
