<?php

namespace App\Filament\Imports;

use App\Models\Line;
use App\Models\Machine;
use App\Models\Plant;
use App\Models\WorkGroupMaster;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Str;

class MachineImporter extends Importer
{
    protected static ?string $model = Machine::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('name')
                ->requiredMapping()
                ->exampleHeader('Machine')
                ->example(['1600251'])
                ->label('Machine')
                ->rules(['required']),
            ImportColumn::make('work_center')
                ->requiredMapping()
                ->exampleHeader('Work Center')
                ->example('RMGCE001')
                ->label('Work Center')
                ->rules(['required']),
            ImportColumn::make('workGroupMaster')
                ->requiredMapping()
                ->relationship(resolveUsing: 'name')
                ->exampleHeader('Work Group Center')
                ->example(['RMGCGABC'])
                ->label('Work Group Center')
                ->rules(['required']),
            ImportColumn::make('line')
                ->requiredMapping()
                ->relationship(resolveUsing: 'name')
                ->exampleHeader('Line')
                ->example(['4 inch pump line'])
                ->label('Line')
                ->rules(['required']),
            ImportColumn::make('plant')
                ->requiredMapping()
                ->relationship(resolveUsing: 'name')
                ->exampleHeader('Plant')
                ->example(['Ransar Industries-I'])
                ->label('Plant')
                ->rules(['required']),
        ];
    }

    public function resolveRecord(): ?Machine
    {
        $warnMsg = [];
        $plant = Plant::where('name', $this->data['plant'])->first();
        $line = null;
        $machine = $this->data['name'];
        $workCenter = $this->data['work_center'];
        $groupWorkCenter = WorkGroupMaster::where('name', $this->data['workGroupMaster'])->first();
        if (!$plant) {
            $warnMsg[] = "Plant not found!";
        }
        else {
            $groupWorkCenter = WorkGroupMaster::where('name', $this->data['workGroupMaster'])->where('plant_id', $plant->id)->first();
            $line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first();
            if ($line) {
                $grpWrkCnr = $line->no_of_operation;
                if (!$grpWrkCnr || $grpWrkCnr < 1)//Str::length($grpWrkCnr) < 1)
                {
                    $warnMsg[] = "Group work center line not found!";
                }
                else if (!$groupWorkCenter) {
                    $warnMsg[] = "Group work center not found!";
                }
                else {
                    $dupMachine = Machine::where('plant_id', $plant->id)->where('work_center', '!=', $workCenter)->where('name', $machine)->first();
                    if ($dupMachine) {
                        $warnMsg[] = "Duplicate machine name found!";
                    }
                    else {
                        $isValidGroupWork = false;
                        for ($i = 1; $i <= $line->no_of_operation; $i++) {
                            $column = "work_group{$i}_id";
                            if (!empty($line->$column)) {
                                if ($line->$column == $groupWorkCenter->id) {
                                    $isValidGroupWork = true;
                                    break;
                                }
                            }
                        }

                        if (!$isValidGroupWork) {
                            $warnMsg[] = "Group work center does not match with line!";
                        }
                    }
                }
            }
            else
            {
                $warnMsg[] = "Line not found!";
            }
        }

        if (Str::length($machine) <= 0) {
            $warnMsg[] = "Machine name not found!";
        }

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

        Machine::updateOrCreate(
            [
                'plant_id' => $plant->id,
                'work_center' => $workCenter
            ],
            [
                'line_id' => $line->id,
                'name' => $machine,
                'work_group_master_id' => $groupWorkCenter->id
            ]
        );
        return null;
        // // return Machine::firstOrNew([
        // //     // Update existing records, matching them by `$this->data['column_name']`
        // //     'email' => $this->data['email'],
        // // ]);

        // return new Machine();
    }

    public static function getCompletedNotificationBody(Import $import): string
    {
        $body = 'Your machine 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;
    }
}
