<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\UserAddressRequest;
use App\Models\LocalizationManagement\Country;
use App\Models\LocalizationManagement\Address;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;

class UserAddressController extends Controller{

    public function __construct(){

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

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

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

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

        $this->middleware('permission:user-address-delete')
            ->only(['destroy']);

    }

    public function index(): View{
        $userAddresses = Address::with(['user', 'country', 'state', 'city'])
            ->when(request()->filled("keyword"), fn ($query) => $query->search(request()->keyword))
            ->when(request()->filled("active"), fn ($query) => $query->whereActive(request()->active))
            ->orderBy(request()->sortBy ?? 'id', request()->orderBy ?? 'desc')
            ->paginate(request()->limitBy ?? 10);
        return view('backend.user_addresses.index', compact('userAddresses'));
    }

    public function create(): View{
        $countries = Country::active()->get(['id', 'name']);
        return view('backend.user_addresses.create', compact('countries'));
    }

    public function store(UserAddressRequest $request): RedirectResponse{
        Address::create($request->validated());

        return redirect()->route('admin.user_addresses.index')->with([
            'message' => action_message("create"),
            'alert-type' => 'success'
        ]);
    }

    public function show(Address $userAddress): View{
        return view('backend.user_addresses.show', compact('userAddress'));
    }

    public function edit(Address $userAddress): View{
        $countries = Country::active()->get(['id', 'name']);

        return view('backend.user_addresses.edit', compact('userAddress', 'countries'));
    }

    public function update(UserAddressRequest $request, Address $userAddress): RedirectResponse{
        $userAddress->update($request->validated());

        return redirect()->route('admin.user_addresses.index')->with([
            'message' => action_message("update"),
            'alert-type' => 'success'
        ]);
    }

    public function destroy(UserAddress $userAddress): RedirectResponse{
        $userAddress->delete();

        return redirect()->route('admin.user_addresses.index')->with([
            'message' => action_message("delete"),
            'alert-type' => 'success'
        ]);
    }
}
