<?php

namespace App\Imports;

use App\Models\SupplierModel;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\RemembersRowNumber;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\BeforeImport;
use Maatwebsite\Excel\Events\AfterImport;

class SupplierImport implements ToModel, WithHeadingRow, WithEvents
{
    use RemembersRowNumber;
    protected $row;

    public function registerEvents(): array
    {
        return [
            BeforeImport::class => function (BeforeImport $event) {
                DB::beginTransaction();
            },
            AfterImport::class => function (AfterImport $event) {
                $errors = session()->get('supplier_err', []);
                if (empty($errors)) {
                    DB::commit();
                } else {
                    DB::rollBack();
                }
            }
        ];
    }

    public function model(array $row)
    {
        $this->row = $this->getRowNumber();
        $hasErrors = false;

        // Validate required fields
        if (empty($row['suppliername'])) {
            $this->storeErrors('Supplier Name', $row['suppliername'] ?? '', 'Enter Supplier Name');
            $hasErrors = true;
        }

        if (empty($row['address'])) {
            $this->storeErrors('Address', $row['address'] ?? '', 'Enter Supplier Address');
            $hasErrors = true;
        }

        // Check for duplicates
        if (!empty($row['phonenumber']) || empty($row['phonenumber'])) {
            if (!empty($row['phonenumber'])) {
                $supplierNumber = SupplierModel::where('phone', $row['phonenumber'])->where('oprntl_flag', 'A')->first();
                if ($supplierNumber) {
                    $this->storeErrors('Phone Number', $row['phonenumber'], 'Already Exists');
                    $hasErrors = true;
                }
            } else {
                $this->storeErrors('Phone Number', $row['phonenumber'], 'Enter Phone number');
                $hasErrors = true;
            }
        }

        if (!empty($row['email']) ) {
            if (!empty($row['email'])) {
                $supplierEmail = SupplierModel::where('email', $row['email'])->where('oprntl_flag', 'A')->first();
                if ($supplierEmail) {
                    $this->storeErrors('Email', $row['email'], 'Already Exists');
                    $hasErrors = true;
                }
            }
        }

        if ($hasErrors) {
            return null;
        }

        try {
            return new SupplierModel([
                'branch_id' => session('branch_id'),
                'supplier_name' => $row['suppliername'],
                'phone' => $row['phonenumber'] ?? null,
                'email' => $row['email'] ?? null,
                'address' => $row['address'],
                'active_status' => 1,
            ]);
        } catch (\Exception $e) {
            // $this->storeErrors('System Error', '', $e->getMessage());
            \Log::error('While importing supplier at row ' . $this->row . ': ' . $e->getMessage());
            return null;
        }
    }

    private function storeErrors($key, $value = ' ', $error = 'Please check the spelling')
    {
        $errors = session()->get('supplier_err', []);
        $errors[] = htmlspecialchars($key) . ': ' . htmlspecialchars($value) . ' ' . htmlspecialchars($error) . ' at row no: ' . $this->row;
        session()->put('supplier_err', $errors);
    }
}