<?php
// app/Http/Controllers/Api/Admin/UserController.php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Traits\ApiResponse;
use App\Models\User;
use App\Http\Requests\Api\Admin\UserRequest;
use App\Http\Resources\Api\UserResource;
use App\Http\Resources\Api\UserCollection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;

class UserController extends Controller
{
    use ApiResponse;

    /**
     * Display a listing of users.
     */
    public function index(Request $request)
    {
            try {
        $users = User::paginate(20);
        
        // BYPASS RESOURCE, return array langsung
        $data = [
            'data' => $users->map(function ($user) {
                return [
                    'id' => $user->id ?? $user->getKey(),
                    'name' => $user->name,
                    'email' => $user->email,
                    'phone' => $user->phone,
                    'role' => $user->role,
                    'created_at' => $user->created_at,
                ];
            }),
            'meta' => [
                'current_page' => $users->currentPage(),
                'last_page' => $users->lastPage(),
                'per_page' => $users->perPage(),
                'total' => $users->total(),
            ]
        ];
        
        return response()->json([
            'success' => true,
            'message' => 'Users retrieved',
            'data' => $data
        ]);
        
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ], 500);
    }
    }

    /**
     * Display the specified user.
     */
    public function show($id)
    {
        try {
            $user = User::find($id);

            if (!$user) {
                return $this->errorResponse('User not found', 404);
            }

            return $this->successResponse(
                new UserResource($user),
                'User retrieved successfully'
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to retrieve user', 500, $e->getMessage());
        }
    }

    /**
     * Store a newly created user.
     */
    public function store(UserRequest $request)
    {
        try {
            $data = $request->validated();
            
            // Hash password
            $data['password'] = Hash::make($data['password']);
            
            // Auto verify for admin-created users
            $data['email_verified_at'] = now();
            
            $user = User::create($data);

            return $this->successResponse(
                new UserResource($user),
                'User created successfully',
                201
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to create user: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Update the specified user.
     */
    public function update(UserRequest $request, $id)
    {
        try {
            $user = User::find($id);

            if (!$user) {
                return $this->errorResponse('User not found', 404);
            }

            $data = $request->validated();
            
            // Update password only if provided
            if (isset($data['password']) && !empty($data['password'])) {
                $data['password'] = Hash::make($data['password']);
            } else {
                unset($data['password']);
            }

            $user->update($data);

            return $this->successResponse(
                new UserResource($user->fresh()),
                'User updated successfully'
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to update user: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Remove the specified user.
     */
    public function destroy($id)
    {
        try {
            $user = User::find($id);

            if (!$user) {
                return $this->errorResponse('User not found', 404);
            }

            // Cannot delete yourself
            if ($user->id === \Illuminate\Support\Facades\Auth::id()) {
                return $this->errorResponse('You cannot delete your own account', 400);
            }

            // Check for dependencies
            $hasOrders = $user->orders()->exists();
            $hasAssignedOrders = $user->assignedOrders()->exists();
            $hasPayments = $user->confirmedPayments()->exists();
            $hasReviews = $user->reviews()->exists();

            if ($hasOrders || $hasAssignedOrders || $hasPayments || $hasReviews) {
                return $this->errorResponse(
                    'Cannot delete user because they have associated records',
                    400,
                    [
                        'has_orders' => $hasOrders,
                        'has_assigned_orders' => $hasAssignedOrders,
                        'has_payments' => $hasPayments,
                        'has_reviews' => $hasReviews,
                    ]
                );
            }

            $user->delete();

            return $this->successResponse(
                null,
                'User deleted successfully'
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to delete user: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Toggle user verification status.
     */
    public function toggleStatus($id)
    {
        try {
            $user = User::find($id);

            if (!$user) {
                return $this->errorResponse('User not found', 404);
            }

            // Cannot change your own status
            if ($user->id === \Illuminate\Support\Facades\Auth::id()) {
                return $this->errorResponse('You cannot change your own status', 400);
            }

            $newStatus = $user->email_verified_at ? null : now();
            $user->update(['email_verified_at' => $newStatus]);

            return $this->successResponse([
                'user' => new UserResource($user),
                'status' => $newStatus ? 'verified' : 'unverified',
                'message' => 'User status updated successfully'
            ]);
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to update user status: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Get user statistics.
     */
    public function statistics()
    {
        try {
            $totalUsers = User::count();
            
            $roles = ['customer', 'employee', 'admin'];
            $byRole = [];
            
            foreach ($roles as $role) {
                $byRole[$role] = User::where('role', $role)->count();
            }

            $verifiedUsers = User::whereNotNull('email_verified_at')->count();
            $unverifiedUsers = $totalUsers - $verifiedUsers;
            
            // Recent users (last 30 days)
            $recentUsers = User::where('created_at', '>=', Carbon::now()->subDays(30))
                ->count();

            // Monthly growth
            $currentMonthStart = Carbon::now()->startOfMonth();
            $lastMonthStart = Carbon::now()->subMonth()->startOfMonth();
            $lastMonthEnd = Carbon::now()->subMonth()->endOfMonth();
            
            $currentMonthUsers = User::where('created_at', '>=', $currentMonthStart)->count();
            $lastMonthUsers = User::whereBetween('created_at', [$lastMonthStart, $lastMonthEnd])->count();
            
            $growthRate = $lastMonthUsers > 0 
                ? round((($currentMonthUsers - $lastMonthUsers) / $lastMonthUsers) * 100, 2)
                : ($currentMonthUsers > 0 ? 100 : 0);

            // Top active users (with most orders)
            $topCustomers = User::withCount(['orders' => function ($query) {
                $query->where('status', 'completed');
            }])
            ->where('role', 'customer')
            ->orderBy('orders_count', 'desc')
            ->limit(5)
            ->get()
            ->map(function ($user) {
                return [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'orders_count' => $user->orders_count,
                    'last_order' => $user->orders()->latest()->first()->created_at ?? null,
                ];
            });

            return $this->successResponse([
                'total' => $totalUsers,
                'by_role' => $byRole,
                'verification_status' => [
                    'verified' => $verifiedUsers,
                    'unverified' => $unverifiedUsers,
                    'percentage' => $totalUsers > 0 ? round(($verifiedUsers / $totalUsers) * 100, 2) : 0
                ],
                'growth' => [
                    'recent_30_days' => $recentUsers,
                    'monthly_growth_rate' => $growthRate,
                    'current_month' => $currentMonthUsers,
                    'last_month' => $lastMonthUsers
                ],
                'top_customers' => $topCustomers
            ], 'User statistics retrieved successfully');
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to retrieve user statistics: ' . $e->getMessage(), 500);
        }
    }
}