<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Cookie;

class AuthController extends Controller {

    public function index()
    {
        return view('auth.index');
    }

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

        $usuario = DB::table('con_usuarios')
            ->where('email', $request->email)
            ->first();

        if ($usuario && Hash::check($request->password, $usuario->clave)) {
            
            Auth::loginUsingId($usuario->id, true);
            $lang = $request->input('idioma', config('app.locale'));
            session(['locale' => $lang]);
            app()->setLocale($lang); 

            $response = response()->json([
                'success' => true,
                'message' => 'Inicio de sesión correcto'
            ]);

            if ($request->has('remember')) {
                $minutes = 60 * 24 * 30;
                $response->withCookie(cookie('remember_email', $request->email, $minutes));
                $response->withCookie(cookie('remember_password', $request->password, $minutes));
                $response->withCookie(cookie('remember_idioma', $lang, $minutes));
            } else {
                $response->withCookie(Cookie::forget('remember_email'));
                $response->withCookie(Cookie::forget('remember_password'));
                $response->withCookie(Cookie::forget('remember_idioma'));
            }

            return $response;
        }

        return response()->json([
            'success' => false,
            'message' => 'Email o clave incorrectos'
        ]);
    }

    public function formCambioPassword()
    {
        return view('configuracion.password.index');
    }

    public function cambioPassword(Request $request)
    {

        $request->validate([
            'ClaveActual' => 'required',
            'ClaveNueva' => 'required|min:8',
            'ClaveNueva2' => 'required|same:ClaveNueva',
        ]);

        $usuario = Auth::user();

        if (!Hash::check($request->ClaveActual, $usuario->clave)) {
            return response()->json([
                'success' => false,
                'message' => 'La clave actual ingresada es incorrecta'
            ]);
        }

        $datos = [
            'clave' => bcrypt($request->ClaveNueva)
        ];

        $actualizado = DB::table("con_usuarios")
            ->where('id', $usuario->id)
            ->update($datos);

        if ($actualizado) {
            return response()->json([
                'success' => true,
                'message' => 'Clave actualizada con éxito'
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'Ocurrió un error al actualizar la clave'
        ]);
    }


    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('login');
    }
}
