<?php

namespace App\Imports;

use App\Model\product\ProductModel;
use App\Model\setup\MemberModel;
use App\Model\setup\MemberTypeModel;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Validators\Failure;
use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;

class MemberPackageImport implements ToModel, WithHeadingRow, SkipsOnFailure, WithCalculatedFormulas
{

    public function model(array $row)
    {
        if (@$row['barcode']) {
            $product = ProductModel::where('barcode', $row['barcode'])->first();
            $member_type = MemberTypeModel::updateOrCreate(['name'=>$row['member_type']],['name'=>$row['member_type']]);

            if ($product) {
                return MemberModel::updateOrCreate(
                    [
                        'member_type' => $member_type->id,
                        'product_id' => $product->id
                    ], [
                    'user_id' => Auth::id(),
                    'member_type' => $member_type->id,
                    'product_id' => $product->id,
                    'price_riel' => $row['price_riel'],
                    'price_usd' => $row['price_usd'],
                ]);
            }
        }
    }

    public function onFailure(Failure ...$failures)
    {
        // TODO: Implement onFailure() method.
    }
}
