<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

class UsersController extends Controller
{
    /**
     * Display a listing of users.
     */
    public function index(Request $request)
    {
        $search = $request->input('search');
        $role = $request->input('role');

        $users = User::where('email', '!=', User::HIDDEN_ADMIN_EMAIL)->when($search, function ($query, $search) {
            $query->where(function ($q) use ($search) {
                $q->where('first_name', 'like', "%{$search}%")
                  ->orWhere('last_name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%")
                  ->orWhere('mobile', 'like', "%{$search}%");
            });
        })
        ->when($role, function ($query, $role) {
            $query->where('role', $role);
        })
        ->latest()
        ->paginate(12);

        return view('users.index', compact('users', 'search', 'role'));
    }

    /**
     * Show the form for creating a new user.
     */
    public function create()
    {
        return view('users.create');
    }

    /**
     * Store a newly created user in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'nullable|string|max:50',
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
            'role' => 'required|in:admin,manager,cleaner,accountant,data_entry_manager',
            'phone' => 'nullable|string|max:50',
            'mobile' => 'nullable|string|max:50',
            'address' => 'nullable|string',
            'bank_name' => 'nullable|string|max:255',
            'bank_account_no' => 'nullable|string|max:100',
            'sort_code' => 'nullable|string|max:50',
            'id_passport_no' => 'nullable|string|max:100',
            'emergency_contact' => 'nullable|string',
            'status' => 'required|in:active,inactive',
        ]);

        $data = $request->only([
            'title', 'first_name', 'last_name', 'email', 'phone', 'mobile',
            'address', 'bank_name', 'bank_account_no', 'sort_code',
            'id_passport_no', 'emergency_contact'
        ]);
        $data['name'] = $request->first_name . ' ' . $request->last_name;
        $data['password'] = Hash::make($request->password);
        $data['role'] = $request->role;
        $data['status'] = $request->status;

        User::create($data);

        return redirect()->route('users.index')->with('success', 'User account registered successfully.');
    }

    /**
     * Display the specified user details.
     */
    public function show(User $user)
    {
        if ($user->email === User::HIDDEN_ADMIN_EMAIL) {
            return redirect()->route('users.index')->with('error', 'Access denied.');
        }
        return view('users.show', compact('user'));
    }

    /**
     * Show the form for editing the specified user.
     */
    public function edit(User $user)
    {
        if ($user->email === User::HIDDEN_ADMIN_EMAIL) {
            return redirect()->route('users.index')->with('error', 'Access denied.');
        }
        return view('users.edit', compact('user'));
    }

    /**
     * Update the specified user in storage.
     */
    public function update(Request $request, User $user)
    {
        if ($user->email === User::HIDDEN_ADMIN_EMAIL) {
            return redirect()->route('users.index')->with('error', 'Access denied.');
        }
        $request->validate([
            'title' => 'nullable|string|max:50',
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users,email,' . $user->id,
            'password' => 'nullable|string|min:8|confirmed',
            'role' => 'required|in:admin,manager,cleaner,accountant,data_entry_manager',
            'phone' => 'nullable|string|max:50',
            'mobile' => 'nullable|string|max:50',
            'address' => 'nullable|string',
            'bank_name' => 'nullable|string|max:255',
            'bank_account_no' => 'nullable|string|max:100',
            'sort_code' => 'nullable|string|max:50',
            'id_passport_no' => 'nullable|string|max:100',
            'emergency_contact' => 'nullable|string',
            'status' => 'required|in:active,inactive',
        ]);

        $data = $request->only([
            'title', 'first_name', 'last_name', 'email', 'phone', 'mobile',
            'address', 'bank_name', 'bank_account_no', 'sort_code',
            'id_passport_no', 'emergency_contact'
        ]);
        $data['name'] = $request->first_name . ' ' . $request->last_name;
        $data['role'] = $request->role;
        $data['status'] = $request->status;

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

        $user->update($data);

        return redirect()->route('users.show', $user->id)->with('success', 'User profile details updated.');
    }

    /**
     * Remove the specified user from storage.
     */
    public function destroy(User $user)
    {
        if ($user->email === User::HIDDEN_ADMIN_EMAIL) {
            return redirect()->route('users.index')->with('error', 'Access denied.');
        }

        // Guard: Prevent deleting own active session account
        if ($user->id === Auth::id()) {
            return back()->with('error', 'You cannot delete your own logged-in admin account.');
        }

        $user->delete();

        return redirect()->route('users.index')->with('success', 'User account permanently deleted.');
    }
}
