<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rules\Password;

class SuperAdminUserController extends Controller
{
    public function userDetails()
    {
        return view('superadmin.users.userdetails');
    }

    public function list()
    {
        // Check if status column exists and use it if available
        $hasStatusColumn = \Schema::hasColumn('users', 'status');

        $query = User::select('id', 'name', 'email', 'role', 'created_at', 'updated_at');

        if ($hasStatusColumn) {
            $query->addSelect('status');
        }

        $users = $query->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($user) use ($hasStatusColumn) {
                return [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'role' => $user->role,
                    'status' => $hasStatusColumn ? ($user->status ?? 'active') : 'active',
                    'created_at' => $user->created_at ? $user->created_at->format('d-m-Y H:i') : '-',
                    'updated_at' => $user->updated_at ? $user->updated_at->format('d-m-Y H:i') : '-',
                ];
            })
            ->values()
            ->toArray();

        return response()->json(['data' => $users]);
    }

    public function store(Request $request)
    {
        $hasStatusColumn = \Schema::hasColumn('users', 'status');

        $rules = [
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255|unique:users,email',
            'password' => ['required', 'string', 'min:8'],
            'role' => 'required|in:superadmin,admin,manager',
        ];

        if ($hasStatusColumn) {
            $rules['status'] = 'nullable|in:active,inactive';
        }

        $validated = $request->validate($rules, [
            'name.required' => 'Name is required.',
            'email.required' => 'Email is required.',
            'email.unique' => 'This email is already registered.',
            'password.required' => 'Password is required.',
            'password.min' => 'Password must be at least 8 characters.',
            'role.required' => 'Please select a role.',
        ]);

        $userData = [
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => $request->role,
        ];

        if ($hasStatusColumn) {
            $userData['status'] = $request->status ?? 'active';
        }

        $user = User::create($userData);

        return response()->json([
            'success' => true,
            'message' => 'User created successfully!'
        ]);
    }

    public function show(User $user)
    {
        return response()->json([
            'success' => true,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'role' => $user->role,
                'status' => $user->status ?? 'active',
            ]
        ]);
    }

    public function update(Request $request, User $user)
    {
        $hasStatusColumn = \Schema::hasColumn('users', 'status');

        $rules = [
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255|unique:users,email,' . $user->id,
            'role' => 'required|in:superadmin,admin,manager',
            'password' => ['nullable', 'string', 'min:8'],
        ];

        if ($hasStatusColumn) {
            $rules['status'] = 'nullable|in:active,inactive';
        }

        $validated = $request->validate($rules, [
            'name.required' => 'Name is required.',
            'email.required' => 'Email is required.',
            'email.unique' => 'This email is already registered.',
            'password.min' => 'Password must be at least 8 characters.',
            'role.required' => 'Please select a role.',
        ]);

        // Prevent demoting yourself if you're the last superadmin
        if ($user->id === Auth::id() && $user->role === 'superadmin' && $request->role !== 'superadmin') {
            $superadminCount = User::where('role', 'superadmin')->count();
            if ($superadminCount <= 1) {
                return response()->json([
                    'success' => false,
                    'message' => 'Cannot change role. You are the only Super Admin!'
                ], 422);
            }
        }

        $user->name = $request->name;
        $user->email = $request->email;
        $user->role = $request->role;

        if ($hasStatusColumn) {
            $user->status = $request->status ?? $user->status ?? 'active';
        }

        if ($request->filled('password')) {
            $user->password = Hash::make($request->password);
        }

        $user->save();

        return response()->json([
            'success' => true,
            'message' => 'User updated successfully!'
        ]);
    }

    public function delete(User $user)
    {
        // Prevent self-deletion
        if ($user->id === Auth::id()) {
            return response()->json([
                'success' => false,
                'message' => 'You cannot delete your own account!'
            ], 422);
        }

        // Prevent deletion of last superadmin
        if ($user->role === 'superadmin') {
            $superadminCount = User::where('role', 'superadmin')->count();
            if ($superadminCount <= 1) {
                return response()->json([
                    'success' => false,
                    'message' => 'Cannot delete the last Super Admin!'
                ], 422);
            }
        }

        $user->delete();

        return response()->json([
            'success' => true,
            'message' => 'User deleted successfully!'
        ]);
    }

    public function toggleStatus(User $user)
    {
        $hasStatusColumn = \Schema::hasColumn('users', 'status');

        if (!$hasStatusColumn) {
            return response()->json([
                'success' => false,
                'message' => 'Status feature is not available. Please run migrations.'
            ], 422);
        }

        // Prevent deactivating yourself
        if ($user->id === Auth::id()) {
            return response()->json([
                'success' => false,
                'message' => 'You cannot deactivate your own account!'
            ], 422);
        }

        $user->status = $user->status === 'active' ? 'inactive' : 'active';
        $user->save();

        return response()->json([
            'success' => true,
            'message' => 'User status updated to ' . ucfirst($user->status) . '!'
        ]);
    }
}
