<?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\Support\Facades\Storage;

class ArticleController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = Article::query();

        // Filtres
        if ($request->filled('category')) {
            $query->where('category', $request->category);
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('search')) {
            $query->where(function ($q) use ($request) {
                $q->where('title', 'like', '%' . $request->search . '%')
                  ->orWhere('content', 'like', '%' . $request->search . '%');
            });
        }

        $articles = $query->orderBy('created_at', 'desc')->paginate(15);
        
        $categories = Article::select('category')->distinct()->pluck('category');
        $statuses = ['draft', 'published', 'archived'];

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

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $categories = ['sensibilisation', 'formation', 'evenement', 'partenariat', 'sante', 'distribution', 'communaute'];
        return view('admin.articles.create', compact('categories'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'excerpt' => 'nullable|string|max:500',
            'content' => 'required|string',
            'author' => 'required|string|max:255',
            'category' => 'required|in:sensibilisation,formation,evenement,partenariat,sante,distribution,communaute',
            'status' => 'required|in:draft,published,archived',
            'is_featured' => 'boolean',
            'featured_image' => 'nullable|image|max:2048',
        ]);

        // Génération du slug unique
        $slug = Str::slug($validated['title']);
        $originalSlug = $slug;
        $count = 1;
        while (Article::where('slug', $slug)->exists()) {
            $slug = $originalSlug . '-' . $count;
            $count++;
        }

        // Gestion simple de l'upload d'image
        $imagePath = null;
        if ($request->hasFile('featured_image')) {
            // Créer le dossier s'il n'existe pas
            $uploadPath = 'articles/images';
            Storage::disk('public')->makeDirectory($uploadPath);
            
            // Upload simple du fichier
            $imagePath = $request->file('featured_image')->store($uploadPath, 'public');
        }

        // Création de l'article
        $article = Article::create([
            'title' => $validated['title'],
            'slug' => $slug,
            'excerpt' => $validated['excerpt'],
            'content' => $validated['content'],
            'author' => $validated['author'],
            'category' => $validated['category'],
            'status' => $validated['status'],
            'is_featured' => $validated['is_featured'] ?? false,
            'featured_image' => $imagePath,
            'published_at' => $validated['status'] === 'published' ? now() : null,
        ]);

        return redirect()->route('admin.articles.index')
            ->with('success', 'Article créé avec succès.');
    }

    /**
     * Display the specified resource.
     */
    public function show(Article $article)
    {
        return view('admin.articles.show', compact('article'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Article $article)
    {
        $categories = ['sensibilisation', 'formation', 'evenement', 'partenariat', 'sante', 'distribution', 'communaute'];
        return view('admin.articles.edit', compact('article', 'categories'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Article $article)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'excerpt' => 'nullable|string|max:500',
            'content' => 'required|string',
            'author' => 'required|string|max:255',
            'category' => 'required|in:sensibilisation,formation,evenement,partenariat,sante,distribution,communaute',
            'status' => 'required|in:draft,published,archived',
            'is_featured' => 'boolean',
            'featured_image' => 'nullable|image|max:2048',
        ]);

        // Mise à jour du slug si le titre a changé
        $slug = $article->slug;
        if ($validated['title'] !== $article->title) {
            $slug = Str::slug($validated['title']);
            $originalSlug = $slug;
            $count = 1;
            while (Article::where('slug', $slug)->where('id', '!=', $article->id)->exists()) {
                $slug = $originalSlug . '-' . $count;
                $count++;
            }
        }

        // Gestion simple de l'upload d'image
        $imagePath = $article->featured_image;
        if ($request->hasFile('featured_image')) {
            // Supprimer l'ancienne image
            if ($article->featured_image) {
                Storage::disk('public')->delete($article->featured_image);
            }
            
            // Créer le dossier s'il n'existe pas
            $uploadPath = 'articles/images';
            Storage::disk('public')->makeDirectory($uploadPath);
            
            // Upload du nouveau fichier
            $imagePath = $request->file('featured_image')->store($uploadPath, 'public');
        }

        // Mise à jour de l'article
        $article->update([
            'title' => $validated['title'],
            'slug' => $slug,
            'excerpt' => $validated['excerpt'],
            'content' => $validated['content'],
            'author' => $validated['author'],
            'category' => $validated['category'],
            'status' => $validated['status'],
            'is_featured' => $validated['is_featured'] ?? false,
            'featured_image' => $imagePath,
            'published_at' => $validated['status'] === 'published' && !$article->published_at ? now() : $article->published_at,
        ]);

        return redirect()->route('admin.articles.index')
            ->with('success', 'Article mis à jour avec succès.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Article $article)
    {
        try {
            // Supprimer l'image associée
            if ($article->featured_image && \Storage::disk('public')->exists($article->featured_image)) {
                \Storage::disk('public')->delete($article->featured_image);
            }

            // Supprimer l'article
            $title = $article->title;
            $article->delete();

            return redirect()->route('admin.articles.index')
                ->with('success', "L'article '{$title}' a été supprimé avec succès.");

        } catch (\Exception $e) {
            \Log::error('Erreur lors de la suppression de l\'article: ' . $e->getMessage());
            
            return redirect()->route('admin.articles.index')
                ->with('error', 'Une erreur est survenue lors de la suppression de l\'article.');
        }
    }

    /**
     * Toggle featured status
     */
    public function toggleFeatured(Article $article)
    {
        $article->update(['is_featured' => !$article->is_featured]);

        return response()->json([
            'success' => true,
            'is_featured' => $article->is_featured
        ]);
    }

    /**
     * Bulk actions
     */
    public function bulkAction(Request $request)
    {
        $request->validate([
            'action' => 'required|in:delete,publish,draft,archive',
            'articles' => 'required|array',
            'articles.*' => 'exists:articles,id'
        ]);

        $articles = Article::whereIn('id', $request->articles);

        switch ($request->action) {
            case 'delete':
                $articles->each(function ($article) {
                    if ($article->featured_image) {
                        \Storage::disk('public')->delete($article->featured_image);
                    }
                });
                $articles->delete();
                $message = 'Articles supprimés avec succès.';
                break;
            case 'publish':
                $articles->update(['status' => 'published']);
                $message = 'Articles publiés avec succès.';
                break;
            case 'draft':
                $articles->update(['status' => 'draft']);
                $message = 'Articles mis en brouillon avec succès.';
                break;
            case 'archive':
                $articles->update(['status' => 'archived']);
                $message = 'Articles archivés avec succès.';
                break;
        }

        return redirect()->route('admin.articles.index')
            ->with('success', $message);
    }
}