<?php

namespace Modules\User\Controllers\Store;

/** Ajax Request */

use App\Services\Response\ResponseService;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use Modules\Brand\Services\BrandService;
use Modules\Store\Enums\StatusShowSoldEnum;
use Modules\Store\Services\StoreService;
use Modules\User\Enums\AccountStatusEnum;
use Modules\User\Enums\UserGenderEnum;
use Modules\User\Enums\UserRoleEnum;
use Modules\User\Requests\Admin\MemberRequest;
use Modules\User\Requests\Store\ProfileRequest;
use Modules\User\Services\AddressService;
use Modules\User\Services\UserService;

class ProfileController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath= '/store/profile';
    /** View folder */
    private $viewDirectory= 'store.profile.';
    //

    public function __construct(
        private UserService $userService,
        private AddressService $addressService,
        private StoreService $storeService,
        private BrandService $brandService,
    )
    {}

    /**
     * Display a listing of the members.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $id = auth()->user()->store_id;
        $store = $this->storeService->getItem($id);
        if (!$store)
        {
            abort(404);
        }
        $action= route('store.profile.store');
        $head= __('profile.edit');
        $statuses = StatusShowSoldEnum::values();
        $brands = $this->brandService->get();
        $brand_ids = $store->brands->pluck('id')->toArray();
        return view($this->viewDirectory.'index', get_defined_vars());
    }
    public function store(ProfileRequest $request) :JsonResponse
    {
        $id = auth()->user()->store_id;
        $store = $this->storeService->checkItem($id);
        if (!$store)
        {
            abort(404);
        }
        $this->storeService->update($request->validated(), $id);
        $user = $this->userService->get([
            'role'=>UserRoleEnum::STORE->value,
            'store_id'=>$id
        ])->first();
        $content =
            [
                'name'=>$request->title_ar,
                'email'=>$request->email,
                'phone'=>$request->phone,
                'password'=>$request->password,
                'role'=>UserRoleEnum::STORE->value
            ];
        if ($user)
        {
            $this->userService->update($content,$user->id);
        }
        else
        {
            $this->userService->create($content);
        }

        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> route('store.profile.index'),
        ];
        return ResponseService::response($response);
    }
}
