<?php

namespace App\Filament\Pages;

use App\Models\Item;
use App\Models\Plant;
use App\Models\ProductionQuantity;
use App\Models\QualityValidation;
use App\Models\StickerMaster;
use Filament\Facades\Filament;
use Filament\Forms\Components\Actions;
use Filament\Forms\Components\Actions\Action;
use Filament\Forms\Form;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Pages\Page;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;

class DataSendToSap extends Page implements HasForms
{
    use InteractsWithForms;

    public $pId , $pOrder, $pUom, $pItem, $transHeadLog, $sNums = [];

    public $scanned_quantity;

    public array $data = []; //Required to back form state

    protected static ?string $navigationIcon = 'heroicon-o-document-text';
    protected static string $view = 'filament.pages.data-send-to-sap';

    protected static ?string $navigationGroup = 'Send To SAP';

    protected $listeners = ['updateScannedQuantity' => 'setScannedQuantity'];



    public function setScannedQuantity($quantity)
    {
        // Set the scanned_quantity value in the Filament page/form
        $this->scanned_quantity = $quantity;
        $this->form->fill([
            'scanned_quantity' => $quantity,
            'production_order' => $this->pOrder,
            'plant_id' => $this->pId,
        ]);
    }

    public function form(Form $form): Form
    {
        return $form
            ->statePath('data')
            ->schema([
                Select::make('plant_id')
                    ->label('Plant')
                    // ->options(Plant::pluck('name', 'id'))
                    ->options(function (callable $get) {
                        $userHas = Filament::auth()->user()->plant_id;
                        return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
                    })
                    ->reactive()
                    ->required()
                    ->afterStateUpdated(function ($state, $set, callable $get) {
                        $plantId = $get('plant_id');
                        if (!$plantId) {
                            $set('pqPlantError', 'Please select a plant first.');
                            $set('production_order', null);
                            $set('scanned_quantity', null);
                            return;
                        }
                        else {
                            $this->pId = $plantId;
                            $set('production_order', null);
                            $set('scanned_quantity', null);
                            $set('validationError', null);
                            $set('pqPlantError', null);
                        }
                    })
                    ->hint(fn ($get) => $get('pqPlantError') ? $get('pqPlantError') : null)
                    ->hintColor('danger'),

                TextInput::make('production_order')
                ->required()
                ->reactive()
                ->afterStateUpdated(function ($state, $set, callable $get) {
                    $productionOrder = $get('production_order');

                    if (!$productionOrder) {
                        $set('pqproducError', 'Please provide production order.');
                        $set('production_order', null);
                        $set('scanned_quantity', null);
                        $this->dispatch('refreshed', $this->pId, $this->pOrder);

                        return;
                    }
                    else {
                        $this->pOrder = null;
                        $this->dispatch('refreshed', $this->pId, $this->pOrder);
                        $set('scanned_quantity', null);
                        $set('validationError', null);
                        $set('pqproducError', null);
                    }
                })
                ->hint(fn ($get) => $get('pqproducError') ? $get('pqproducError') : null)
                ->hintColor('danger')
                ->extraAttributes([
                    'wire:keydown.enter' => 'processValues($event.target.value)',
                ]),

                TextInput::make('scanned_quantity')
                ->reactive()  // Make it reactive to update when changed
                ->afterStateUpdated(function ($state, $set, $get) {
                    $this->scanned_quantity = $state;
                })
                ->readOnly(),

                 // Add your custom action button here
                 Actions::make([
                    Action::make('send_to_sap')
                        ->label('Send Data to SAP')
                        ->action(function ($set, $get) {
                            $year = date('y'); // '25' for 2025
                            $month = date('m'); // '05' for May
                            $plantId = $get('plant_id');
                            $code = Plant::where('id', $plantId)->value('code');
                            $finalBatch = $year . $month . $code;
                            $transHeadLogId = $this->transHeadLog; //'3256';
                            $lineItemCnt = '1'; //1 hard code
                            $sapOrder = $get('production_order');
                            $itemCode = $this->pItem;
                            $quantity = (string)$get('scanned_quantity');
                            $UOM = $this->pUom;
                            $batchNumber = $finalBatch;
                            $locationName = '';
                            $lamiCdate = $get('lami_cdate');
                            $serialNumbers = $this->sNums;

                           // dd($batchNumber);

                            $currentDateTime = date('j/n/Y h:i:s A');

                            $header = [
                                'Trans_Head_Log_Id' => $transHeadLogId,   //'3256',
                                'Line_Item_Count' => $lineItemCnt,        //'1',
                                'SAP_Order_Number' => $sapOrder,          //'12345678'
                                'Item_Code' => $itemCode,                 //'6458795'
                            ];
                        //    $serialNumbers = ['12024090000142', '12024090000142', '12024090000142'];
                            $Receipt = [
                                // 'Receipt' => [
                                    [
                                        'Quantity' => $quantity, //'1',
                                        'UOM' => $UOM,
                                        'Batch_Number' => $batchNumber,
                                        'Location_Name' => $locationName,
                                        'LAMI_Cdate' => $currentDateTime, //'9/9/2024 10:48:37 AM',
                                        'Serial_Number' => array_map(function ($serial) {
                                            return ['Serial_Number' => $serial];
                                        }, $serialNumbers)
                                    ]
                                // ]
                            ];


                            $payload = [
                                //  ...$header,
                                'Receipt' => $Receipt
                            ];
                        //     dd($payload);

//                         $header = [
//                             'Trans_Head_Log_Id' => '3256',
//                             'Line_Item_Count' => '1',
//                             'SAP_Order_Number' => '12345678',
//                             'Item_Code' => '6458795'
//                         ];
//                         $serialNumbers = ['12024090000142'];
//                         $Receipt = [
//                             // 'Receipt' => [
//                                 [
//                                     'Quantity' => '1',
//                                     'UOM' => 'EA',
//                                     'Batch_Number' => '',
//                                     'Location_Name' => '',
//                                     'LAMI_Cdate' => '9/9/2024 10:48:37 AM',
//                                     'Serial_Number' => array_map(function ($serial) {
//                                         return ['Serial_Number' => $serial];
//                                     }, $serialNumbers)
//                                 ]
//                             // ]
//                         ];


//                         $payload = [
//                             //  ...$header,
//                             'Receipt' => $Receipt
//                         ];
                        // dd($payload);
                            try {
                                // $response = Http::withHeaders([
                                //     'Content-Type' => 'application/json',
                                //     'Trans_Head_Log_Id' => '3256',//$transHeadLogId,
                                //     'Line_Item_Count' => '1', // $lineItemCnt,
                                //     'SAP_Order_Number' => '12345678', //$sapOrder,
                                //     'Item_Code' => '6458795', //$itemCode,
                                // ])
                                $response = Http::withHeaders([
                                    'Content-Type' => 'application/json',
                                    'Trans_Head_Log_Id' => $transHeadLogId,
                                    'Line_Item_Count' => $lineItemCnt,
                                    'SAP_Order_Number' => $sapOrder,
                                    'Item_Code' => $itemCode,
                                ])

                                ->withBasicAuth(
                                    env('SAP_API_USERNAME'),
                                    env('SAP_API_PASSWORD')
                                )
                                ->withBody(json_encode($payload), 'application/json')
                                ->post(env('SAP_API_URL'), $payload);

                           $messageCode = $response->headers()['messagecode'][0] ?? null;

                           if ($messageCode && str_starts_with($messageCode, 'ERROR')) {

                            $cleanError = str_replace('ERROR:|', '', $messageCode);

                            // Update rows where plant_id and production_order match
                            QualityValidation::where('plant_id', $get('plant_id'))
                            ->where('production_order', $get('production_order'))
                            ->update([
                                'sap_msg_status' => 'ERROR',
                                'sap_msg_description' => $cleanError,
                            ]);

                               Notification::make()
                                   ->title('SAP Error')
                                   ->body($cleanError)
                                   ->danger()
                                   ->send();
                                   $this->dispatch('loadItems', $this->pId, $this->pOrder);
                           }
                           else
                           {
                               $messageCode = $response->headers()['messagecode'][0] ?? null;
                               $sapSuccessMsg = str_replace('SUCCESS:|', '', $messageCode);

                               QualityValidation::where('plant_id', $get('plant_id'))
                               ->where('production_order', $get('production_order'))
                               ->update([
                                   'sap_msg_status' => 'SUCCESS',
                                   'sap_msg_description' => $sapSuccessMsg,
                               ]);

                               Notification::make()
                                   ->title('SAP Success')
                                   ->body($sapSuccessMsg)
                                   ->success()
                                   ->send();
                                   $this->dispatch('loadItems', $this->pId, $this->pOrder);
                            }
                            } catch (\Exception $e) {
                                Notification::make()
                                    ->title('Exception')
                                    ->body('Error sending data to SAP: ' . $e->getMessage())
                                    ->danger()
                                    ->send();
                            }
                                            })
                        ->color('success')
                        ->outlined()
                        ->hidden(fn (callable $get) => (!$get('scanned_quantity'))) //!$get('plant_id') && !$get('production_order') &&
                        ->extraAttributes(['class' => 'align-to-input']),
                ]),
            ])
            ->columns(4);
    }

