<?php

namespace App\Http\Controllers\Epelcon;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class StaffController extends Controller
{
    public function index(Request $request)
    {
        $staff = User::whereIn('role', array_keys(User::STAFF_ROLES))
            ->when(\App\Support\Tenancy::check(), fn ($q) => $q->where('hotel_id', \App\Support\Tenancy::id()))
            ->when($request->filled('role'), fn ($q) => $q->where('role', $request->role))
            ->when($request->filled('q'), fn ($q) => $q->where(fn ($w) => $w->where('name', 'like', '%' . $request->q . '%')->orWhere('email', 'like', '%' . $request->q . '%')))
            ->orderBy('name')
            ->paginate(20)->withQueryString();

        $roleCounts = User::whereIn('role', array_keys(User::STAFF_ROLES))
            ->when(\App\Support\Tenancy::check(), fn ($q) => $q->where('hotel_id', \App\Support\Tenancy::id()))
            ->selectRaw('role, COUNT(*) as cnt')->groupBy('role')->pluck('cnt', 'role');

        return view('epelcon.staff.index', compact('staff', 'roleCounts'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|max:120',
            'email' => 'required|email|max:120|unique:users,email',
            'phone' => 'nullable|string|max:40',
            'role' => 'required|in:' . implode(',', array_keys(User::STAFF_ROLES)),
            'department' => 'nullable|string|max:60',
            'password' => 'required|string|min:8',
        ]);

        $data['password'] = Hash::make($data['password']);
        $data['status'] = 'active';
        $data['referral_code'] = strtoupper(Str::random(8));
        $data['hotel_id'] = \App\Support\Tenancy::id();

        $user = User::create($data);
        ActivityLog::record('created staff account', 'staff', "{$user->name} ({$user->roleLabel()})");

        return back()->with('success', "Staff account for {$user->name} created.");
    }

    public function update(Request $request, User $user)
    {
        $data = $request->validate([
            'name' => 'required|string|max:120',
            'email' => 'required|email|max:120|unique:users,email,' . $user->id,
            'phone' => 'nullable|string|max:40',
            'role' => 'required|in:' . implode(',', array_keys(User::STAFF_ROLES)),
            'department' => 'nullable|string|max:60',
            'password' => 'nullable|string|min:8',
        ]);

        if (! empty($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        } else {
            unset($data['password']);
        }

        $user->update($data);
        ActivityLog::record('updated staff account', 'staff', $user->name);

        return back()->with('success', 'Staff account updated.');
    }

    public function toggle(User $user)
    {
        if ($user->id === auth()->id()) {
            return back()->with('error', 'You cannot suspend your own account.');
        }

        $user->update(['status' => $user->status === 'active' ? 'suspended' : 'active']);
        ActivityLog::record($user->status === 'active' ? 'reactivated account' : 'suspended account', 'security', $user->name);

        return back()->with('success', "{$user->name} is now {$user->status}.");
    }

    public function security(Request $request)
    {
        $logs = ActivityLog::with('user')
            ->when($request->filled('module'), fn ($q) => $q->where('module', $request->module))
            ->when($request->filled('user'), fn ($q) => $q->where('user_id', $request->user))
            ->latest()
            ->paginate(30)->withQueryString();

        $users = User::whereIn('role', array_keys(User::STAFF_ROLES))->orderBy('name')->get(['id', 'name']);
        $modules = ActivityLog::whereNotNull('module')->distinct()->pluck('module');

        return view('epelcon.staff.security', compact('logs', 'users', 'modules'));
    }

    public function settings()
    {
        $settings = [
            'hotel_name' => Setting::get('hotel_name', 'Epelcon Hospitality'),
            'currency' => Setting::get('currency', '₦'),
            'tax_percent' => Setting::get('tax_percent', '0'),
            'address' => Setting::get('address', ''),
            'phone' => Setting::get('phone', ''),
            'email' => Setting::get('email', ''),
            'checkin_time' => Setting::get('checkin_time', '14:00'),
            'checkout_time' => Setting::get('checkout_time', '12:00'),
            'referral_points' => Setting::get('referral_points', '50'),
        ];

        return view('epelcon.staff.settings', compact('settings'));
    }

    public function saveSettings(Request $request)
    {
        foreach (['hotel_name', 'currency', 'tax_percent', 'address', 'phone', 'email', 'checkin_time', 'checkout_time', 'referral_points'] as $key) {
            if ($request->has($key)) {
                Setting::put($key, (string) $request->input($key));
            }
        }

        ActivityLog::record('updated settings', 'settings');

        return back()->with('success', 'Settings saved.');
    }
}
