<?php

namespace App\Services;

use Openguru\OpenCartFramework\QueryBuilder\Builder;
use Openguru\OpenCartFramework\QueryBuilder\Connections\ConnectionInterface;
use Openguru\OpenCartFramework\Support\Arr;

class OcCustomerService
{
    private Builder $builder;
    private ConnectionInterface $database;

    public function __construct(Builder $builder, ConnectionInterface $database)
    {
        $this->builder = $builder;
        $this->database = $database;
    }

    public function findOrCreate(array $orderData): ?int
    {
        $email = Arr::get($orderData, 'email');
        $phone = Arr::get($orderData, 'telephone');

        if (! $email && ! $phone) {
            return null;
        }

        $customer = $this->builder->newQuery()
            ->from(db_table('customer'))
            ->where('email', '=', $email)
            ->where('telephone', '=', $phone)
            ->firstOrNull();

        if ($customer) {
            return (int) $customer['customer_id'];
        }

        $customerData = [
            'customer_group_id' => $orderData['customer_group_id'],
            'store_id' => $orderData['store_id'],
            'language_id' => $orderData['language_id'],
            'firstname' => $orderData['firstname'] ?? '',
            'lastname' => $orderData['lastname'] ?? '',
            'email' => $orderData['email'] ?? '',
            'telephone' => $orderData['telephone'] ?? '',
            'fax' => $orderData['fax'] ?? '',
            'password' => bin2hex(random_bytes(16)),
            'salt' => bin2hex(random_bytes(9)),
            'ip' => $orderData['ip'] ?? '',
            'status' => 1,
            'safe' => 0,
            'token' => bin2hex(random_bytes(32)),
            'code' => '',
            'date_added' => $orderData['date_added'],
        ];

        $this->database->insert(db_table('customer'), $customerData);

        return $this->database->lastInsertId();
    }
}
