<?php

/*
|--------------------------------------------------------------------------
| OwnStore - Build your own online store
| Author: TakfeDev (MKJUEL)
| All Rights Reserved
|--------------------------------------------------------------------------
*/

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Inertia\Inertia;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->query('search', '');

        // Fetch users with search and pagination
        $users = User::with('managedStore:id,name,company_name')
            ->when($search, function ($query, $search) {
                $query->where('name', 'like', "%{$search}%")
                      ->orWhere('email', 'like', "%{$search}%")
                      ->orWhere('username', 'like', "%{$search}%");
            })
            ->orderBy('created_at', 'desc')
            ->paginate(10)
            ->withQueryString();

        $stores = User::where('role', 'seller')
            ->orWhereNotNull('company_name')
            ->select('id', 'name', 'company_name')
            ->get();

        return Inertia::render('cp/Users/Index', [
            'users' => $users,
            'stores' => $stores,
            'filters' => ['search' => $search]
        ]);
    }

    public function updateRole(Request $request, User $user)
    {
        $request->validate([
            'role' => 'required|in:user,buyer,seller,manager,admin',
            'managed_store_id' => 'required_if:role,manager|nullable|exists:users,id'
        ]);

        // ---  Cast to integer ---
        if ((int) $user->id === (int) auth()->id()) {
            return back()->withErrors(['error' => 'You cannot change your own role.']);
        }

        $managedStoreId = $request->role === 'manager' ? $request->managed_store_id : null;
        $role = $request->role === 'buyer' ? 'user' : $request->role;

        $user->update([
            'role' => $role,
            'managed_store_id' => $managedStoreId
        ]);

        return back()->with('success', 'User role & permissions updated successfully.');
    }

    public function destroy(User $user)
    {
        // --- Cast to integer ---
        if ((int) $user->id === (int) auth()->id()) {
            return back()->withErrors(['error' => 'You cannot delete yourself.']);
        }
        $user->delete();
        return back()->with('success', 'User deleted successfully.');
    }
}