<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Log;
use App\Mail\UserApproveMail;

use Illuminate\Http\Request;
use App\Models\{Institution, User, Service};
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\{Mail, Crypt};
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;


class LoginController extends Controller
{
    //
    public function showLoginForm()
    {
        return view('auth.login');
    }
    public function showRegisterForm()
    {
        return view('auth.register', [
            'institutions' => Institution::all(),
            'services' => Service::all()
        ]);
    }


    public function register(Request $request)
    {
        $isRectorate = $request->boolean('is_rectorate');

        $validated = $request->validate([
            'first_name' => ['required', 'string', 'max:100'],
            'last_name' => ['required', 'string', 'max:100'],

            'email' => [
                'required',
                'email',
                'max:255',
                'unique:users,email',
            ],

            'mobile' => [
                'nullable',
                'string',
                'max:20',
            ],

            // 🔁 Institution OU Service selon le switch
            'institution_id' => [
                Rule::requiredIf(!$isRectorate),
                'nullable',
                'exists:institutions,id',
            ],

            'service_id' => [
                Rule::requiredIf($isRectorate),
                'nullable',
                'exists:services,id',
            ],

            'role' => [
                'required',
                Rule::in(['secretaire', 'chef-institution']),
            ],

            'password' => [
                'required',
                'confirmed',
                'min:8',
            ],
        ]);

        /**
         * 🔹 Construction du nom complet
         */
        $fullName = trim(
            ucfirst(strtolower($validated['first_name'])) . ' ' .
            strtoupper($validated['last_name'])
        );

        /**
         * 🔹 Normalisation du numéro WhatsApp
         */
        $phone = null;
        if (!empty($request->mobile)) {
            $rawPhone = trim($request->mobile);
            $phone = preg_replace('/\s+/', '', $rawPhone);

            // 8 chiffres → Bénin sans indicatif
            if (preg_match('/^\d{8}$/', $phone)) {
                $phone = '22901' . $phone;
            }
            // 10 chiffres commençant par 01 → Bénin
            elseif (preg_match('/^01\d{8}$/', $phone)) {
                $phone = '229' . $phone;
            }
            // sinon : on garde la valeur telle quelle (international)
        }

        /**
         * 🔹 Création utilisateur
         */
        $user = User::create([
            'name' => $fullName,
            'email' => $validated['email'],
            'mobile' => $phone,

            // 🔁 Exclusivité institution / service
            'institution_id' => $isRectorate ? null : $validated['institution_id'],
            'service_id' => $isRectorate ? $validated['service_id'] : null,

            'role' => $validated['role'],

            'password' => Hash::make($validated['password']),
            'is_admin' => 0, // validation requise
            'status' => 'pending',
        ]);
        toast('Votre profil a été créé avec succès et est en cours de validation. Vous serez informé(e) par mail et par whatsapp de sa validation', 'success');
        return redirect()
            ->route('welcome')
            ->with('success', 'Compte créé avec succès. En attente de validation.');
    }

    // Traite le login
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required']
        ]);

        $remember = $request->has('remember');

        if (Auth::attempt($credentials, $remember)) {
            $request->session()->regenerate();

            // Redirection selon rôle
            if (auth()->user()->status == 'confirmed' || auth()->user()->role == 'vr-aa') {

                return redirect()->route('admin.appointments.index');
            }

            return redirect()->intended('/');
        }

        return back()->withErrors([
            'email' => 'Identifiants incorrects',
        ])->withInput();
    }

    // Logout
    public function logout(Request $request)
    {
        Auth::logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/');
    }

    public function index()
    {
        $users = User::with('institution')
            ->orderByDesc('created_at')
            ->get();

        return view('admin.users.index', [

            'users' => $users,
        ]);
    }

    public function approve(Request $request, $id)
    {
        $user = User::findOrFail($id);
        $user->status = 'confirmed';
        $user->admin_note = $request->admin_note_approve;
        $user->save();
        $message = "Bonjour {$user->name},\n";
        $message .= "Nous espérons que notre message vous trouvera en pleine santé. Vous recevez ce message en réponse à la demande de validation de votre profil sur la plateforme *Audience Rectorat*. \n Votre profil a été bien validé. Vous pouvez désormais vous authentifier avec les identifiants que vous avez fourni \n Cordialement, \n *Le Service Informatique du Rectorat de l\'UAC*";
        Log::info('Message final envoyé', ['message' => $message]);


        // ========== ENVOI WHATSAPP ==========

        $params = [
            'token' => config('services.ultra_msg.token'),
            'to' => $user->mobile,
            'image' => 'https://ifri-uac.bj/assets/img/logouac.png',
            'caption' => $message
        ];

        Log::info('Params envoyés WhatsApp', $params);

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => "https://api.ultramsg.com/instance113582/messages/image",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($params),
            CURLOPT_HTTPHEADER => ["Content-Type: application/x-www-form-urlencoded"],
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => 0,
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);

        if ($err) {
            Log::error("Erreur cURL UltraMsg", ['error' => $err]);
        } else {
            Log::info("Réponse UltraMsg", ['response' => $response]);
        }


        // ========== ENVOI MAIL ==========
        if (!empty($user->email)) {
            Mail::to($user->email)->send(new UserApproveMail([
                'name' => $user->name,
                'subject' => "Validation de profil sur la plateforme Audience Rectorat",
                'image' => 'https://ifri-uac.bj/assets/img/logouac.png',
            ]));
        } else {
            Log::warning("Pas d'email pour cet utilisateur, mail non envoyé",);
        }


        return response()->json([
            'success' => true,
            'message' => 'Utilisateur validé avec succès',
        ]);
    }

    public function reject(Request $request, $id)
    {
        $user = User::findOrFail($id);
        $user->status = 'rejected';
        $user->admin_note = $request->admin_note_reject;
        $user->save();
        $message = "Bonjour {$user->name},\n";
        $message .= "Nous espérons que notre message vous trouvera en pleine santé. Vous recevez ce message en réponse à la demande de validation de votre profil sur la plateforme *Audience Rectorat*. \n Votre profil a été rejeté pour le motif suivant: *{$user->admin_note}* \n Cordialement, \n *Le Service Informatique du Rectorat de l\'UAC*";
        Log::info('Message final envoyé', ['message' => $message]);


        // ========== ENVOI WHATSAPP ==========

        $params = [
            'token' => config('services.ultra_msg.token'),
            'to' => $user->mobile,
            'image' => 'https://ifri-uac.bj/assets/img/logouac.png',
            'caption' => $message
        ];

        Log::info('Params envoyés WhatsApp', $params);

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => "https://api.ultramsg.com/instance113582/messages/image",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($params),
            CURLOPT_HTTPHEADER => ["Content-Type: application/x-www-form-urlencoded"],
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => 0,
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);

        if ($err) {
            Log::error("Erreur cURL UltraMsg", ['error' => $err]);
        } else {
            Log::info("Réponse UltraMsg", ['response' => $response]);
        }


        // ========== ENVOI MAIL ==========
        if (!empty($user->email)) {
            Mail::to($user->email)->send(new UserApproveMail([
                'name' => $user->name,
                'subject' => "Validation de profil sur la plateforme Audience Rectorat",
                'object'=> $user->admin_note,
                'image' => 'https://ifri-uac.bj/assets/img/logouac.png',
            ]));
        } else {
            Log::warning("Pas d'email pour cet utilisateur, mail non envoyé");
        }


        return response()->json([
            'success' => true,
            'message' => 'Utilisateur rejeté',
        ]);
    }
}
