<?php

namespace App\Imports;

use App\Models\accounting\AccountItem;
use App\Models\accounting\AccountItemUnit;
use App\Models\accounting\AccountItemCategory;
use Illuminate\Validation\ValidationException;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Facades\Log;

class ItemImport implements ToModel, WithHeadingRow
{
    private $admin_id;

    public function __construct($adminId)
    {
        $this->admin_id = $adminId;
    }

    public function model(array $row)
    {
        // Validate required fields
       

        $itemData = [
            "admin_id" => $this->admin_id,
            "name" => $row["name"] ?? null,
            "item_code" => $row["item_code"] ?? null,
            "description" => $row["description"] ?? null,
            "unit_id" => $this->getOrCreateUnitId($row["unit"] ?? 0),
            "category_id" => $this->getOrCreateCategoryId($row["category"] ?? 0),
            "tax" => $row["tax"] ?? 0,
            "sales_unit_price" => $row["sales_unit_price"] ?? 0,
            "sales_currency" => $row["sales_currency"] ?? null,
            "sales_cess_percentage" => $row["sales_cess_percentage"] ?? 0,
            "sales_cess_plus" => $row["sales_cess_plus"] ?? 0,
            "purchase_unit_price" => $row["purchase_unit_price"] ?? 0,
            "purchase_currency" => $row["purchase_currency"] ?? null,
            "purchase_cess_percentage" => $row["purchase_cess_percentage"] ?? 0,
            "purchase_cess_plus" => $row["purchase_cess_plus"] ?? 0,
            "quantity" => $row["quantity"] ?? 0,
            "type" => $row["type"] ?? null,
            'created_at' => now()
        ];

        return new AccountItem($itemData);
    }

    private function getOrCreateUnitId($unitName)
    {
        if (empty($unitName)) {
            return 0;
        }

        $unit = AccountItemUnit::where("admin_id", $this->admin_id)
            ->whereRaw('LOWER(name) = ?', [strtolower($unitName)])
            ->first();

        if (!$unit) {
            $unit = AccountItemUnit::create([
                "admin_id" => $this->admin_id,
                "name" => $unitName
            ]);
        }

        return $unit->id;
    }

    private function getOrCreateCategoryId($categoryName)
    {
        if (empty($categoryName)) {
            return 0;
        }

        $category = AccountItemCategory::where("admin_id", $this->admin_id)
            ->whereRaw('LOWER(name) = ?', [strtolower($categoryName)])
            ->first();

        if (!$category) {
            $category = AccountItemCategory::create([
                "admin_id" => $this->admin_id,
                "name" => $categoryName
            ]);
        }

        return $category->id;
    }
}