<?php
/**
 * Copyright (c) Since 2024 InnoShop - All Rights Reserved
 *
 * @link       https://www.innoshop.com
 * @author     InnoShop <team@innoshop.com>
 * @license    https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
 */

namespace InnoShop\Front\Controllers\Account;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use InnoShop\Common\Models\Address;
use InnoShop\Common\Repositories\AddressRepo;
use InnoShop\Common\Resources\AddressListItem;

class AddressesController extends Controller
{
    /**
     * @return mixed
     */
    public function index(): mixed
    {
        $filters = [
            'customer_id' => current_customer_id(),
        ];
        $items     = AddressRepo::getInstance()->builder($filters)->get();
        $addresses = (AddressListItem::collection($items))->jsonSerialize();

        $data = [
            'addresses' => $addresses,
        ];

        return inno_view('account.addresses', $data);
    }

    /**
     * @param  Request  $request
     * @return mixed
     * @throws \Throwable
     */
    public function store(Request $request): mixed
    {
        $data                = $request->all();
        $data['customer_id'] = current_customer_id();

        $address = AddressRepo::getInstance()->create($data);
        $result  = new AddressListItem($address);

        return json_success('success', $result);
    }

    /**
     * @param  Request  $request
     * @param  Address  $address
     * @return mixed
     */
    public function update(Request $request, Address $address): mixed
    {
        $data                = $request->all();
        $data['customer_id'] = current_customer_id();

        $address = AddressRepo::getInstance()->update($address, $data);
        $result  = new AddressListItem($address);

        return json_success('success', $result);
    }

    /**
     * @param  Address  $address
     * @return mixed
     */
    public function destroy(Address $address): mixed
    {
        $address->delete();

        return json_success('success');
    }
}
