<?php

namespace TPS\Shop\Http\Controllers;

use TPS\Shop\Http\Requests\CustomerAddressRequest;
use Webkul\Customer\Http\Controllers\Controller;
use Webkul\Customer\Repositories\CustomerAddressRepository;

class AddressController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @param  \Webkul\Customer\Repositories\CustomerAddressRepository  $customerAddressRepository
     * @return void
     */
    public function __construct(protected CustomerAddressRepository $customerAddressRepository)
    {
        $this->_config = request('_config');

        $this->customer = auth()->guard('customer')->user();
    }

    /**
     * Create a new address for customer.
     *
     * @return view
     */
    public function store(CustomerAddressRequest $request)
    {
        $data = $request->all();

        $data['customer_id'] = $this->customer->id;
        $data['address1'] = implode(PHP_EOL, array_filter(request()->input('address1')));

        if ($this->customer->addresses->count() == 0) {
            $data['default_address'] = 1;
        }

        if ($this->customerAddressRepository->create($data)) {
            session()->flash('success', trans('shop::app.customer.account.address.create.success'));

            return redirect()->route($this->_config['redirect']);
        }

        session()->flash('error', trans('shop::app.customer.account.address.create.error'));

        return redirect()->back();
    }
}