<?php

namespace App\Http\Controllers\API\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\DeliveryBoy;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class UserManagementController extends Controller
{
    public function index(Request $request)
    {
        try {
            $query = User::with('roles');
            
            if ($request->role) {
                $query->role($request->role);
            }
            
            if ($request->restaurant_id) {
                $query->whereHas('restaurant', function($q) use ($request) {
                    $q->where('id', $request->restaurant_id);
                });
            }
            
            if ($request->status) {
                $query->where('status', $request->status);
            }
            
            if ($request->search) {
                $query->where(function($q) use ($request) {
                    $q->where('name', 'like', '%' . $request->search . '%')
                      ->orWhere('email', 'like', '%' . $request->search . '%')
                      ->orWhere('phone', 'like', '%' . $request->search . '%');
                });
            }
            
            $users = $query->latest()->paginate($request->per_page ?? 20);
            
            return response()->json([
                'success' => true,
                'data' => $users
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function store(Request $request)
    {
        try {
            $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'required|email|unique:users,email',
                'phone' => 'required|string|unique:users,phone',
                'password' => 'required|min:6',
                'role' => 'required|exists:roles,name',
                'address' => 'nullable|string'
            ]);
            
            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'phone' => $request->phone,
                'password' => Hash::make($request->password),
                'address' => $request->address,
                'email_verified_at' => now()
            ]);
            
            $user->assignRole($request->role);
            
            return response()->json([
                'success' => true,
                'message' => 'User created successfully',
                'data' => $user->load('roles')
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function show($id)
    {
        try {
            $user = User::with(['roles', 'permissions'])->findOrFail($id);
            
            return response()->json([
                'success' => true,
                'data' => $user
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'User not found'
            ], 404);
        }
    }

    public function update(Request $request, $id)
    {
        try {
            $user = User::findOrFail($id);
            
            $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'required|email|unique:users,email,' . $id,
                'phone' => 'required|string|unique:users,phone,' . $id,
                'address' => 'nullable|string'
            ]);
            
            $user->update([
                'name' => $request->name,
                'email' => $request->email,
                'phone' => $request->phone,
                'address' => $request->address
            ]);
            
            if ($request->role) {
                $user->syncRoles([$request->role]);
            }
            
            return response()->json([
                'success' => true,
                'message' => 'User updated successfully',
                'data' => $user->load('roles')
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function destroy($id)
    {
        try {
            $user = User::findOrFail($id);
            $user->delete();
            
            return response()->json([
                'success' => true,
                'message' => 'User deleted successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function block($id)
    {
        try {
            $user = User::findOrFail($id);
            $user->update(['status' => 'blocked']);
            
            return response()->json([
                'success' => true,
                'message' => 'User blocked successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function unblock($id)
    {
        try {
            $user = User::findOrFail($id);
            $user->update(['status' => 'active']);
            
            return response()->json([
                'success' => true,
                'message' => 'User unblocked successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function resetPassword(Request $request, $id)
    {
        try {
            $request->validate([
                'password' => 'required|min:6|confirmed'
            ]);
            
            $user = User::findOrFail($id);
            $user->update(['password' => Hash::make($request->password)]);
            
            return response()->json([
                'success' => true,
                'message' => 'Password reset successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function getRoles()
    {
        try {
            $roles = Role::all();
            
            return response()->json([
                'success' => true,
                'data' => $roles
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function getPermissions()
    {
        try {
            $permissions = Permission::all();
            
            return response()->json([
                'success' => true,
                'data' => $permissions
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function assignPermissions(Request $request, $id)
    {
        try {
            $user = User::findOrFail($id);
            $user->syncPermissions($request->permissions);
            
            return response()->json([
                'success' => true,
                'message' => 'Permissions assigned successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function getDashboardStats()
    {
        try {
            $stats = [
                'total_users' => User::count(),
                'customers' => User::role('customer')->count(),
                'admins' => User::role('admin')->count(),
                'delivery_boys' => User::role('delivery-boy')->count(),
                'managers' => User::role('manager')->count(),
                'blocked_users' => User::where('status', 'blocked')->count(),
                'active_users' => User::where('status', 'active')->count(),
                'verified_users' => User::whereNotNull('email_verified_at')->count()
            ];
            
            return response()->json([
                'success' => true,
                'data' => $stats
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function exportUsers(Request $request)
    {
        try {
            $query = User::with('roles');
            
            if ($request->role) {
                $query->role($request->role);
            }
            
            $users = $query->get();
            
            $filename = 'users_' . date('Y-m-d_His') . '.xls';
            
            $headers = [
                'Content-Type' => 'application/vnd.ms-excel',
                'Content-Disposition' => 'attachment; filename="' . $filename . '"',
                'Cache-Control' => 'max-age=0',
            ];
            
            $callback = function() use ($users) {
                echo "<html><head><meta charset='utf-8'></head><body><table border='1'>";
                echo "<tr style='background-color: #ff6b35; color: white; font-weight: bold;'>";
                echo "<th>ID</th><th>Name</th><th>Email</th><th>Phone</th><th>Role</th><th>Status</th><th>Created</th>";
                echo "</tr>";
                
                foreach ($users as $user) {
                    echo "<tr>";
                    echo "<td>" . $user->id . "</td>";
                    echo "<td>" . htmlspecialchars($user->name) . "</td>";
                    echo "<td>" . htmlspecialchars($user->email) . "</td>";
                    echo "<td>" . htmlspecialchars($user->phone) . "</td>";
                    echo "<td>" . htmlspecialchars($user->roles->pluck('name')->implode(', ')) . "</td>";
                    echo "<td>" . htmlspecialchars($user->status ?? 'active') . "</td>";
                    echo "<td>" . $user->created_at->format('Y-m-d H:i:s') . "</td>";
                    echo "</tr>";
                }
                
                echo "</table></body></html>";
            };
            
            return response()->stream($callback, 200, $headers);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }
}
