<?php

namespace App\Http\Controllers;

use App\Models\Article;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Contracts\View\View;
use App\Models\Category;
use App\Models\ArticleImage;

class ArticleController extends Controller
{

    public function index(Request $request, Category $category = null): View
    {
        $query = Article::query()->with('category')->latest();

        $query->when($request->search, function ($q, $search) {
            return $q->where('title', 'like', "%{$search}%");
        });

        $query->when($category, function ($q) use ($category) {
            return $q->where('category_id', $category->id);
        });

        $articles = $query->paginate(10)->withQueryString(); 
        $categories = Category::withCount('articles')->orderBy('name', 'asc')->get();

        return view('artikel.index', [
            'articles' => $articles,
            'categories' => $categories,
            'currentCategory' => $category,
        ]);
    }

    public function show(Article $article)
    {
        $categories = Category::withCount('articles')->orderBy('name', 'asc')->get();

        return view('artikel.show', [
            'article' => $article,
            'categories' => $categories,
        ]);
    }


    public function adminIndex(Request $request)
    {
        $search = $request->input('search');

        $articles = Article::with('category')
            ->when($search, function ($query, $search) {
                return $query->where('title', 'like', "%{$search}%")
                             ->orWhereHas('category', function ($q) use ($search) {
                                 $q->where('name', 'like', "%{$search}%");
                             });
            })
            ->latest()
            ->paginate(10)
            ->withQueryString(); 

        return view('admin.artikel.index', compact('articles'));
    }

    public function create()
    {
        $categories = Category::all();
        return view('admin.artikel.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'content' => 'required|string',
            'images' => 'nullable|array',
            'images.*' => 'image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $article = Article::create([
            'title' => $validatedData['title'],
            'content' => $validatedData['content'],
            'category_id' => $validatedData['category_id'],
        ]);

        if ($request->hasFile('images')) {
            foreach ($request->file('images') as $imageFile) {
                $path = $imageFile->store('articles', 'public');
                $article->images()->create(['path' => $path]);
            }
        }

        return redirect()->route('admin.articles.index')->with('success', 'Artikel berhasil dibuat!');
    }

    public function edit(Article $article)
    {
        $categories = Category::all();
        return view('admin.artikel.edit', compact('article', 'categories'));
    }

    public function update(Request $request, Article $article)
    {
        $validatedData = $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'content' => 'required|string',
            'images' => 'nullable|array',
            'images.*' => 'image|mimes:jpeg,png,jpg,gif|max:2048',
            'delete_images' => 'nullable|array',
            'delete_images.*' => 'integer|exists:article_images,id',
        ]);

        $article->update($request->only('title', 'content', 'category_id'));

        // Hapus gambar
        if ($request->has('delete_images')) {
            foreach ($request->delete_images as $imageId) {
                $imageToDelete = ArticleImage::find($imageId);
                if ($imageToDelete) {
                    Storage::disk('public')->delete($imageToDelete->path);
                    $imageToDelete->delete();
                }
            }
        }

        if ($request->hasFile('images')) {
            foreach ($request->file('images') as $imageFile) {
                $path = $imageFile->store('articles', 'public');
                $article->images()->create(['path' => $path]);
            }
        }

        return redirect()->route('admin.articles.index')->with('success', 'Artikel berhasil diperbarui!');
    }

    public function destroy(Article $article)
    {
        foreach ($article->images as $image) {
            Storage::disk('public')->delete($image->path);
        }
        $article->delete();

        return redirect()->route('admin.articles.index')->with('success', 'Artikel berhasil dihapus!');
    }
}