<?php

namespace App\Http\Controllers;

use App\Models\Campaign;
use App\Models\Group;
use \App\Models\Donateur;
use App\Enums\LinkStatus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use App\Jobs\SendCampaignNotifications;
use App\Services\NotificationService;

class CampaignController extends Controller
{
    public function index()
    {
        $campaigns = Campaign::with(['links.donateur', 'links.payments'])
            ->withCount([
                'links',
                'links as paid_count' => function ($q) {
                    $q->where('status', LinkStatus::Paid);
                }
            ])
            ->orderBy('created_at', 'desc')
            ->get();

        return view('campaigns.index', compact('campaigns'));
    }

    public function create()
    {
        return view('campaigns.create');
    }

    public function store(Request $r)
    {
        $r->merge(['slug' => Str::slug($r->input('slug'))]);
        $data = $r->validate([
            'name'           => 'required|string|unique:campaigns,name',
            'slug'           => 'required|string|unique:campaigns,slug',
            'message'        => 'required|string',
            'reminder_message' => 'nullable|string',
            'cover_image'    => 'sometimes|file|image|mimes:jpg,jpeg,png,svg,gif|max:2048',
            'thank_image'    => 'sometimes|file|image|mimes:jpg,jpeg,png,svg,gif|max:2048',
            'reminder_image' => 'sometimes|file|image|mimes:jpg,jpeg,png,svg,gif|max:2048',
            'initiator_name'     => 'nullable|string',
            'initiator_position' => 'nullable|string',
            'contact_phone'      => 'nullable|string',
            'contact_email'      => 'nullable|string',
            'color'              => ['nullable', 'regex:/^#[0-9A-Fa-f]{6}$/'],
        ]);

        $campaign = Campaign::create($data);

        foreach (['cover_image','thank_image','reminder_image'] as $field) {
            if ($r->hasFile($field)) {
                $path = $r->file($field)->store('campaigns/'.$campaign->id, 'public');
                $campaign->update([$field => $path]);
            }
        }

         // Création automatique des groupes
         Group::create([
            'name' => "{$campaign->name} - En attente",
            'description' => "Donateurs en attente pour la campagne {$campaign->name}",
        ]);
        Group::create([
            'name' => "{$campaign->name} - Payés",
            'description' => "Donateurs ayant payé pour la campagne {$campaign->name}",
        ]);

        return redirect()->route('campaigns.index')->with('success','Campagne créée et groupes associés générés');
    }

    public function edit(Campaign $campaign)
    {
        return view('campaigns.edit', compact('campaign'));
    }

    public function update(Request $r, Campaign $campaign)
    {
        // 1) Pré-validation et récupération de l'ancien nom
        $oldName = $campaign->name;

        $r->merge(['slug' => Str::slug($r->input('slug'))]);

        $data = $r->validate([
            'name'           => 'required|string|unique:campaigns,name,'.$campaign->id,
            'slug'           => 'required|string|unique:campaigns,slug,'.$campaign->id,
            'message'        => 'required|string',
            'reminder_message' => 'nullable|string',
            'cover_image'    => 'sometimes|file|image|mimes:jpg,jpeg,png,svg,gif|max:2048',
            'thank_image'    => 'sometimes|file|image|mimes:jpg,jpeg,png,svg,gif|max:2048',
            'reminder_image' => 'sometimes|file|image|mimes:jpg,jpeg,png,svg,gif|max:2048',
            'initiator_name'     => 'nullable|string',
            'initiator_position' => 'nullable|string',
            'contact_email'      => 'nullable|email',
            'contact_phone'      => 'nullable|string',
            'color'              => ['nullable', 'regex:/^#[0-9A-Fa-f]{6}$/'],
        ]);

        // 2) Mise à jour de la campagne
        $campaign->update($data);

        if ($r->filled('remove_cover_image') && $campaign->cover_image) {
        Storage::disk('public')->delete($campaign->cover_image);
            $campaign->cover_image = null;
        }
        if ($r->filled('remove_thank_image') && $campaign->thank_image) {
            Storage::disk('public')->delete($campaign->thank_image);
            $campaign->thank_image = null;
        }
        if ($r->filled('remove_reminder_image') && $campaign->reminder_image) {
            Storage::disk('public')->delete($campaign->reminder_image);
            $campaign->reminder_image = null;
        }
        $campaign->save();

        foreach (['cover_image','thank_image','reminder_image'] as $field) {
        if ($r->hasFile($field)) {
                // supprimer l’ancienne si vous voulez :
                // Storage::disk('public')->delete($campaign->$field);
                $path = $r->file($field)->store('campaigns/'.$campaign->id, 'public');
                $campaign->update([$field => $path]);
            }
        }

        // 3) Mise à jour des groupes associés
        $suffixes = ['En attente', 'Payés'];
        foreach ($suffixes as $suffix) {
            $oldGroupName = "{$oldName} - {$suffix}";
            $newGroupName = "{$campaign->name} - {$suffix}";

            $group = Group::where('name', $oldGroupName)->first();
            if ($group) {
                // Remplace également l'ancien nom dans la description
                $newDescription = str_replace($oldName, $campaign->name, $group->description);

                $group->update([
                    'name'        => $newGroupName,
                    'description' => $newDescription,
                ]);
            }
        }

        return back()->with('success', 'Campagne et groupes associés mis à jour.');
    }

