<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

class AuthController extends Controller
{
    public function index()
    {
        return "";
    }
    
    public function login(Request $request)
    {
        $credentials = $request->only(['email', 'password']);

        $validator = Validator::make($credentials, [
            'email' => 'required',
            'password' => 'required',
        ]);

        if ($validator->fails()) {
            return response($validator->errors()->all(), 422);
        }
        
        $username = $request->input('email');
        
        $checkUser = User::where('username', $username)->first();
        
        if (!$checkUser) {
            return response("User not found", 401);
        } else {
            if (!Hash::check($request->input('password'), $checkUser->pass_mobile)) {
                return response("Password incorrect", 401);
            }
        }

        $token = auth()->login($checkUser);
        $output = $this->respondWithToken($token);
        
        return response()->json($output);
    }
    
    // public function login(Request $request)
    // {
    //     $credentials = $request->only(['email', 'password']);
    
    //     $validator = Validator::make($credentials, [
    //         'email' => 'required',
    //         'password' => 'required',
    //     ]);
    
    //     if ($validator->fails()) {
    //         return response($validator->errors()->all(), 422);
    //     }
        
    //     $username = $request->input('email');
        
    //     // Debug: Log or return the username
    //     \Log::debug('Input username:', ['username' => $username]);
        
    //     $checkUser = User::where('username', $username)->first();
        
    //     // Debug: Log the user check result
    //     \Log::debug('User found:', ['user' => $checkUser]);
        
    //     if (!$checkUser) {
    //         return response("User not found", 401);
    //     } else {
    //         // Debug: Log the password check
    //         \Log::debug('Password check initiated');
            
    //         // Check if password matches
    //         if (!Hash::check($request->input('password'), $checkUser->pass_mobile)) {
    //             // Debug: Log password mismatch
    //             \Log::debug('Password mismatch', ['input_password' => $request->input('password'), 'stored_password' => $checkUser->pass_mobile]);
    //             return response("Password incorrect", 401);
    //         }
    //     }
    
    //     $token = auth()->login($checkUser);
    //     $output = $this->respondWithToken($token);
        
    //     // Debug: Log the generated token
    //     \Log::debug('Generated token:', ['token' => $token]);
    
    //     return response()->json($output);
    // }
    
    // public function login(Request $request)
    // {
    //     // Ambil email (username) dan password dari input, serta kd_gelombang
    //     $credentials = $request->only(['email', 'password', 'kd_gelombang']);
    
    //     $validator = Validator::make($credentials, [
    //         'email' => 'required',
    //         'password' => 'required',
    //         'kd_gelombang' => 'required',  // Validasi kd_gelombang
    //     ]);
    
    //     // Cek validasi
    //     if ($validator->fails()) {
    //         return response($validator->errors()->all(), 422);
    //     }
    
    //     $username = $request->input('email');
    //     $kd_gelombang = $request->input('kd_gelombang');
    
    //     // Debug: Log username dan kd_gelombang
    //     \Log::debug('Input username dan kd_gelombang:', ['username' => $username, 'kd_gelombang' => $kd_gelombang]);
    
    //     // Cari user berdasarkan username dan kd_gelombang
    //     $checkUser = User::where('username', $username)
    //                      ->where('kd_gelombang', $kd_gelombang)
    //                      ->first();
    
    //     // Debug: Log hasil pencarian user
    //     \Log::debug('User ditemukan:', ['user' => $checkUser]);
    
    //     // Jika user tidak ditemukan
    //     if (!$checkUser) {
    //         return response("User dengan kd_gelombang tersebut tidak ditemukan", 401);
    //     } else {
    //         // Cek password
    //         if (!Hash::check($request->input('password'), $checkUser->pass_mobile)) {
    //             // Debug: Log password mismatch
    //             \Log::debug('Password mismatch', ['input_password' => $request->input('password'), 'stored_password' => $checkUser->pass_mobile]);
    //             return response("Password incorrect", 401);
    //         }
    //     }
    
    //     // Generate token
    //     $token = auth()->login($checkUser);
    //     $output = $this->respondWithToken($token);
        
    //     // Debug: Log token yang dihasilkan
    //     \Log::debug('Generated token:', ['token' => $token]);
    
    //     return response()->json($output);
    // }
    
    public function me()
    {
        return response()->json(auth()->user());
    }

    public function logout()
    {
        auth()->logout();
        return response()->json(['message' => 'Berhasil Keluar.']);
    }

    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    protected function respondWithToken($token)
    {
        $user = auth()->user();
        
        // Periksa apakah group_id == 8
        // Ambil kd_gelombang dari user
        $kd_gelombang = $user->kd_gelombang;
        // Log::info("kd_gelombang: $kd_gelombang");

        if ($user->id_group == 8) {
            $profile = $user->CalonMahasiswa()->with([
                'kd_agama', 
                'prodi', 
            ])->first();
        } else {
            $profile = $user->profile()->with([
                'group_id', 
                'kelurahan', 
                'kecamatan', 
                'kabupaten', 
                'provinsi', 
                'kd_agama', 
                'prodi', 
                'kelaskuliah'
            ])->first();
        }
    
        $responseData = [
            'message' => 'Data berhasil ditemukan',
            'token' => $token,
            'token_type' => 'bearer',
            'login' => 'true',
            'user' => [
                'id' => $user->id,
                'kd_gelombang' => $user->kd_gelombang,
                'id_user' => $user->id_user,
                'id_group' => $user->id_group,
                'id_company' => $user->id_company,
                'username' => $user->username,
                'pass_mobile' => $user->pass_mobile,
                'id_session' => $user->id_session,
                'tgl_registrasi' => $user->tgl_registrasi,
                'aktif' => $user->aktif,
                'online' => $user->online,
            ],
            'expires_in' => auth()->factory()->getTTL() * 60 * 24
        ];
    
        // Tambahkan data grup jika ada
        if ($user->m_group) {
            $responseData['user']['group_name'] = $user->m_group->group_name;
            $responseData['user']['group_description'] = $user->m_group->group_description;
        }
    
        // Tambahkan data profil ke dalam respons
        if ($profile) {
            // Tambahkan profil dan pastikan tempat_lahir serta tanggal_lahir visible
            $profile->makeVisible(['tempat_lahir', 'tanggal_lahir']);
            $responseData['user']['profile'] = $profile;
        }
    
        return $responseData;
    }

}
