<?php

namespace App\Http\Controllers\API;

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

class AuthApiController extends Controller
{
    public function login(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'telepon'   => 'required',
                'password'  => 'required'
            ], [
                'telepon.required'  => 'nomor telepon wajib diisi',
                'password.required' => 'password wajib diisi'
            ]);
            
            if ($validator->fails()) {
                return response()->json([
                    'errors' => $validator->errors()
                ], 400);
            }
            
            $user = User::where('telepon', $request->telepon)->first();
            
            if (!$user || !Hash::check($request->password, $user->password)) {
                return response()->json([
                    'errors' => [
                        'telepon' => 'nomor telepon atau password salah',
                        'password' => 'nomor telepon atau password salah'
                    ]
                ], 400);
            }
            
            Auth::login($user);
            $request->session()->regenerate();
            
            $token = $user->createToken('auth_token')->plainTextToken;
            
            return response()->json([
                'data' => [
                    'token' => $token
                ]
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'errors' => [
                    'message' => 'Terjadi kesalahan pada server'
                ]
            ], 500);
        }
    }


    public function logout(Request $request)
    {
        $user = $request->user();
    
        if ($user) {
            $user->tokens()->delete();
            
            return response()->json([
                'message' => 'berhasil logout'
            ], 200);
        }
        
        return response()->json([
            'success' => false,
            'message' => 'User tidak terautentikasi'
        ], 400);
    }
}