    public function destroy(Campaign $campaign)
    {
        if ($campaign->links()->exists()) {
            return back()->with('error', 'Suppression impossible : la campagne possède encore des liens.');
        }

        $campaign->delete();
        return back()->with('success','Campagne supprimée');
    }

    // Formulaire d'envoi
    public function sendForm(Campaign $campaign)
    {
        // récupérer liste de donateurs et groupes
        $donateurs = Donateur::orderBy('nom')->get();
        $groups    = Group::with('donateurs:id')->orderBy('name')->get();
        return view('campaigns.send', compact('campaign','donateurs','groups'));
    }

    // Traitement d'envoi (sera implémenté en phase 5)
    public function send(Request $r, Campaign $campaign)
    {
        $data = $r->validate([
            'donateurs' => 'nullable|array',
            'donateurs.*' => 'exists:donateurs,id',
            'groups'    => 'nullable|array',
            'groups.*'  => 'exists:groups,id',
        ]);

        $donateurIds = $data['donateurs'] ?? [];
        $groupIds    = $data['groups'] ?? [];

        $waitingGroupName = "{$campaign->name} - En attente";
        $waitingGroup = Group::firstOrCreate(
            ['name' => $waitingGroupName],
            ['description' => "Donateurs en attente pour la campagne « {$campaign->name} »"]
        );

        foreach ($donateurIds as $donId) {
            if (! $waitingGroup->donateurs->contains($donId)) {
                $waitingGroup->donateurs()->attach($donId);
            }
        }

        SendCampaignNotifications::dispatch(
            $campaign,
            $donateurIds,
            $groupIds
        );

        return back()->with('success','Envoi en file d’attente.');
    }

    public function details(Campaign $campaign)
    {
        // Charger liens, donateurs et paiements
        $campaign->load(['links.donateur', 'links.payments']);

            // 1) Les liens/dons déjà payés
        $paidLinks = $campaign->links()
            ->where('status', LinkStatus::Paid)
            ->with('donateur')
            ->get();

        // 2) Ceux qui ont refusé la relance
        $optOutLinks = $campaign->links()
            ->where('no_relance', true)
            ->with('donateur')
            ->get();

        // 3) Ceux qui acceptent encore la relance
        $toRelanceLinks = $campaign->links()
            ->where('status', LinkStatus::Pending)
            ->where('no_relance', false)
            ->with('donateur')
            ->get();

        //dd($toRelanceLinks);
        //dd($campaign,$toRelanceLinks,$optOutLinks,$paidLinks );

        return view('campaigns.details', compact(
            'campaign',
            'paidLinks',
            'optOutLinks',
            'toRelanceLinks'
        ));
    }

    public function detailsAjax(Request $request, Campaign $campaign)
    {
        if (! $request->ajax()) {
            return abort(404);
        }

        $campaign->load(['links.donateur', 'links.payments']);
        return view('campaigns.partials.details', compact('campaign'));
    }

    public function remind(Campaign $campaign, NotificationService $notifier)
    {
        // Nom exact du groupe “En attente” pour cette campagne
        $waitingName  = "{$campaign->name} - En attente";
        $waitingGroup = Group::firstWhere('name', $waitingName);

        if (! $waitingGroup) {
            return back()->with('error', "Le groupe “En attente” ({$waitingName}) n'existe pas.");
        }
        $i=0;
        // On boucle sur chaque donateur du groupe
        foreach ($waitingGroup->donateurs as $donateur) {
            // On récupère le lien associé à cette campagne
            $link = $donateur->links()
                            ->where('campaign_id', $campaign->id)
                            ->where('status', LinkStatus::Pending)   // par sécurité
                            ->where('no_relance', false)
                            ->first();

            if ($link) {
                $notifier->sendReminder($link);
                $i++;
            }
        }

        return back()->with('success', "Relance envoyée à {$i} donateur(s).");
    }
}