<?php

namespace App\Repositories\Shop;

use App\Datatables\Shop\CustomerInvoicesDataTable;
use App\Datatables\Shop\CustomerOrdersDataTable;
use App\Models\Shop\Customer;
use App\Repositories\Core\File;
use App\Traits\Model\Basic;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Laravolt\Avatar\Avatar;

class Customers
{
    use Basic;

    public static function init()
    {
        return [
            'sale_channels' => SaleChannels::getOptions(),
        ];
    }

    public static function getSaleChannelIds($customerId = false)
    {
        $channels = self::getSaleChannels($customerId);

        return $channels ? $channels->pluck('id')->toArray() : false;
    }

    public static function getSaleChannels($customerId = false)
    {
        $customer = $customerId ? self::get($customerId) : self::getAuth();

        return $customer ? $customer->sale_channels : SaleChannels::getDefault();
    }

    public static function getSaleChannel()
    {
        return SaleChannels::getDefault();
    }

    public static function getDeliveries()
    {
        $customer = self::getAuth();

        return $customer ? $customer->deliveries : Deliveries::getDefault();
    }

    public static function getOptions()
    {
        return Customer::pluck('last_name', 'id');
    }

    public static function editProfile($id = false)
    {
        return $id ? [
            'customer' => self::get($id, ['addresses', 'deliveries'])->toArray(),
            'deliveries' => Deliveries::getAllWithSaleChannel()->toArray(),
            'orders' => (new CustomerOrdersDataTable())->html(),
            'invoices' => (new CustomerInvoicesDataTable())->html(),
        ] : abort('403');
    }

    public static function getAvatar($id = false)
    {
        $customer = $id ? self::get($id) : self::getAuth();
        $file = self::makeAvatarFilename($customer);
        if (!File::checkFile($file)) {
            self::createAvatar($customer);
        }

        return self::getPublic(self::getAvatarFilename($customer));
    }

    public static function createAvatar($customer)
    {
        $filename = self::makeAvatarFilename($customer);
        $name = $customer->first_name . ' ' . $customer->last_name;
        $avatar = new Avatar();

        return $avatar->create($name)
            ->setBackground('#F2B90F')
            ->setForeground('#335012')
            ->setBorder(1, '#28a745')
            ->setFontFamily('Roboto Condensed')
            ->setDimension(36)
            ->setFontSize(16)
            ->save($filename);
    }

    public static function makeAvatarFilename($customer)
    {
        $path = storage_path(self::getStorage());
        if (File::checkDirOrCreate($path)) {
            $filename = $path . self::getAvatarFilename($customer);
        }

        return $filename ?? false;
    }

    public static function getAvatarFilename($customer)
    {
        return 'user-' . $customer->uuid . '.png';
    }

    public static function getAddresses($id = false)
    {
        $customer = self::getWithAddresses($id);

        return $customer ? $customer->addresses : false;
    }

    public static function getWithAddresses($id = false)
    {
        $id = $id ? $id : self::getId();

        return self::get($id, ['invoice_addresses', 'delivery_addresses']);
    }

    public static function getName($id = false)
    {
        $user = $id ? self::get($id) : self::getAuth();

        return $user ? $user->name : '';
    }

    public static function getAuth()
    {
        return self::guard()->user();
    }

    public static function getId()
    {
        return self::guard()->id();
    }

    public static function isNotConnected()
    {
        return !self::isConnected();
    }

    public static function isConnected()
    {
        return self::guard()->check();
    }

    public static function edit($id)
    {
        if (!$id) {
            abort('403');
        }
        $customer = self::get($id, ['delivery_addresses', 'invoice_addresses', 'sale_channels']);
        $data = $customer->toArray();
        $data['sale_channels'] = $customer->sale_channels->pluck('id')->toArray();
        $data['deliveries'] = Deliveries::getBySaleChannels($data['sale_channels'])->toArray();

        return $data;
    }

    public static function storeFull($data)
    {
        $data2 = $data;
        if ($data['sale_channels'] ?? false) {
            $saleChannels = $data['sale_channels'] ?? false;
            unset($data['sale_channels']);
        }
        if ($data['deliveries'] ?? false) {
            unset($data['deliveries']);
        }
        if ($data['invoices'] ?? false) {
            unset($data['invoices']);
        }
        $customer = self::store($data);
        CustomerAddresses::storeByCustomer($customer, $data2);

        return $customer->id;
    }

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

        return $customer->deliveries()->sync($deliveries);
    }

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

    public static function storeSaleChannels($customerId, $saleChannels)
    {
        $oldSaleChannels = self::getSaleChannelIds($customerId);
        $deleteSaleChannels = array_diff($oldSaleChannels, $saleChannels);
        $newSaleChannels = array_diff($saleChannels, $oldSaleChannels);

        $data = ['customer_id' => $customerId];
        foreach ($newSaleChannels as $saleChannelId) {
            $data['sale_channel_id'] = $saleChannelId;
            CustomerSaleChannels::store($data);
        }
        foreach ($deleteSaleChannels as $saleChannelId) {
            CustomerSaleChannels::destroyByCustomerAndSaleChannel($customerId, $saleChannelId);
        }
    }

    public static function create($data)
    {
        $data['uuid'] = Str::uuid();
        $data['active'] = true;
        $data['password'] = bcrypt($data['password']);

        return Customer::create($data);
    }

    public static function getStorage($filename = false)
    {
        $path = '/app/public/Customers/';

        return $filename ? $path . $filename : $path;
    }

    public static function getPublic($filename = false)
    {
        $path = '/storage/Customers/';

        return $filename ? $path . $filename : $path;
    }

    public static function guard()
    {
        return Auth::guard('customer');
    }

    public static function getModel()
    {
        return Customer::query();
    }
}
