<?php

namespace App\Filament\Imports;

use App\Models\AlertMailRule;
use App\Models\Plant;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Filament\Facades\Filament;
use Str;

class AlertMailRuleImporter extends Importer
{
    protected static ?string $model = AlertMailRule::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('module')
                ->requiredMapping()
                ->exampleHeader('Module')
                ->example('ProductionQuantities/InvoiceValidation/QualityValidation/InvoiceDataReport/InvoiceTransit')
                ->label('Module')
                ->rules(['required']),
            ImportColumn::make('rule_name')
                ->requiredMapping()
                ->exampleHeader('Rule Name')
                ->example('ProductionMail/InvoiceMail/QualityMail/InvoiceDataMail/InvoiceTransitMail')
                ->label('Rule Name')
                ->rules(['required']),
            ImportColumn::make('email')
                ->requiredMapping()
                ->exampleHeader('Email')
                ->example('admin@cripumps.com,ranjith.bala@cripumps.com')
                ->label('Email')
                ->rules(['required']),
            ImportColumn::make('schedule_type')
                ->exampleHeader('Schedule Type')
                ->example('Daily/Live/Hourly')
                ->label('Schedule Type'),
            ImportColumn::make('plant')
                ->requiredMapping()
                ->exampleHeader('Plant Code')
                ->example('1000 or All Plants')
                ->label('Plant Code')
                ->rules(['required']),
            ImportColumn::make('cc_emails')
                ->exampleHeader('CC Email')
                ->example('admin@cripumps.com,ranjith.bala@cripumps.com')
                ->label('CC Email')
                ->rules(['nullable', 'string']),
                //->rules(['cc_emails']),
            // ImportColumn::make('invoiceMaster')
            //     ->relationship(),
            ImportColumn::make('receiving_plant_name')
                ->exampleHeader('Receiving Plant Name')
                ->example('BANGALORE')
                ->label('Receiving Plant Name')
                ->requiredMapping(),
            ImportColumn::make('transporter_name')
                ->exampleHeader('Transporter Name')
                ->example('SAFEXPRESS PRIVATE LIMITED')
                ->label('Transporter Name')
                ->requiredMapping(),
        ];
    }

    public function resolveRecord(): ?AlertMailRule
    {
        $warnMsg = [];

        $user = Filament::auth()->user();

        $operatorName = $user->name;

        if (strtolower($this->data['plant']) == 'all plants') {
            $this->data['plant'] = 0;
        } else {
            $plant = Plant::where('code', $this->data['plant'])->first();
            if (!$plant) {
                $warnMsg[] = "Plant code '{$this->data['plant']}' not found.";
                $this->data['plant'] = null;
            } else {
                $this->data['plant'] = $plant->id;
            }
        }

        $receivingPlantName = $this->data['receiving_plant_name'] ?? null;
        $transporterName = $this->data['transporter_name'] ?? null;

        if (!$receivingPlantName || !$transporterName)
        {
            $warnMsg [] = 'Both Receiving Plant Name and Transporter Name are required.';
        }

        $invoiceMaster = \App\Models\InvoiceMaster::where('receiving_plant_name', $receivingPlantName)
            ->where('transport_name', $transporterName)
            ->first();

        if (!$invoiceMaster) {
            $warnMsg [] = "Invoice Master not found for Receiving Plant '{$receivingPlantName}' and Transporter '{$transporterName}'.";
        }

        $this->data['invoice_master_id'] = $invoiceMaster->id;

        unset($this->data['receiving_plant_name'], $this->data['transporter_name']);

        if(! empty($warnMsg)){
            throw new RowImportFailedException(implode(', ', $warnMsg));
        }

        return AlertMailRule::Create([
            'module'            => $this->data['module'],
            'rule_name'         => $this->data['rule_name'],
            'email'             => $this->data['email'],
            'schedule_type'     => $this->data['schedule_type'],
            'plant'             => $this->data['plant'],
            'cc_emails'         => $this->data['cc_emails'] ?? null,
            'invoice_master_id' => $invoiceMaster->id,
            'created_by'        => $operatorName,
            'updated_by'        => $operatorName,
        ]);

        //return new AlertMailRule();
    }

    public static function getCompletedNotificationBody(Import $import): string
    {
        $body = 'Your alert mail rule import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.';

        if ($failedRowsCount = $import->getFailedRowsCount()) {


            $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.';
        }

        return $body;
    }
}