    public function processValues($value)
    {

        $this->pOrder = $value;

        $plantId = trim($this->form->getState()['plant_id']) ?? null;
        //$this->plantId = $plantId;


    //    $this->pUom = QualityValidation::where('plant_id',$this->pId)
    //    ->where('production_order',$this->pOrder)
    //    ->latest()
    //    ->first()
    //    ->value('uom');

    //    $this->transHeadLog = QualityValidation::where('plant_id',$this->pId)
    //    ->where('production_order',$this->pOrder)
    //    ->latest()
    //    ->value('id');

    $latestValidation = QualityValidation::where('plant_id', $this->pId)
    ->where('production_order', $this->pOrder)
    ->latest()
    ->first();

    if (!$latestValidation) {
        Notification::make()
            ->title('Invalid Production Order')
            ->body('No data found for the selected plant and production order.')
            ->danger()
            ->send();

        $this->dispatch('refreshed', $this->pId, $this->pOrder);
        $this->pOrder = null;
        $this->form->fill([
                'plant_id' => $this->pId,
                'production_order' => null,
            ]);
        return;
    }

    $this->pUom = $latestValidation->uom;
    $this->transHeadLog = $latestValidation->id;

       $this->sNums = [];

        if(!$this->pUom)
        {
            Notification::make()
            ->title('UOM Not Found')
            ->body('UOM not found for the production order')
            ->icon('heroicon-o-x-circle') // optional, to force red/error-style icon
            ->danger()
            ->send();
            $this->dispatch('refreshed', $this->pId, $this->pOrder);

        }
        else
        {
            $this->pItem = Item::where('id', StickerMaster::where('id', QualityValidation::where('plant_id',$this->pId)->where('production_order',$this->pOrder)->latest()->first()->sticker_master_id)->value('item_id'))->value('code');

            $this->sNums = QualityValidation::where('plant_id', $this->pId)
            ->where('production_order', $this->pOrder)
            ->pluck('serial_number')
            ->toArray();

            //dd($this-> pItem);

          $this->dispatch('loadItems', $this->pId, $this->pOrder);
       }
    }
    public static function canAccess(): bool
    {
        return Auth::check() && Auth::user()->can('view quality data send to sap');
    }

    public static function getNavigationLabel(): string
    {
        return 'Quality Data';
    }
}
