<?php

namespace App\DBRealTestSupport;

use Faker\Factory;
use Illuminate\Support\Facades\DB;

class FactReceiptDetailMother
{

    public static function build1($idFactProduct = null, $idFactTypeOperation = null, $idFactReceipt = null, $idFactUnit = null, $id = 1)
    {
        $idFactProduct = $idFactProduct ?? FactProductMother::push1()['Id_FactProduct'];
        $idFactTypeOperation = $idFactTypeOperation ?? FactTypeOperationMother::push1()['Id_FactTypeOperation'];
        $idFactReceipt = $idFactReceipt ?? FactReceiptMother::push1()['Id_FactReceipt'];
        $idFactUnit = $idFactUnit ?? FactUnitMother::push1()['Id_FactUnit'];
        $faker = Factory::create();
        $unitPrice = $faker->randomNumber(8);
        $discount = $faker->randomNumber(8);
        return [
            'Id_FactReceiptDetail' => $id,
            'FactReceiptDetail_Amount' => $faker->randomNumber(8),
            'FactReceiptDetail_UnitPrice' => $unitPrice,
            'FactReceiptDetail_Discount' => $discount,
            'FactReceiptDetail_Total' => $unitPrice * $discount,
            'FactReceiptDetail_Status' => $faker->randomElement([1, 2]),
            'Id_FactProduct' => $idFactProduct,
            'Id_FactTypeOperation' => $idFactTypeOperation,
            'Id_FactUnit' => $idFactUnit,
            'Id_FactReceipt' => $idFactReceipt,
        ];
    }

    public static function push1($idFactProduct = null, $idFactTypeOperation = null, $idFactReceipt = null, $idFactUnit = null, $id = 1)
    {
        return self::push(self::build1($idFactProduct, $idFactTypeOperation, $idFactReceipt, $idFactUnit, $id));
    }

    private static function push($object)
    {
        $response = DB::select("INSERT INTO `t_fact_receipt_detail`(
            `FactReceiptDetail_Amount`,
            `FactReceiptDetail_UnitPrice`,
            `FactReceiptDetail_Discount`,
            `FactReceiptDetail_Status`,
            `Id_FactProduct`,
            `Id_FactTypeOperation`,
            `Id_FactUnit`,
            `Id_FactReceipt`
        ) VALUES (?,?,?,?,?,?,?,?)", [
            $object['FactReceiptDetail_Amount'],
            $object['FactReceiptDetail_UnitPrice'],
            $object['FactReceiptDetail_Discount'],
            $object['FactReceiptDetail_Status'],
            $object['Id_FactProduct'],
            $object['Id_FactTypeOperation'],
            $object['Id_FactUnit'],
            $object['Id_FactReceipt']
        ]);
        $response = DB::select('SELECT LAST_INSERT_ID() as `id`');
        $object['Id_FactReceiptDetail'] = $response[0]->id;
        return $object;
    }

    public static function tablesToClear()
    {
        return [
            TableCreation::FACT_RECEIPT_DETAIL,
            ...FactReceiptMother::tablesToClear(),
            ...FactProductMother::tablesToClear(),
            ...FactTypeOperationMother::tablesToClear()
        ];
    }
}
