<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\LoginRequest;
use App\Interfaces\ApiInterface\AuthRepositoryInterface;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    protected $authrepository;

    public function __construct(AuthRepositoryInterface $authrepository)
    {
        $this->authrepository = $authrepository;
    }

    public function Login(LoginRequest $request)
    {
        $data = $request->validated();

        $user = $this->authrepository->login($data['email']);

        if (!$user || !Hash::check($data['password'], $user->password)) {
            return response()->json([
                'status' => 'error',
                'message' => 'Username Atau Password Salah'
            ], 401);
        }

        if ($user->approve == null) {
            return response()->json([
                'status' => 'error',
                'message' => 'Akun Anda Belum Disetujui'
            ], 401);
        }

        if ($user->approve == 0) {
            return response()->json([
                'status' => 'error',
                'message' => 'Mohon Maaf Akun Anda Tidak Disetujui'
            ], 401);
        }

        $user->tokens()->delete();
        $token = $user->createToken('rahasia')->plainTextToken;
        $role = $user->role;
        return response()->json([
            'status' => 'success',
            'message' => 'Login Berhasil',
            'data' => [
                'id' => $user->id,
                'name' => $user->name,
                'access_token' => $token,
                'token_type' => 'Bearer',
                'role' => $user->role->role,
                'location_id' => $user->location->id,
                'location' => $user->location->name,
                "all_site" => $role->isAllLocation == "1" || $role->isAllLocation == 1 || $role->isAllLocation == true
            ]
        ], 200);
    }

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

        return response()->json([
            "status" => "success",
            "message" => "Logout Success"
        ], 200);
    }

    public function updatePassword(Request $request)
    {
        $request->validate([
            'old_password' => 'required|string',
            'new_password' => 'required|string|min:6|confirmed',
        ]);

        $userId = auth()->id();

        $result = $this->authrepository->updatePassword(
            $userId,
            $request->old_password,
            $request->new_password
        );

        if (!$result['success']) {
            return response()->json([
                'success' => false,
                'message' => $result['message']
            ], 400);
        }

        return response()->json([
            'success' => true,
            'message' => $result['message']
        ]);
    }
}
