HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/farmfun/reserveren.farmfun.be/app/Komma/Teamleader/TeamleaderService.php
<?php

namespace App\Komma\Teamleader;

use App\Http\Requests\MailProgramRequest;
use App\Http\Requests\QuotationRequest;
use App\Komma\Locations\Models\Location;
use App\Komma\Orders\Models\Order;
use App\Komma\Reservations\Models\Reservation;
use App\Komma\ShoppingCart\ShoppingCart;
use App\Komma\Teamleader\Base\ApiException;
use App\Komma\Teamleader\Resources\Deal;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class TeamleaderService
{
    /**
     * @param Order $order
     * @param Reservation $reservation
     * @return array
     * @throws \Exception
     */
    public function insertOrderIntoTeamleader(Order $order, Reservation $reservation): array
    {
        $this->checkIfAllowedEnvironment();

        try {
            $teamleaderApi = new TeamleaderApi();

            // === Validate uniqueness

            $companyResponse = $teamleaderApi->company->list([
                'filter' => [
                    'email' => [
                        'type' => 'primary',
                        'email' => $order->invoice_email,
                    ],
                ],
            ]);

            if (count($companyResponse->data) > 0) {
                return [false, ['Er zijn al een of meerdere bedrijven gevonden met het emailadres: "'.$order->invoice_email.'"']];
            }

            if (! empty($order->company_vat_number)) {
                $companyResponse = $teamleaderApi->company->list([
                    'filter' => [
                        'vat_number' => $order->company_vat_number,
                    ],
                ]);

                if (count($companyResponse->data) > 0) {
                    return [false, ['Er zijn al een of meerdere bedrijven gevonden met het BTW nummer: "'.$order->company_vat_number.'"']];
                }
            }

            $contactResponse = $teamleaderApi->contact->list([
                'filter' => [
                    'email' => [
                        'type' => 'primary',
                        'email' => $order->email,
                    ],
                ],
            ]);

            if (count($contactResponse->data) > 0) {
                return [false, ['Er zijn al een of meerdere contacten gevonden met het emailadres: "'.$order->email.'"']];
            }

            // === Start creating

            $contact = $teamleaderApi->contact->add(
                $this->extractContactDataFromOrder($order)
            )->data;

            // Het is belangrijk dat iedere deal een bedrijf heeft met een accountmanager.
            // Kun je, ook als de klant kiest voor particulier, het zo maken dat er steeds een bedrijf wordt aangemaakt (dan gewoon voor- en achternaam van de klant).
            $company = $teamleaderApi->company->add(
                $this->extractCompanyDataFromOrder($order)
            )->data;

            $teamleaderApi->contact->linkToCompany(
                $contact->id,
                $company->id
            );

            $dealData = $this->extractDealDataFromOrder($order, $reservation);
            $dealData['lead'] = [
                'customer' => [
                    'type' => isset($company) ? 'company' : 'contact',
                    'id' => isset($company) ? $company->id : $contact->id,
                ],
                'contact_person_id' => $contact->id,
            ];
            $deal = $teamleaderApi->deal->create($dealData)->data;

            $quotationData = $this->extractQuotationDataFromOrder($order, $deal->id);
            $quotation = $teamleaderApi->quotation->create($quotationData)->data;

//            $invoiceData = $this->extractInvoiceDataFromOrder($order);
//            $invoiceData['invoicee'] = [
//                'customer' => [
//                    'type' => isset($company) ? 'company' : 'contact',
//                    'id' => isset($company) ? $company->id : $contact->id,
//                ],
//            ];
//
//            $teamleaderApi->invoice->draft($invoiceData)->data;
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            Log::error($e->getTraceAsString());

            return [false, ['Er is iets mis gegaan bij het wegschrijven richting Teamleader']];
        }

        return [true, []];
    }

    /**
     * @param ShoppingCart $shoppingCart
     * @param MailProgramRequest $request
     * @return array
     * @throws \Exception
     */
    public function insertShoppingCartIntoTeamLeader(ShoppingCart $shoppingCart, MailProgramRequest $request): array
    {
        $this->checkIfAllowedEnvironment();

        try {

            $contactEmail = $request->get('email');
            $contactFirstName = $request->get('first_name') ?? '';
            $contactLastName = $request->get('last_name') ?? '';
            $companyName = $request->get('company_name') ?? '';

            $teamleaderApi = new TeamleaderApi();

            // === Validate uniqueness
            $companyResponse = $teamleaderApi->company->list(['filter' => ['email' => ['type' => 'primary', 'email' => $contactEmail]]]);
            if (count($companyResponse->data) > 0) return [false, ['Er zijn al een of meerdere bedrijven gevonden met het emailadres: "'.$contactEmail.'"']];

            $contactResponse = $teamleaderApi->contact->list(['filter' => ['email' => ['type' => 'primary', 'email' => $contactEmail]]]);
            if (count($contactResponse->data) > 0) return [false, ['Er zijn al een of meerdere contacten gevonden met het emailadres: "'.$contactEmail.'"']];

            // === Create Contact
            $contactArray = [];
            $contactArray['first_name'] = $contactFirstName;
            $contactArray['last_name'] = $contactLastName;
            $contactArray['emails'] = [['type' => 'primary', 'email' => $contactEmail]];
            $contact = $teamleaderApi->contact->add($contactArray)->data;

            // === Create Company
            // Het is belangrijk dat iedere deal een bedrijf heeft met een accountmanager.
            // Kun je, ook als de klant kiest voor particulier, het zo maken dat er steeds een bedrijf wordt aangemaakt (dan gewoon voor- en achternaam van de klant).
            $companyArray = [];
            if (! empty($companyName)) {
                $companyArray['name'] = $companyName;
            } else {
                $companyArray['name'] = $contactFirstName.' '.$contactLastName;
            }
            $companyArray['responsible_user_id'] = $shoppingCart->getLocation()->teamleader_related_user_id;
            $companyArray['emails'] = [['type' => 'primary', 'email' => $contactEmail]];
            $companyArray['language'] = 'nl';
            $companyArray['tags'] = ['website'];
            $company = $teamleaderApi->company->add($companyArray)->data;

            // === Create link between Contact and Company
            $teamleaderApi->contact->linkToCompany($contact->id, $company->id);

            // === Create Deal
            $deal = $teamleaderApi->deal->create(
                $this->extractDealDataFromShoppingCart($shoppingCart, $contactFirstName, $contactLastName, $contact, $company)
            )->data;

            $quotationData = $this->extractQuotationDataFromShoppingCart($shoppingCart, $deal->id);
            $teamleaderApi->quotation->create($quotationData)->data;

        } catch (\Exception $e) {
            Log::error($e->getMessage());
            Log::error($e->getTraceAsString());

            return [false, ['Er is iets mis gegaan bij het wegschrijven richting Teamleader']];
        }

        return [true, []];
    }

    /**
     * @param QuotationRequest $request
     * @return array
     * @throws \Exception
     */
    public function insertQuotationIntoTeamLeader(QuotationRequest $request): array
    {
        $this->checkIfAllowedEnvironment();

        try {

            $quotationEmail = $request->get('email');
            $quotationFirstName = $request->get('first_name') ?? '';
            $quotationNamePreposition = $request->get('name_preposition') ?? '';
            $quotationLastName = $request->get('last_name') ?? '';
            $quotationCompanyName = $request->get('company_name') ?? '';
            $quotationLocation = $request->get('location') ?? '';
            $quotationPhone = $request->get('phone') ?? '';

            $location = Location::where('city', '=', $quotationLocation)->first();

            $teamleaderApi = new TeamleaderApi();

            // === Validate uniqueness
            $companyResponse = $teamleaderApi->company->list(['filter' => ['email' => ['type' => 'primary', 'email' => $quotationEmail]]]);
            if (count($companyResponse->data) > 0) return [false, ['Er zijn al een of meerdere bedrijven gevonden met het emailadres: "'.$quotationEmail.'"']];

            $contactResponse = $teamleaderApi->contact->list(['filter' => ['email' => ['type' => 'primary', 'email' => $quotationEmail]]]);
            if (count($contactResponse->data) > 0) return [false, ['Er zijn al een of meerdere contacten gevonden met het emailadres: "'.$quotationEmail.'"']];

            // === Create Contact
            $contactArray = [];
            $contactArray['first_name'] = $quotationFirstName;
            $contactArray['last_name'] = trim($quotationNamePreposition.' '.$quotationLastName);
            $contactArray['emails'] = [['type' => 'primary', 'email' => $quotationEmail]];
            $contactArray['telephones'] = [['type' => 'phone', 'number' => $quotationPhone]];
            $contact = $teamleaderApi->contact->add($contactArray)->data;

            // === Create Company
            // Het is belangrijk dat iedere deal een bedrijf heeft met een accountmanager.
            // Kun je, ook als de klant kiest voor particulier, het zo maken dat er steeds een bedrijf wordt aangemaakt (dan gewoon voor- en achternaam van de klant).
            $companyArray = [];
            if (! empty($quotationCompanyName)) {
                $companyArray['name'] = $quotationCompanyName;
            } else {
                $companyArray['name'] = $quotationFirstName.' '.trim($quotationNamePreposition.' '.$quotationLastName);
            }
            $companyArray['responsible_user_id'] = isset($location) ? $location->teamleader_related_user_id : '';
            $companyArray['emails'] = [['type' => 'primary', 'email' => $quotationEmail]];
            $companyArray['telephones'] = [['type' => 'phone', 'number' => $quotationPhone]];
            $companyArray['language'] = 'nl';
            $companyArray['tags'] = ['website'];
            $company = $teamleaderApi->company->add($companyArray)->data;

            // === Create link between Contact and Company
            $teamleaderApi->contact->linkToCompany($contact->id, $company->id);

            // === Create Deal
            $teamleaderApi->deal->create(
                $this->extractDealDataFromQuotation($request, $location, $contact, $company)
            )->data;


        } catch (\Exception $e) {
            Log::error($e->getMessage());
            Log::error($e->getTraceAsString());

            return [false, ['Er is iets mis gegaan bij het wegschrijven richting Teamleader']];
        }

        return [true, []];
    }

    /**
     * @return void
     * @throws \Exception
     */
    private function checkIfAllowedEnvironment()
    {
        if (app()->environment() === 'production') return;
        throw new \Exception('Add records into Teamleader is disabled for all non-production environments');
    }

    /**
     * Create array for creating a contact in Teamleader by provided Order
     *
     * @param Order $order
     * @return array
     */
    private function extractContactDataFromOrder(Order $order): array
    {
        $contact = new class {
        };
        $contact->first_name = $order->first_name;
        $contact->last_name = $order->last_name;

        $contact->emails = [
            [
                'type' => 'primary',
                'email' => $order->email,
            ],
        ];

        $contact->telephones = [
            [
                'type' => 'phone',
                'number' => $order->phone,
            ],
        ];

        $contact->addresses = [
            [
                'type' => 'primary',
                'address' => [
                    'line_1' => $order->invoice_street.' '.$order->invoice_house_number,
                    'postal_code' => $order->invoice_postal_code,
                    'city' => $order->invoice_city,
                    'country' => $order->getCountryIso(),
                ],
            ],
        ];

        $contact->language = 'nl';
        $contact->tags = [
            'website',
        ];

        // Already added directly to mailchimp
//        $contact->marketing_mails_consent = $order->subscribe_to_newsletter;

        return (array) $contact;
    }

    /**
     * Create array for creating a company in Teamleader by provided Order
     *
     * @param Order $order
     * @return array
     */
    private function extractCompanyDataFromOrder(Order $order): array
    {
        $company = new class {};
        if (! empty($order->company_name)) {
            $company->name = $order->company_name;
        } else {
            $company->name = $order->first_name.' '.$order->last_name;
        }
        $company->responsible_user_id = $order->getLocation()->teamleader_related_user_id;

        if (! empty($order->company_vat_number)) {
            $company->vat_number = $order->company_vat_number;
        }

        $company->emails = [
            [
                'type' => 'primary',
                'email' => $order->email,
            ],
        ];

        if (! empty($order->invoice_email) && $order->email !== $order->invoice_email) {
            $company->emails[] = [
                'type' => 'invoicing',
                'email' => $order->invoice_email,
            ];
        }

        $company->telephones = [
            [
                'type' => 'phone',
                'number' => $order->phone,
            ],
        ];

        $company->addresses = [
            [
                'type' => 'primary',
                'address' => [
                    'line_1' => $order->invoice_street.' '.$order->invoice_house_number,
                    'postal_code' => $order->invoice_postal_code,
                    'city' => $order->invoice_city,
                    'country' => $order->getCountryIso(),
                ],
            ],
        ];

        $company->language = 'nl';
        $company->tags = [
            'website',
        ];

        return (array) $company;
    }

    /**
     * Create array for creating a company in Teamleader by provided Order
     *
     * @param Order $order
     * @return array
     * @throws ApiException
     */
    private function extractInvoiceDataFromOrder(Order $order): array
    {
        $invoice = new class {
        };
        $invoice->department_id = $order->getLocation()->teamleader_department_id;
        $invoice->payment_term = [
            'type' => 'after_invoice_date',
            'days' => 10,
        ];

        $teamleaderApi = new TeamleaderApi();

        // Get correct taxs for department
        $taxRates = $teamleaderApi->taxRate->list([
            'filter' => [
                'department_id' => $invoice->department_id,
            ],
        ])->data;

        $tax21 = array_values(array_filter($taxRates, fn ($taxRate) => Str::contains($taxRate->description, '21%')))[0];
        $tax12 = array_values(array_filter($taxRates, fn ($taxRate) => Str::contains($taxRate->description, '12%')))[0];

        $lines = [];
        foreach ($order->lines as $orderLine) {
            $teamleaderLine = new class {
            };

            // Combined price
            if ($orderLine->price_each_unit > 0 && $orderLine->price_start_up > 0) {
                $teamleaderLine->quantity = 1;
                $teamleaderLine->unit_price = [
                    'amount' => ($orderLine->price_total / (100 + $orderLine->vat_percentage) * 100) / 100,
                    'currency' => 'EUR',
                    'tax' => 'excluding',
                ];
            } elseif ($orderLine->price_start_up > 0 && $orderLine->price_each_unit == 0) {
                $teamleaderLine->quantity = 1;
                $teamleaderLine->unit_price = [
                    'amount' => ($orderLine->price_total / (100 + $orderLine->vat_percentage) * 100) / 100,
                    'currency' => 'EUR',
                    'tax' => 'excluding',
                ];
            } elseif ($orderLine->price_each_unit > 0) {
                $teamleaderLine->quantity = $orderLine->quantity;
                $teamleaderLine->unit_price = [
                    'amount' => ($orderLine->price_each_unit / (100 + $orderLine->vat_percentage) * 100) / 100,
                    'currency' => 'EUR',
                    'tax' => 'excluding',
                ];
            } else {
                // Skip product, doesn't match any conditions
                continue;
            }

            switch ($orderLine->vat_percentage) {
                case 12:
                    $teamleaderLine->tax_rate_id = $tax12->id;
                    break;

                case 21:
                    $teamleaderLine->tax_rate_id = $tax21->id;
                    break;

                default:
                    throw new \UnexpectedValueException('Undetermined VAT rate');
            }

            $teamleaderLine->quantity = $orderLine->quantity;
            $teamleaderLine->description = $orderLine->product->translation->name;

            $teamleaderProduct = $teamleaderApi->product->list([
                'filter' => [
                    'term' => 'PROD-'.$orderLine->product_id,
                ],
            ])->data;

            if (count($teamleaderProduct) === 1) {
                $teamleaderLine->product_id = $teamleaderProduct[0]->id;
            }

            $lines[] = (array) $teamleaderLine;
        }

        $invoice->grouped_lines = [
            [
                'line_items' => $lines,
            ],
        ];

        return (array) $invoice;
    }

    /**
     * @param Order $order
     * @param string $dealId
     * @return array
     * @throws ApiException
     */
    private function extractQuotationDataFromOrder(Order $order, string $dealId): array
    {
        $quotation = new class {
        };
        $quotation->deal_id = $dealId;

        $teamleaderApi = new TeamleaderApi();

        // Get correct taxs for department
        $taxRates = $teamleaderApi->taxRate->list([
            'filter' => [
                'department_id' => $order->getLocation()->teamleader_department_id,
            ],
        ])->data;

        $tax21 = array_values(array_filter($taxRates, fn ($taxRate) => Str::contains($taxRate->description, '21%')))[0];
        $tax12 = array_values(array_filter($taxRates, fn ($taxRate) => Str::contains($taxRate->description, '12%')))[0];

        $lines = [];
        foreach ($order->lines as $orderLine) {
            $teamleaderLine = new class {};

            // https://app.asana.com/0/1204095245059239/1204328048650609/f
            // Exception for BBQ + BAKKER
            if ($orderLine->product_id === 12) {

                // BBQ bakken door traiteur - 1x
                $teamleaderProduct = $teamleaderApi->product->list([
                    'filter' => [
                        'term' => 'PROD-'.$orderLine->product_id,
                    ],
                ])->data;

                $teamleaderLine->quantity = 1;
                $teamleaderLine->unit_price = [
                    'amount' => ($orderLine->price_start_up / (100 + 21) * 100) / 100,
                    'currency' => 'EUR',
                    'tax' => 'excluding',
                ];
                $teamleaderLine->tax_rate_id = $tax21->id;
                $teamleaderLine->description = $teamleaderProduct[0]->name;
                if (count($teamleaderProduct) === 1) $teamleaderLine->product_id = $teamleaderProduct[0]->id;

                $lines[] = (array) $teamleaderLine;

                // BBQ - extra line - aantal personen
                $teamleaderProducts = $teamleaderApi->product->list()->data;
                foreach ($teamleaderProducts as $teamleaderProduct) {
                    if (trim($teamleaderProduct->name) === 'BBQ') {

                        $teamleaderExtraLine = new class {};

                        $teamleaderExtraLine->quantity = $orderLine->quantity;
                        $teamleaderExtraLine->unit_price = [
                            'amount' => ($orderLine->price_each_unit / (100 + $orderLine->vat_percentage) * 100) / 100,
                            'currency' => 'EUR',
                            'tax' => 'excluding',
                        ];
                        switch ($orderLine->vat_percentage) {
                            case 12:
                                $teamleaderExtraLine->tax_rate_id = $tax12->id;
                                break;

                            case 21:
                                $teamleaderExtraLine->tax_rate_id = $tax21->id;
                                break;

                            default:
                                throw new \UnexpectedValueException('Undetermined VAT rate');
                        }
                        $teamleaderExtraLine->description = $teamleaderProduct->name;
                        $teamleaderExtraLine->product_id = $teamleaderProduct->id;

                        $lines[] = (array) $teamleaderExtraLine;
                    }
                }

            } else {

                // Combined price
                if ($orderLine->price_each_unit > 0 && $orderLine->price_start_up > 0) {
                    $teamleaderLine->quantity = 1;
                    $teamleaderLine->unit_price = [
                        'amount' => ($orderLine->price_total / (100 + $orderLine->vat_percentage) * 100) / 100,
                        'currency' => 'EUR',
                        'tax' => 'excluding',
                    ];
                } elseif ($orderLine->price_start_up > 0 && $orderLine->price_each_unit == 0) {
                    $teamleaderLine->quantity = 1;
                    $teamleaderLine->unit_price = [
                        'amount' => ($orderLine->price_total / (100 + $orderLine->vat_percentage) * 100) / 100,
                        'currency' => 'EUR',
                        'tax' => 'excluding',
                    ];
                } elseif ($orderLine->price_each_unit > 0) {
                    $teamleaderLine->quantity = $orderLine->quantity;
                    $teamleaderLine->unit_price = [
                        'amount' => ($orderLine->price_each_unit / (100 + $orderLine->vat_percentage) * 100) / 100,
                        'currency' => 'EUR',
                        'tax' => 'excluding',
                    ];
                } else {
                    // Skip product, doesn't match any conditions
                    continue;
                }

                switch ($orderLine->vat_percentage) {
                    case 12:
                        $teamleaderLine->tax_rate_id = $tax12->id;
                        break;

                    case 21:
                        $teamleaderLine->tax_rate_id = $tax21->id;
                        break;

                    default:
                        throw new \UnexpectedValueException('Undetermined VAT rate');
                }

                $teamleaderLine->description = $orderLine->product->translation->name;

                $teamleaderProduct = $teamleaderApi->product->list([
                    'filter' => [
                        'term' => 'PROD-'.$orderLine->product_id,
                    ],
                ])->data;

                if (count($teamleaderProduct) === 1) {
                    $teamleaderLine->product_id = $teamleaderProduct[0]->id;
                }

                $lines[] = (array) $teamleaderLine;
            }

        }

        $quotation->grouped_lines = [
            [
                'line_items' => $lines,
            ],
        ];

        return (array) $quotation;
    }

    /**
     * @param ShoppingCart $shoppingCart
     * @param string $dealId
     * @return array
     * @throws ApiException
     */
    private function extractQuotationDataFromShoppingCart(ShoppingCart $shoppingCart, string $dealId): array
    {
        $quotation = new class {};
        $quotation->deal_id = $dealId;

        $teamleaderApi = new TeamleaderApi();

        // Get correct taxs for department
        $taxRates = $teamleaderApi->taxRate->list(['filter' => ['department_id' => $shoppingCart->getLocation()->teamleader_department_id]])->data;
        $tax21 = array_values(array_filter($taxRates, fn ($taxRate) => Str::contains($taxRate->description, '21%')))[0];
        $tax12 = array_values(array_filter($taxRates, fn ($taxRate) => Str::contains($taxRate->description, '12%')))[0];

        $lines = [];
        foreach ($shoppingCart->getItems() as $shoppingCartItem) {

            $shoppingCartItemProduct = $shoppingCartItem->getProduct();
            $teamleaderLine = new class {};

            $vatPercentage = $shoppingCartItemProduct->vat_percentage;

            // Combined price
            if ($shoppingCartItemProduct->price_each_unit > 0 && $shoppingCartItemProduct->price_start_up > 0) {
                $teamleaderLine->quantity = 1;
                $teamleaderLine->unit_price = [
                    'amount' => ($shoppingCartItemProduct->price_total / (100 + $vatPercentage) * 100) / 100,
                    'currency' => 'EUR',
                    'tax' => 'excluding',
                ];
            } elseif ($shoppingCartItemProduct->price_start_up > 0 && $shoppingCartItemProduct->price_each_unit == 0) {
                $teamleaderLine->quantity = 1;
                $teamleaderLine->unit_price = [
                    'amount' => ($shoppingCartItemProduct->price_total / (100 + $vatPercentage) * 100) / 100,
                    'currency' => 'EUR',
                    'tax' => 'excluding',
                ];
            } elseif ($shoppingCartItemProduct->price_each_unit > 0) {
                $teamleaderLine->quantity = ($shoppingCartItem->amountOfPersons ?? 1);
                $teamleaderLine->unit_price = [
                    'amount' => ($shoppingCartItemProduct->price_each_unit / (100 + $vatPercentage) * 100) / 100,
                    'currency' => 'EUR',
                    'tax' => 'excluding',
                ];
            } else {
                // Skip product, doesn't match any conditions
                continue;
            }

            switch ($vatPercentage) {
                case 12:
                    $teamleaderLine->tax_rate_id = $tax12->id;
                    break;

                case 21:
                    $teamleaderLine->tax_rate_id = $tax21->id;
                    break;

                default:
                    throw new \UnexpectedValueException('Undetermined VAT rate');
            }

            $teamleaderLine->description = $shoppingCartItemProduct->translation->name;

            $teamleaderProduct = $teamleaderApi->product->list(['filter' => ['term' => 'PROD-'.$shoppingCartItemProduct->id]])->data;
            if (count($teamleaderProduct) === 1) {
                $teamleaderLine->product_id = $teamleaderProduct[0]->id;
            }

            $lines[] = (array) $teamleaderLine;
        }

        $quotation->grouped_lines = [
            [
                'line_items' => $lines,
            ],
        ];

        return (array) $quotation;
    }


    /**
     * Create array for creating a Deal in Teamleader by provided Order
     *
     * @param Order $order
     * @param Reservation $reservation
     * @return array
     */
    private function extractDealDataFromOrder(Order $order, Reservation $reservation): array
    {
        $deal = new class {
        };

        $title = $order->order_reservation_number;
        $title .= ' '.$order->first_name;
        if (! empty($order->name_preposition)) {
            $title .= ' '.$order->name_preposition;
        }
        $title .= ' '.$order->last_name;

        $deal->title = $title;
        $deal->summary = $order->remarks;
        $deal->source_id = Deal::ONLINE_BOOKING_SOURCE;
        $deal->department_id = $order->getLocation()->teamleader_department_id;
        $deal->responsible_user_id = $order->getLocation()->teamleader_related_user_id;
        $deal->phase_id = Deal::WON_PHASE;
        $deal->estimated_value = [
            'amount' => $order->total / 100,
            'currency' => 'EUR',
        ];
        $deal->estimated_probability = 1;
        $deal->estimated_closing_date = now()->format('Y-m-d');

        $hasFood = false;
        foreach ($order->lines as $line) {
            if ($line->product->product_type == 0) {
                continue;
            }
            $hasFood = true;
        }

        $startTime = Carbon::createFromTimeString(
            $reservation->items()->min('start_time')
        );

        $deal->custom_fields = [
            [
                'id' => Deal::$custom_fields_ids['event_date'],
                'value' => $order->date->format('Y-m-d'),
            ],
            [
                'id' => Deal::$custom_fields_ids['persons'],
                'value' => (string) $order->lines->max('quantity'),
            ],
            [
                'id' => Deal::$custom_fields_ids['start_time'],
                'value' => $startTime->format('H:i'),
            ],
            [
                'id' => Deal::$custom_fields_ids['with_food'],
                'value' => $hasFood,
            ],
        ];

        return (array) $deal;
    }

    /**
     * Create array for creating a Deal in Teamleader by provided Shoppingcart
     *
     * @param ShoppingCart $shoppingCart
     * @param string $contactFirstName
     * @param string $contactLastName
     * @param $contact
     * @param $company
     * @return array
     */
    private function extractDealDataFromShoppingCart(ShoppingCart $shoppingCart, string $contactFirstName, string $contactLastName, $contact, $company): array
    {
        $dealData = new class {};
        $dealData->title = 'Offerte aanvraag van '.$contactFirstName.' '.$contactLastName;
        $dealData->source_id = Deal::ONLINE_BOOKING_SOURCE;
        $dealData->department_id = $shoppingCart->getLocation()->teamleader_department_id;
        $dealData->responsible_user_id = $shoppingCart->getLocation()->teamleader_related_user_id;
        $dealData->phase_id = Deal::NEW_PHASE;
        $dealData->estimated_value = [
            'amount' => number_format(str_replace(',', '.', $shoppingCart->getTotal()), 2),
            'currency' => 'EUR',
        ];

        $hasFood = false;
        $persons = 0;
        $startTime = '2359';
        foreach ($shoppingCart->getItems() as $item) {
            if ($item->amountOfPersons > $persons) {
                $persons = $item->amountOfPersons;
            }

            $selectedTimeSlot = $item->getSelectedTimeSlot();
            if(isset($selectedTimeSlot->start) && $selectedTimeSlot->start->format('Hi') < $startTime) {
                $startTime = $selectedTimeSlot->start->format('Hi');
            }

            if ($item->getProduct()->product_type == 0) {
                continue;
            }
            $hasFood = true;
        }

        $dealData->custom_fields = [
            [
                'id' => Deal::$custom_fields_ids['event_date'],
                'value' => $shoppingCart->getDate()->format('Y-m-d'),
            ],
            [
                'id' => Deal::$custom_fields_ids['persons'],
                'value' => (string) $persons,
            ],
            [
                'id' => Deal::$custom_fields_ids['start_time'],
                'value' => substr($startTime, 0, 2).':'.substr($startTime, 2, 2),
            ],
            [
                'id' => Deal::$custom_fields_ids['with_food'],
                'value' => $hasFood,
            ],
        ];

        $dealData->lead = [
            'customer' => [
                'type' => isset($company) ? 'company' : 'contact',
                'id' => isset($company) ? $company->id : $contact->id,
            ],
            'contact_person_id' => $contact->id,
        ];

        return (array) $dealData;
    }

    /**
     * @param QuotationRequest $request
     * @param Location $location
     * @param $contact
     * @param $company
     * @return array
     */
    private function extractDealDataFromQuotation(QuotationRequest $request, Location $location, $contact, $company): array
    {

        $title = 'Offerte aanvraag van ';
        $title .= ' '.$request->get('first_name');
        if (! empty($request->get('name_preposition'))) {
            $title .= ' '.$request->get('name_preposition');
        }
        $title .= ' '.$request->get('last_name');

        $dealData = new class {};
        $dealData->title = $title;
        $dealData->summary = $request->get('form_message');
        $dealData->source_id = Deal::ONLINE_BOOKING_SOURCE;
        $dealData->department_id = $location->teamleader_department_id;
        $dealData->responsible_user_id = $location->teamleader_related_user_id;
        $dealData->phase_id = Deal::NEW_PHASE;

        $dealData->custom_fields = [
            [
                'id' => Deal::$custom_fields_ids['event_date'],
                'value' => Carbon::parse($request->get('date'))->format('Y-m-d'),
            ],
            [
                'id' => Deal::$custom_fields_ids['persons'],
                'value' => (string) $request->get('estimation_persons'),
            ],
            [
                'id' => Deal::$custom_fields_ids['start_time'],
                'value' => $request->get('start_time'),
            ],
            [
                'id' => Deal::$custom_fields_ids['with_food'],
                'value' => $request->get('with_food') === 'on',
            ],
        ];

        $dealData->lead = [
            'customer' => [
                'type' => isset($company) ? 'company' : 'contact',
                'id' => isset($company) ? $company->id : $contact->id,
            ],
            'contact_person_id' => $contact->id,
        ];

        return (array) $dealData;
    }
}