<?php

namespace App\Repositories\Shop;

use App\Models\Shop\CustomerAddress;
use App\Traits\Model\Basic;

class CustomerAddresses
{
    use Basic;

    public static function add($userId, $data)
    {
        self::addDeliveryAddress($userId, $data);
        self::addInvoiceAddress($userId, $data);
    }

    public static function addDeliveryAddress($userId, $data)
    {
        $name = $data['company'] ? $data['company'] : $data['first_name'].' '.$data['last_name'];
        $delivery = $data['use_for_delivery'] ?? false;
        
        $data = [
            'customer_id' => $userId,
            'type' => 2,
            'name' => $name,
            'address' => $delivery ? $data['delivery_address'] : $data['address'],
            'address2' => $delivery ? $data['delivery_address2'] : $data['address2'],
            'zipcode' => $delivery ? $data['delivery_zipcode'] : $data['zipcode'],
            'city' => $delivery ? $data['delivery_city'] : $data['city'],
        ];

        return self::store($data);
    }

    public static function addInvoiceAddress($userId, $data)
    {
        $name = $data['company'] ? $data['company'] : $data['first_name'].' '.$data['last_name'];
        
        $data = [
            'customer_id' => $userId,
            'type' => 1,
            'name' => $name,
            'address' => $data['address'],
            'address2' => $data['address2'],
            'zipcode' => $data['zipcode'],
            'city' => $data['city'],
        ];

        return self::store($data);
    }

    public static function getInvoiceAddress($customerId)
    {
        $addresses = CustomerAddress::byCustomer($customerId)->byInvoicing()->get();
        if (count($addresses)) {
            $address = $addresses->first();
        }

        return $address;
    }

    public static function getDeliveryAddress($customerId)
    {
        $addresses = CustomerAddress::byCustomer($customerId)->byDelivery()->get();
        if (count($addresses)) {
            $address = $addresses->first();
        }

        return $address;
    }

    public static function storeByCustomer($customer, $data)
    {
        $deliveries = $data['deliveries'] ?? false;
        if ($deliveries && $deliveries['zipcode'] && $deliveries['city']) {
            $deliveries['customer_id'] = $customer->id;
            $deliveries['type'] = 1;
            self::store($deliveries);
        }

        $invoices = $data['invoices'] ?? false;
        if ($invoices && $invoices['zipcode'] && $invoices['city']) {
            $invoices['customer_id'] = $customer->id;
            $invoices['type'] = 2;
            self::store($invoices);
        }
    }

    public static function toggleActive($id, $active)
    {
        return self::update(['active' => $active], $id);
    }

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