<?php

namespace App\Http\Controllers\Backend;

use App\DataTables\Users\UserDataTable;
use App\DataTables\Users\UserDataTableEditor;
use App\Http\Controllers\Controller;
use App\Models\UserManagement\Customer;
use App\Models\UserManagement\User;
use App\Models\UserManagement\UserType;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;


class UserController extends Controller{

    public function __construct(){

        $this->middleware('permission:user-list')
            ->only(["index"]);

        $this->middleware(['permission:user-show','permission:customer-show'])
            ->only(["show"]);

        $this->middleware('permission:user-create')
            ->only(['create',"dtEdit"]);

        $this->middleware('permission:user-update')
            ->only(['update',"dtEdit"]);

        $this->middleware('permission:user-delete')
            ->only(['delete',"deleteMany","dtEdit"]);

    }

    public function index(Request $request ){

        $userType = $request->userType ?? UserType::ADMIN;

        if (request()->ajax() and request()->boolean("no_dt")){
            return Customer::with([
                            "addresses" => fn ($query) => $query->select("title")
                        ])
                      //  ->where("user_type_code",$userType)
                        ->active()
                        ->get()
                        ->map->only(['id',"first_name","last_name","full_name","avatar","email","phone","status","username","full_default","balance"]);
        }

        $type = ($userType == UserType::ADMIN) ? __("Users") : __("Customers");
        $dataTable = new UserDataTable($userType);
        $title = __("Manage :type",['type' => $type]);
        return $dataTable->render('backend.users.dt-index',compact("title"));
    }

    public function show(User $user): View{
        return view('backend.users.show', compact('user'));
    }

    public function dtEdit(UserDataTableEditor $editor){
        return $editor->process(request());
    }
}
