<?php

namespace App\Repositories\Shop;

use Illuminate\Support\Facades\Auth;


use App\Models\Shop\Customer;

class Customers
{

    public static function getAvatar()
    {

    }

    public static function getName()
    {
        $user = self::getAuth();
        return $user ? $user->first_name : '';
    }

    public static function getAuth()
    {
        return Auth::guard('customer')->user();
    }

    public static function getId()
    {
        return Auth::guard('customer')->id();
    }

    public static function isConnected()
    {
        return Auth::guard('customer')->check();
    }

    public static function getOptions()
    {
        return Customer::orderBy('value', 'asc')->get()->pluck('value', 'id')->toArray();
    }

    public static function getOptionsByPackage($package_id)
    {
        return Customer::byPackage($package_id)->orderBy('value', 'asc')->get()->pluck('value', 'id')->toArray();
    }

    public static function getAll()
    {
        return Customer::orderBy('value', 'asc')->get();
    }

    public static function get($id)
    {
        return Customer::find($id);
    }

    public static function edit($id)
    {
        $customer = Customer::with(['addresses'])->find($id);
        $data = $customer->toArray();
        $data['deliveries'] = $customer->deliveries->pluck('id')->toArray();
        return $data;
    }

    public static function storeFull($data)
    {
        $deliveries = $data['deliveries'];
        $addresses = $data['addresses'];
        unset($data['deliveries']);
        unset($data['addresses']);
        $customer = self::store($data);
        self::storeDeliveries($customer, $deliveries);
        self::storeAddresses($customer, $addresses);
        return $customer->id;
    }

    public static function store($data)
    {
        $id = $data['id'] ?? false;
        $item = $id ? self::update($data, $id) : self::create($data);
        return $item;
    }

    public static function storeDeliveries($customer, $deliveries)
    {
        if ($deliveries) {
            $deliveries = collect($deliveries)->transform(
                function ($item, $key) {
                    return (int) $item;
                }
            )->toArray();
            return $customer->deliveries()->sync($deliveries);
        } else {
            return false;
        }
    }

    public static function storeAddresses($customer, $addresses)
    {
        foreach ($addresses as $address) {
            $address['customer_id'] = $customer->id;
            CustomerAddresses::store($address);
        }
    }

    public static function create($data)
    {
        return Customer::create($data);
    }

    public static function update($data, $id = false)
    {
        $id = $id ? $id : $data['id'];
        $customer = self::get($id);
        $customer->update($data);
        return $customer;
    }

    public static function destroy($id)
    {
        return Customer::destroy($id);
    }
}
