<?php
namespace App\Http\Controllers;

use App\Models\Donateur;
use Illuminate\Http\Request;
use App\Imports\DonateursImport;
use Maatwebsite\Excel\Facades\Excel;

class DonateurController extends Controller
{
    public function index()
    {
        $donateurs = Donateur::orderBy('created_at', 'desc')->get();
        return view('donateurs.index', compact('donateurs'));
    }

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

    public function details(Donateur $donateur)
    {
        // Charger tous les liens et paiements associés
        $donateur->load(['links.campaign', 'links.payments']);
        return view('donateurs.details', compact('donateur'));
    }

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

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

    public function store(Request $r)
    {
        $data = $r->validate([
            'nom'       => 'required|string',
            'prenom'    => 'required|string',
            'email'     => 'nullable|email|unique:donateurs',
            'telephone' => 'nullable|string|unique:donateurs',
            'sexe'      => 'required|in:M,F',
            'fonction'  => 'nullable|string',
        ]);

        Donateur::create($data);
        return back()->with('success','Donateur ajouté.');
    }

    public function edit(Donateur $donateur)
    {
        return view('donateurs.edit', compact('donateur'));
    }

    public function update(Request $r, Donateur $donateur)
    {
        $data = $r->validate([
            'nom'       => 'required|string',
            'prenom'    => 'required|string',
            'email'     => 'nullable|email|unique:donateurs,email,'.$donateur->id,
            'telephone' => 'nullable|string|unique:donateurs,telephone,'.$donateur->id,
            'sexe'      => 'required|in:M,F',
            'fonction'  => 'nullable|string',
        ]);
        $donateur->update($data);
        return back()->with('success','Donateur mis à jour.');
    }

    public function destroy(Donateur $donateur)
    {
        if ($donateur->links()->exists() || $donateur->groups()->exists()) {
            return back()->with('error', 'Suppression impossible : le donateur est encore référencé.');
        }

        $donateur->delete();
        return back()->with('success','Donateur supprimé');
    }

    public function import(Request $request)
    {
        // Confirmation step after preview
        if ($request->boolean('confirm')) {
            $action  = $request->input('action', 'all');
            $allRows = $request->session()->pull('import_rows', []);
            $rows    = $request->input('rows', []);

            if ($action === 'visible') {
                $remaining = array_diff_key($allRows, $rows);
            } else {
                $rows = $rows ?: $allRows;
                $remaining = [];
            }

            if (! $rows) {
                return redirect()->route('donateurs.index')
                    ->with('error', 'Aucun fichier à importer.');
            }

            $importer = new DonateursImport;

            $existingPhones = Donateur::whereNotNull('telephone')->pluck('telephone')->toArray();
            $existingEmails = Donateur::whereNotNull('email')->pluck('email')->toArray();
            $seenPhones    = [];
            $seenEmails    = [];

            $validated = [];
            foreach ($rows as $row) {
                $nomRaw    = trim($row['nom']     ?? '');
                $prenomRaw = trim($row['prenom']  ?? '');
                $emailRaw  = trim($row['email']   ?? '');
                $telRaw    = trim($row['telephone'] ?? '');
                $sexeRaw   = trim($row['sexe']    ?? '');
                $funcRaw   = trim($row['fonction'] ?? '');
                $grpRaw    = $row['groupes'] ?? '';

                $errors = [];
                if (! $nomRaw) {
                    $errors[] = 'Nom manquant';
                }
                if (! $prenomRaw) {
                    $errors[] = 'Prénom manquant';
                }

                $email = $emailRaw !== '' ? $importer->normalizeEmail($emailRaw) : null;
                $tel   = $telRaw   !== '' ? $importer->normalizePhone($telRaw) : null;
                if ($tel === '') {
                    $tel = null;
                }

                if ($tel) {
                    if (in_array($tel, $seenPhones, true) || in_array($tel, $existingPhones, true)) {
                        $errors[] = 'Téléphone dupliqué';
                    }
                    $seenPhones[] = $tel;
                }

                if ($email) {
                    if (in_array($email, $seenEmails, true) || in_array($email, $existingEmails, true)) {
                        $errors[] = 'Email dupliqué';
                    }
                    $seenEmails[] = $email;
                }

                if (! $email && ! $tel) {
                    $errors[] = 'Email ou téléphone manquant';
                }

                $validated[] = [
                    'nom'       => $nomRaw,
                    'prenom'    => $prenomRaw,
                    'email'     => $email,
                    'telephone' => $tel,
                    'sexe'      => $sexeRaw ?: null,
                    'fonction'  => $funcRaw ?: null,
                    'groupes'   => $grpRaw,
                    'errors'    => $errors,
                ];
            }

            $count = 0;
            foreach ($validated as $row) {
                if ($row['errors']) {
                    continue;
                }
                $importer->model($row);
                $count++;
            }

            if ($remaining) {
                $request->session()->put('import_rows', $remaining);
                return view('donateurs.import_preview', [
                    'rows' => $remaining,
                ])->with('success', $count.' donateur(s) importé(s) ou mis à jour.');
            }

            return redirect()->route('donateurs.index')
                ->with('success', $count.' donateur(s) importé(s) ou mis à jour.');
        }

        // Preview step
        $request->validate(['file' => 'required|file|mimes:csv,xlsx']);

        $importer   = new DonateursImport;
        $collection = Excel::toCollection($importer, $request->file('file'));
        $rows       = $collection->first();

        $existingPhones = Donateur::whereNotNull('telephone')->pluck('telephone')->toArray();
        $existingEmails = Donateur::whereNotNull('email')->pluck('email')->toArray();
        $seenPhones    = [];
        $seenEmails    = [];

        $preview = [];
        foreach ($rows as $row) {
            $nomRaw    = trim($row['nom']     ?? '');
            $prenomRaw = trim($row['prenom']  ?? '');
            $emailRaw  = trim($row['email']   ?? '');
            $telRaw    = trim($row['telephone'] ?? '');
            $sexeRaw   = trim($row['sexe']    ?? '');
            $funcRaw   = trim($row['fonction'] ?? '');
            $grpRaw    = $row['groupes'] ?? '';

            $errors = [];
            if (! $nomRaw) {
                $errors[] = 'Nom manquant';
            }
            if (! $prenomRaw) {
                $errors[] = 'Prénom manquant';
            }

            $email = $emailRaw !== '' ? $importer->normalizeEmail($emailRaw) : null;
            $tel   = $telRaw   !== '' ? $importer->normalizePhone($telRaw) : null;
            if ($tel === '') {
                $tel = null;
            }

            if ($tel) {
                if (in_array($tel, $seenPhones, true) || in_array($tel, $existingPhones, true)) {
                    $errors[] = 'Téléphone dupliqué';
                }
                $seenPhones[] = $tel;
            }

            if ($email) {
                if (in_array($email, $seenEmails, true) || in_array($email, $existingEmails, true)) {
                    $errors[] = 'Email dupliqué';
                }
                $seenEmails[] = $email;
            }

            if (! $email && ! $tel) {
                $errors[] = 'Email ou téléphone manquant';
            }

            $preview[] = [
                'nom'       => $nomRaw,
                'prenom'    => $prenomRaw,
                'email'     => $email,
                'telephone' => $tel,
                'sexe'      => $sexeRaw ?: null,
                'fonction'  => $funcRaw ?: null,
                'groupes'   => $grpRaw,
                'errors'    => $errors,
            ];
        }

        $request->session()->put('import_rows', $preview);

        return view('donateurs.import_preview', [
            'rows' => $preview,
        ]);
    }

    
}
