<?php

namespace App\Http\Controllers\API;

use Carbon\Carbon;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\Routing\Controllers\HasMiddleware;

class AuthController extends Controller implements HasMiddleware
{
    /**
     * Get the middleware that should be assigned to the controller.
     */
    public static function middleware(): array
    {
        return [
            new Middleware('auth:api', except: ['login', 'register', 'autoLogin']),
        ];
    }

    public function login(Request $request)
    {
        // return response()->json(['message'=>'success']);
        $request->validate([
            // 'email' => 'required|string|email',
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        /**CHECK USER IF EXISTING IN THE CURRENT DB */
        $user = User::where('employee_id', $request->username)
            ->orWhere('username', $request->username)
            ->first();

        if($user !== null){
            $token = Auth::attempt(['username' => $user->username, 'password' => $request->password]);

            // dd('asdadadadadasd');
            /**IF NOT SUCCESSFULL PROMPT FOR ERROR MESSAGE */
            if (!$token) {
                return response()->json([
                    'message' => 'Incorrect Password',
                ], 404);
            }

            $user = Auth::user();

            // Assuming the profile picture URL is needed, and `employee_profile_picture_url` is an accessor in the User model
            $profilePictureUrl = $user->employee_profile_picture; // This accessor should be defined in the User model

            // Add profile picture URL to user data
            $userData = $user->toArray();

            $userData['profile_picture_url'] = $profilePictureUrl != null ? asset('storage/employee-profile/' . $profilePictureUrl->attachment) : '';

            return response()->json([
                'user' => $userData,
                'authorization' => [
                    'token' => $token,
                    'type' => 'bearer',
                ]
            ]);
        } else {
            return response()->json([
                'message' => 'Incorrect Username',
            ], 404);
            // /**ELSE, CHECK IF USER EXISTS IN THE OLD DB */
            // $data = \App\Models\OldDB\User::where('employee_id', $request['username'])->orWhere('u_name', $request->username)->first();

            // /**IF RECORD EXISTS IN THE OLD DB */
            // if(!$data) {
            //     return response()->json([
            //         'message' => 'Unauthorized',
            //     ], 401);
            // }
            // /**CHECK IF CORRECT PASSWORD */
            // $valid = $data->u_password == MD5($request['password']);

            // /** If not correct password, response with error */
            // if(!$valid){
            //     return response()->json([
            //         'message' => 'Invalid username and/or password',
            //     ], 401);
            // }

            // /**If correct password begin the transaction */
            // DB::connection()->beginTransaction();

            // try {
            //     /**CREATE RECORD TO NEW DB*/
            //     $user = User::create([
            //         'employee_id' => $data['employee_id'],
            //         'name' => $data['u_fname'].' '.$data['u_lname'],
            //         'first_name' => $data['u_fname'],
            //         'last_name'=>$data['u_lname'],
            //         'username'=> $data['u_name'],
            //         'email' => $data['email'],
            //         'email_verified_at' => $this->current_datetime,
            //         'default_company_id' => $data['company'],
            //         'default_dealership_id' => $data['dealer'],
            //         'password' => Hash::make($request->password),
            //         'created_at'=> $this->current_datetime,
            //     ]);

            //     /**Commit db changes */
            //     DB::connection()->commit();

            //     $credentials = $request->only('username', 'password');
            //     /**ATTEMPT TO LOGIN */
            //     $token = Auth::attempt($credentials);
            //     /**IF NOT SUCCESSFULL PROMPT FOR ERROR MESSAGE */
            //     if (!$token) {
            //         return response()->json([
            //             'message' => 'Unauthorized',
            //         ], 401);
            //     }
            //     /**IF SUCCESSFUL RETURN DATA WITH TOKEN */
            //     $user = Auth::user();
            //     return response()->json([
            //         'user' => $user,
            //         'authorization' => [
            //             'token' => $token,
            //             'type' => 'bearer',
            //         ]
            //     ]);
            // } catch (\Throwable $e) { /**if error */
            //     /**rollback db changes */
            //     DB::connection()->rollback();
            //     return response()->json([
            //         'message' => 'Unable to process request. Please try again.',
            //         'data'    => $e->getMessage()
            //     ], 422);
            // }
        }
    }

    public function register(Request $request)
    {
        $request->validate([
            'username' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
        ]);

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

        return response()->json([
            'message' => 'User created successfully',
            'user' => $user
        ]);
    }

    public function logout()
    {
        Auth::logout();
        return response()->json([
            'message' => 'Successfully logged out',
        ]);
    }

    public function refresh()
    {
        return response()->json([
            'user' => Auth::user(),
            'authorization' => [
                'token' => Auth::refresh(),
                'type' => 'bearer',
            ]
        ]);
    }

    public function autoLogin(int $id) {
        $user = User::find($id);
        $token = Auth::login($user);
        /**IF NOT SUCCESSFULL PROMPT FOR ERROR MESSAGE */
        if (!$token) {
            return response()->json([
                'message' => 'Unauthorized',
            ], 401);
        }

        return response()->json([
            'user' => $user,
            'authorization' => [
                'token' => $token,
                'type' => 'bearer',
            ]
        ]);
    }
}
