<?php

namespace App\Http\Controllers\Api\V1\Backend\Login;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Backend\Catalog\User as AdminUser;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Api\V1\Backend\ResponseController;
use Illuminate\Support\Facades\Hash;
use App\Helpers\OpenCartPassword;

class AuthController extends ResponseController
{
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required|string',
            'password' => 'required|string|min:6',
        ]);
        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }
        try {
            $credentials = $request->only('username', 'password');

            $user = AdminUser::select('user_id','firstname', 'email', 'image', 'status', 'password', 'salt')
                ->where('username', $credentials['username'])
                ->first();

            if ($user && OpenCartPassword::verify($credentials['password'], $user->password, $user->salt)) {
                Auth::login($user); // Login manually
                $token = $user->createToken('admin-token')->plainTextToken;
                $user->makeHidden(['password', 'salt']);
                // dd($token);
                return $this->sendResponse([
                    'user' => $user,
                    'token' => $token
                ], 'Login successful', 200);
            }
            return $this->sendError('Invalid credentials', [], 401);


        } catch (\Exception $e) {
            return $this->sendError('Login failed. Please try again.', [], 500);
        }

    }
}
