<?php
/**
 * File name: AjaxController.php
 * Last modified: 2022.06.11 at 16:10:52
 * Author:Siddhi
 * Copyright (c) 2022
 */

namespace App\Http\Controllers\Auth;

use App\Models\VendorUsers;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;
use Prettus\Validator\Exceptions\ValidatorException;
use App\Models\Admin_User;


class AjaxController extends Controller
{


    public function setToken(Request $request){
        // Walidacja danych wejściowych dla bezpieczeństwa
        $request->validate([
            'email' => 'required|email|max:255',
            'userId' => 'required|string|max:255',
            'id' => 'required|string|max:255',
            'role' => 'required|string|max:50',
            'firstName' => 'nullable|string|max:255',
            'lastName' => 'nullable|string|max:255'
        ]);

        // 1) Grab the user ID that corresponds to your Firebase node
        $userId = $request->userId;

        $role = $request->role;
        Log::info('Role retrieved', ['role' => $role]);
        $request->session()->put('role', $role);
        $uuid = $request->id;
        $password = $request->password;
        $exist = VendorUsers::where('email',$request->email )->get();
        $data = $exist->isEmpty();

        if($exist->isEmpty()){
            // Zabezpieczone auto-tworzenie użytkownika
            
            // Jeśli brak hasła, generuj bezpieczne tymczasowe
            if (empty($password)) {
                $password = Str::random(32);
                Log::info('Generated temporary password for auto-created user', ['email' => $request->email]);
            }

            // Użyj transakcji dla atomowości
            DB::transaction(function () use ($request, $password, $uuid) {
                $user = User::create([
                    'name' => $request->firstName . ' ' . $request->lastName ?: $request->email,
                    'email' => $request->email,
                    'password' => Hash::make($password),
                    'email_verified_at' => now(), // Firebase już zweryfikował
                ]);

                VendorUsers::create([
                    'user_id' => $user->id,
                    'uuid' => $uuid,
                    'email' => $request->email,
                    'roleType' => $request->role,
                ]);
                
                Log::info('Auto-created user successfully', [
                    'user_id' => $user->id,
                    'email' => $request->email,
                    'role' => $request->role
                ]);
            });
        }

        //$user = VendorUsers::where('user_id',$userId)->first();

        $user = User::where('email',$request->email)->first();


        /* Auth::loginUsingId($user->id, true); */
       Auth::login($user,true);
       $data = array();
       if(Auth::check()){

            $data['access'] = true;
       }


        return $data;
    }

    public function mysqlLogin(Request $request) {
        // Ograniczone logowanie dla bezpieczeństwa
        Log::info('MySQL login attempt');
        
        try {
            $request->validate([
                'email' => 'required|email|max:255',
                'password' => 'required|string|min:1|max:255'
            ]);

            // using pgsql now instead of mysql
            $user = Admin_User::where('email', $request->email)->first();
            
            if (!$user) {
                Log::warning('User not found in MySQL');
                return response()->json(['error' => trans('lang.user_not_found_in_firestore')], 401);
            }
            
            // Sprawdź hasło
            $passwordMatch = Hash::check($request->password, $user->password);
            
            if (!$passwordMatch) {
                Log::warning('Invalid password for MySQL login');
                return response()->json(['error' => trans('lang.invalid_password')], 401);
            }

            // Sprawdź czy użytkownik ma dostęp do systemu (jest w vendor_users)
            $vendorUser = VendorUsers::where('user_id', $user->id)->first();
            
            if (!$vendorUser) {
                Log::warning('User not authorized - no vendor_users record');
                return response()->json(['error' => trans('lang.user_not_authorized')], 403);
            }

            // Sprawdź rolę użytkownika w merchant_employees
            $merchantEmployee = \App\Models\MerchantEmployee::where('user_id', $user->id)->first();
            $role = 'vendor'; // domyślna rola
            
            if ($merchantEmployee) {
                // Mapuj role z merchant_employees na role Firebase
                $roleMapping = [
                    'main_user' => 'vendor',
                    'manager' => 'vendor', 
                    'bar' => 'employee',
                    'kitchen' => 'employee',
                    'waiter' => 'employee',
                    'custom' => 'employee'
                ];
                $role = $roleMapping[$merchantEmployee->role] ?? 'employee';
                
                Log::info('User role determined', [
                    'merchant_role' => $merchantEmployee->role,
                    'firebase_role' => $role,
                    'permissions' => $merchantEmployee->permissions
                ]);
                
                // WAŻNE: Aktualizuj roleType w vendor_users aby getUserRole() zwracała poprawną rolę
                DB::table('vendor_users')
                    ->where('user_id', $user->id)
                    ->update(['roleType' => $role]);
                    
                Log::info('Updated roleType in vendor_users', [
                    'user_id' => $user->id,
                    'new_roleType' => $role
                ]);
            }

            // Zaloguj użytkownika
            Auth::login($user, true);
            // Auth::guard('admin')->login($user, true);
            
            // Ustaw rolę w sesji (tak jak robi to setToken)
            $request->session()->put('role', $role);
            
            Log::info('MySQL login successful', [
                'user_id' => $user->id, 
                'email' => $user->email,
                'role' => $role
            ]);
            
            // Zwróć dane potrzebne do przekierowania
            return response()->json([
                'success' => true,
                'redirect_url' => route('dashboard'),
                'user' => [
                    'id' => $user->id,
                    'email' => $user->email,
                    'name' => $user->name,
                    'role' => $role
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('MySQL login error', ['error' => $e->getMessage(), 'email' => $request->email]);
            return response()->json(['error' => trans('lang.server_error')], 500);
        }
    }

    public function logout(Request $request){

        $user_id = Auth::user()->user_id;
        $user = VendorUsers::where('user_id',$user_id)->first();

        try {
            Auth::logout();
        } catch (\Exception $e) {
              $this->sendError($e->getMessage(), 401);
        }

        $data1 = array();
        if(!Auth::check()){
          $data1['logoutuser'] = true;
        }
        return $data1;
    }


}
