<?php

namespace App\Http\Controllers;

use App\Models\Admin;
use App\Models\Customer;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Validator;

class AdminAuthController extends Controller
{

    public function indexList()
    {
        $customers = Customer::query();
        $customers = request()->query("status") != null ? $customers->where("status", request()->query("status")) : $customers;
        $customers = request()->query("perpage") != null ? $customers->paginate(request()->query("perpage")) : $customers->get();
        foreach ($customers as $key => &$value) {
            $wallet = $value->wallet->balance;
            $value = $wallet;
        }
        return response()->json([
            'success' => true,
            'message' => 'Customers successfully',
            'customers' => $customers,
        ], 201);
    }

    public function singleCustomer($id)
    {
        $customer = Customer::find($id);
        $customer->wallet;
        return response()->json([
            'success' => true,
            'message' => 'Customers successfully',
            'customer' => $customer,
        ], 201);
    }

    /**
     * Register a new admin.
     */
    public function register(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:admins',
            'password' => 'required|string|min:8|confirmed',
            'role' => 'sometimes|string|in:admin,super_admin',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $admin = Admin::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => $request->role ?? 'admin',
        ]);

        $token = JWTAuth::fromUser($admin);

        return response()->json([
            'status' => 'success',
            'message' => 'Admin registered successfully',
            'admin' => $admin,
            'authorization' => [
                'token' => $token,
                'type' => 'bearer',
                'expires_in' => config('jwt.ttl') * 60
            ]
        ], 201);
    }

    /**
     * Admin login.
     */
    public function login(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $credentials = $request->only('email', 'password');

        if (!$token = Auth::guard('admin')->attempt($credentials)) {
            return response()->json([
                'status' => 'error',
                'message' => 'Invalid credentials'
            ], 401);
        }

        $admin = Auth::guard('admin')->user();

        // Check if admin is active
        if (!$admin->isActive()) {
            Auth::guard('admin')->logout();
            return response()->json([
                'status' => 'error',
                'message' => 'Account is deactivated'
            ], 403);
        }

        // Update last login
        $admin->updateLastLogin();

        return response()->json([
            'status' => 'success',
            'message' => 'Login successful',
            'admin' => $admin,
            'authorization' => [
                'token' => $token,
                'type' => 'bearer',
                'expires_in' => config('jwt.ttl') * 60
            ]
        ]);
    }

    /**
     * Get authenticated admin profile.
     */
    public function profile(): JsonResponse
    {
        return response()->json([
            'status' => 'success',
            'admin' => Auth::guard('admin')->user()
        ]);
    }

    /**
     * Update admin profile.
     */
    public function updateProfile(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'name' => 'sometimes|string|max:255',
            'email' => 'sometimes|email|unique:admins,email,' . Auth::guard('admin')->id(),
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $admin = Auth::guard('admin')->user();
        $admin->update($request->only(['name', 'email']));

        return response()->json([
            'status' => 'success',
            'message' => 'Profile updated successfully',
            'admin' => $admin->fresh()
        ]);
    }

    /**
     * Change admin password.
     */
    public function changePassword(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'current_password' => 'required|string',
            'new_password' => 'required|string|min:8|confirmed',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $admin = Auth::guard('admin')->user();

        if (!Hash::check($request->current_password, $admin->password)) {
            return response()->json([
                'status' => 'error',
                'message' => 'Current password is incorrect'
            ], 422);
        }

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

        return response()->json([
            'status' => 'success',
            'message' => 'Password changed successfully'
        ]);
    }

    /**
     * Refresh JWT token.
     */
    public function refresh(): JsonResponse
    {
        try {
            $token = Auth::guard('admin')->refresh();

            return response()->json([
                'status' => 'success',
                'authorization' => [
                    'token' => $token,
                    'type' => 'bearer',
                    'expires_in' => config('jwt.ttl') * 60
                ]
            ]);
        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Token refresh failed'
            ], 401);
        }
    }

    /**
     * Admin logout.
     */
    public function logout(): JsonResponse
    {
        Auth::guard('admin')->logout();

        return response()->json([
            'status' => 'success',
            'message' => 'Successfully logged out'
        ]);
    }
}
