<?php

namespace App\Classes\Modules\Transactions\Services;


use App\Models\Transaction;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class GeneratesPurchaseOrderProducts
{

    /** @var Collection */
    private $products;

    /**
     * GeneratesPurchaseOrderProducts constructor.
     * @param Collection $products
     */
    public function __construct(Collection $products)
    {
        $this->products = $products;
    }


    public function execute(Transaction $transaction, float $amount){

        $products = collect();

        $amountDifference = $amount - $transaction->amount;
        $transactionDetails = $transaction->transactionDetails()->select('*', DB::raw('abs(price - '.abs($amountDifference).') as nearest_price'))->orderBy('nearest_price')->get();
        foreach ($transactionDetails as $product) {

            if($product->price <= 0){
                $amountDifference = $amountDifference + ($product->price * $product->quantity);
                continue;
            }

            $units = floor(abs($amountDifference) / $product->price);
            $quantity = $product->quantity;

            if($amountDifference > 0){
                $quantity = $product->quantity + $units;
                $amountDifference = $amountDifference - ($product->price * $units);
            }

            if($amountDifference < 0) {
                $units = ceil(abs($amountDifference) / $product->price);
                $quantity = $product->quantity - $units;

                if($quantity <= 0){
                    $amountDifference = $amountDifference + ($product->price * $product->quantity);
                    continue;
                }

                $amountDifference = $amountDifference + ($product->price * $quantity);
            }

            $products->push([
                'description' => $product->product_name,
                'quantity' => (int) $quantity,
                'stockCode' => $product->product_code,
                'total' => $product->price * $quantity,
                'unit_price' => (float) $product->price,
            ]);

        }

        return $products;

    }

}