<?php
// app/Http/Controllers/Api/Auth/AuthController.php
namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\Auth\LoginRequest;
use App\Http\Requests\Api\Auth\RegisterRequest;
use App\Http\Requests\Api\Auth\UpdateProfileRequest;
use App\Http\Requests\Api\Auth\ChangePasswordRequest;
use App\Models\User;
use App\Traits\ApiResponse;
use App\Http\Resources\Api\UserResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    use ApiResponse;

    /**
     * Register new customer
     */
    public function register(RegisterRequest $request): JsonResponse
    {
        try {
            $validated = $request->validated();
            
            $user = User::create([
                'name' => $validated['name'],
                'email' => $validated['email'],
                'phone' => $validated['phone'],
                'password' => Hash::make($validated['password']),
                'role' => 'customer',
            ]);

            $token = $user->createToken('auth_token')->plainTextToken;

            return $this->successResponse([
                'user' => new UserResource($user),
                'token' => $token,
                'token_type' => 'Bearer'
            ], 'Registrasi berhasil', 201);

        } catch (\Exception $e) {
            return $this->errorResponse('Registrasi gagal: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Login for all roles
     */
    public function login(LoginRequest $request): JsonResponse
    {
        try {
            $validated = $request->validated();
            
            $user = User::where('email', $validated['email'])->first();

            if (!$user || !Hash::check($validated['password'], $user->password)) {
                return $this->errorResponse('Email atau password salah', 401);
            }

            $token = $user->createToken('auth_token')->plainTextToken;

            return $this->successResponse([
                'user' => new UserResource($user),
                'token' => $token,
                'token_type' => 'Bearer'
            ], 'Login berhasil');

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Login gagal: ' . $e->getMessage(),
                'error' => $e->getTraceAsString()
            ], 500);
        }
    }

    /**
     * Get authenticated user profile
     */
    public function me(Request $request): JsonResponse
    {
        try {
            $user = $request->user();
            
            if (!$user) {
                return $this->errorResponse('Tidak terautentikasi', 401);
            }

            return $this->successResponse([
                'user' => new UserResource($user)
            ], 'Profil berhasil diambil');

        } catch (\Exception $e) {
            return $this->errorResponse('Gagal mengambil profil', 500);
        }
    }

    /**
     * Update user profile
     */
    public function updateProfile(UpdateProfileRequest $request): JsonResponse
    {
        try {
            $user = $request->user();
            
            if (!$user) {
                return $this->errorResponse('Tidak terautentikasi', 401);
            }

            $validated = $request->validated();
            $user->update($validated);

            return $this->successResponse([
                'user' => new UserResource($user)
            ], 'Profil berhasil diperbarui');

        } catch (\Exception $e) {
            return $this->errorResponse('Gagal memperbarui profil', 500);
        }
    }

    /**
     * Change password
     */
    public function changePassword(ChangePasswordRequest $request): JsonResponse
    {
        try {
            $user = $request->user();
            
            if (!$user) {
                return $this->errorResponse('Tidak terautentikasi', 401);
            }

            $validated = $request->validated();

            if (!Hash::check($validated['current_password'], $user->password)) {
                return $this->errorResponse('Password saat ini salah', 422);
            }

            $user->update([
                'password' => Hash::make($validated['new_password'])
            ]);

            return $this->successResponse([], 'Password berhasil diubah');

        } catch (\Exception $e) {
            return $this->errorResponse('Gagal mengubah password', 500);
        }
    }

    /**
     * Logout (Revoke token)
     */
    public function logout(Request $request): JsonResponse
    {
        try {
            $user = $request->user();
            
            if (!$user) {
                return $this->errorResponse('Tidak terautentikasi', 401);
            }

            $user->currentAccessToken()->delete();

            return $this->successResponse([], 'Logout berhasil');

        } catch (\Exception $e) {
            return $this->errorResponse('Logout gagal', 500);
        }
    }
}