<?php

namespace App\Http\Controllers\api;

use App\Models\User;
use App\Models\Profile;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'role' => 'required',
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required|min:8|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/|confirmed',
            'password_confirmation' => 'required',
        ], [
            'required' => ':attribute harus diisi.',
            'email' => ':attribute harus berupa email yang valid.',
            'min' => 'panjang :attribute minimal :min karakter.',
            'regex' => ':attribute harus mengandung minimal satu huruf kecil, satu huruf besar, dan satu angka.',
            'confirmed' => 'Password dan konfirmasi password tidak sama.'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'error' => true,
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ]);
        }

        $cek_email = User::where('email', $request->email)->get()->count();
        if ($cek_email > 0) {
            return response()->json([
                'error' => true,
                'message' => "Email telah terpakai. Silahkan hubungi CS untuk konfirmasi jika merasa tidak mendaftar.",
                'data' => null
            ]);
        }

        $username = $this->generateUsername($request->name);

        $user = User::create([
            'role' => $request->role,
            'name' => $request->name,
            'username' => $username,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'status' => '1'
        ]);

        // Tambahkan Notifikasi
        // $notifikasi = Notification::create([
        //     'user_id' => $user_id,
        //     'judul' => "Anggota Baru",
        //     'isi' => "Anggota baru \"".$request->nama."\" telah mendaftar. Cek sekarang!"
        // ]);

        // event(new ContentNotification("Anggota baru \"".$request->nama."\" telah mendaftar. Cek sekarang!", $user_id));

        return response()->json([
            'error' => false,
            'message' => 'Berhasil melakukan registrasi. Silahkan Login.',
            'data' => null
        ]);
    }

    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required',
        ], [
            'required' => ':attribute harus diisi.',
            'email' => 'alamat email pada kolom :attribute tidak valid.',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'error' => true,
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ]);
        }

        $user = User::select(['id', 'name', 'status', 'role'])->where('email', $request->email)->first();
        if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
            if ($user->role != 1) {
                return response()->json([
                    'error' => true,
                    'message' => 'Anda tidak memiliki hak akses.',
                    'data' => null
                ]);
            }
            $token = $user->createToken("auth-token")->plainTextToken;
            Auth::login($user);
        } else {
            return response()->json([
                'error' => true,
                'message' => 'Pastikan email dan password anda benar.',
                'data' => null
            ]);
        }

        $user = $user->load('profile');

        return response()->json([
            'error' => false,
            'message' => 'Berhasil login.',
            'data' => [
                'token' => $token,
                'user' => $user
            ]
        ]);
    }

    public function login_user(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required',
        ], [
            'required' => ':attribute harus diisi.',
            'email' => 'alamat email pada kolom :attribute tidak valid.',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'error' => true,
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ]);
        }

        $user = User::select([
                    'users.id', 'username', 'users.name', 'status', 'role', 'profiles.location',
                    DB::raw('COUNT(DISTINCT user_skills.id) as skill_count')
                ])
                ->leftJoin('profiles', 'profiles.user_id', '=', 'users.id')
                ->leftJoin('user_skills', 'user_skills.user_id', '=', 'users.id')
                ->where('email', $request->email)
                ->groupBy([
                    'users.id', 'username', 'users.name', 'status', 'role', 'profiles.location'
                ])
                ->first();
        if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
            if ($user->role == 1) {
                return response()->json([
                    'error' => true,
                    'message' => 'Anda tidak memiliki hak akses.',
                    'data' => null
                ]);
            }
            $token = $user->createToken("auth-token")->plainTextToken;
            Auth::login($user);
        } else {
            return response()->json([
                'error' => true,
                'message' => 'Pastikan email dan password anda benar.',
                'data' => null
            ]);
        }

        // $user = $user->load('profile');

        return response()->json([
            'error' => false,
            'message' => 'Berhasil login.',
            'data' => [
                'token' => $token,
                'user' => $user
            ]
        ]);
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
    }

    function generateUsername($name)
    {
        $cleanedName = preg_replace('/[^a-zA-Z0-9]/', '', $name);

        $cleanedName = strtolower($cleanedName);

        $randomString = Str::random(6);
        $username = $cleanedName . $randomString;

        return $username;
    }
}
