<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Partner;
use Illuminate\Http\Request;

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

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

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

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

        $partners = $query->orderBy('order')->orderBy('created_at', 'desc')->paginate(15);
        
        $types = Partner::select('type')->distinct()->pluck('type');

        return view('admin.partners.index', compact('partners', 'types'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $types = ['gouvernement', 'ong', 'entreprise', 'fondation', 'international', 'académique'];
        return view('admin.partners.create', compact('types'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'type' => 'required|in:gouvernement,ong,entreprise,fondation,international,académique',
            'website_url' => 'nullable|url|max:255',
            'logo' => 'nullable|image|max:2048',
            'order' => 'nullable|integer|min:0',
            'is_active' => 'boolean',
        ]);

        // Mapping des types du formulaire vers la DB
        $typeMapping = [
            'gouvernement' => 'government',
            'ong' => 'ngo',
            'entreprise' => 'private',
            'fondation' => 'institutional',
            'international' => 'international',
            'académique' => 'academic'
        ];
        $validated['type'] = $typeMapping[$validated['type']] ?? 'institutional';

        // Gestion du logo
        if ($request->hasFile('logo')) {
            $validated['logo_path'] = $request->file('logo')->store('partners/logos', 'public');
            unset($validated['logo']);
        }

        // Ordre automatique si non spécifié
        if (!isset($validated['order'])) {
            $validated['order'] = Partner::max('order') + 1 ?? 0;
        }

        $validated['is_active'] = $request->has('is_active') ? true : false;

        Partner::create($validated);

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

    /**
     * Display the specified resource.
     */
    public function show(Partner $partner)
    {
        return view('admin.partners.show', compact('partner'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Partner $partner)
    {
        $types = ['gouvernement', 'ong', 'entreprise', 'fondation', 'international', 'académique'];
        return view('admin.partners.edit', compact('partner', 'types'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Partner $partner)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'type' => 'required|in:gouvernement,ong,entreprise,fondation,international,académique',
            'website_url' => 'nullable|url|max:255',
            'logo' => 'nullable|image|max:2048',
            'order' => 'nullable|integer|min:0',
            'is_active' => 'boolean',
        ]);

        // Mapping des types du formulaire vers la DB
        $typeMapping = [
            'gouvernement' => 'government',
            'ong' => 'ngo',
            'entreprise' => 'private',
            'fondation' => 'institutional',
            'international' => 'international',
            'académique' => 'academic'
        ];
        $validated['type'] = $typeMapping[$validated['type']] ?? 'institutional';

        // Gestion du logo
        if ($request->hasFile('logo')) {
            // Supprimer l'ancien logo
            if ($partner->logo_path) {
                \Storage::disk('public')->delete($partner->logo_path);
            }
            $validated['logo_path'] = $request->file('logo')->store('partners/logos', 'public');
            unset($validated['logo']);
        }

        $validated['is_active'] = $request->has('is_active') ? true : false;

        $partner->update($validated);

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

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Partner $partner)
    {
        try {
            // Supprimer le logo
            if ($partner->logo_path && \Storage::disk('public')->exists($partner->logo_path)) {
                \Storage::disk('public')->delete($partner->logo_path);
            }

            // Supprimer le partenaire
            $name = $partner->name;
            $partner->delete();

            return redirect()->route('admin.partners.index')
                ->with('success', "Le partenaire '{$name}' a été supprimé avec succès.");

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

    /**
     * Reorder partners
     */
    public function reorder(Request $request)
    {
        $request->validate([
            'items' => 'required|array',
            'items.*.id' => 'required|exists:partners,id',
            'items.*.order' => 'required|integer|min:0',
        ]);

        foreach ($request->items as $item) {
            Partner::where('id', $item['id'])->update(['order' => $item['order']]);
        }

        return response()->json(['success' => true]);
    }

    /**
     * Toggle active status
     */
    public function toggleActive(Partner $partner)
    {
        $partner->update(['is_active' => !$partner->is_active]);

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

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

        $partners = Partner::whereIn('id', $request->partners);

        switch ($request->action) {
            case 'delete':
                $partners->each(function ($partner) {
                    if ($partner->logo) {
                        \Storage::disk('public')->delete($partner->logo);
                    }
                });
                $partners->delete();
                $message = 'Partenaires supprimés avec succès.';
                break;
            case 'activate':
                $partners->update(['is_active' => true]);
                $message = 'Partenaires activés avec succès.';
                break;
            case 'deactivate':
                $partners->update(['is_active' => false]);
                $message = 'Partenaires désactivés avec succès.';
                break;
        }

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