<?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 ProductionDataSap 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.production-data-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')
                    ->reactive()
                    ->required()
                    //->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();
                    })
                    ->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('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()
                ->required(),

                 // Add your custom action button here
                 Actions::make([
                    Action::make('send_to_sap')
                        ->label('Send Data to SAP')
                        ->action(function ($set, $get) {
                           $plantId = $get('plant_id');
                           $plantWarehouseCodes = [
                            // plant_id => warehouse_code
                            1 => '110',  // Ransar I
                            2 => '101',  // Ransar II
                            3 => '102',  // Chola Pumps
                            4 => '104',  // Tuff Pumps
                            //5 => '107', //WH-Nark
                            5 => '200', // Go-flex
                            //7 => '301', // Krisgo II
                        ];

                            $year = date('y'); // '25' for 2025
                            $month = date('m'); // '05' for May
                            $transHeadLogId = $this->transHeadLog; //'3256';
                            $lineItemCnt = '1'; //1 hard code
                            $sapOrder = $get('production_order');
                            $itemCode = $this->pItem;
                            $quantity = (string)$get('scanned_quantity');
                            $UOM = $this->pUom;

                            $locationName = '';
                            $lamiCdate = $get('lami_cdate');
                            $serialNumbers = $this->sNums;

                            $warehouseCode = $plantWarehouseCodes[$plantId] ?? null;
                            $finalBatch = $warehouseCode . $year . $month;

                            $batchNumber = $finalBatch;
                            //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(
                                    'sb-eba140ab-74bb-44a4-8d92-70a636940def!b1182|it-rt-dev-cri-stjllphr!b68',
                                    '616d8991-307b-4ab1-be37-7894a8c6db9d$0p0fE2I7w1Ve23-lVSKQF0ka3mKrTVcKPJYELr-i4nE='
                                )
                                ->withBody(json_encode($payload), 'application/json')
                                //->dump()

                                ->post('https://dev-cri-stjllphr.it-cpi004-rt.cfapps.ap11.hana.ondemand.com/http/LA2CRI/GoodsReceiptAgFG', $payload);

                             // dump($response->transferStats->getRequest());

                              //  dd(json_encode($payload, JSON_PRETTY_PRINT));
                              //dd($response->status(), $response->body());

                          // dump($response);

                           $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
                            ProductionQuantity::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);

                               ProductionQuantity::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();
                           }
                            } 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;

        $latestValidation = ProductionQuantity::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);
            return;
        }

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

        $itemId = $latestValidation->item_id;

        $this->pUom = Item::where('id', $itemId)->value('uom');

        $this->sNums = [];

        if(!$this->pUom)
        {
            Notification::make()
            ->title('UOM Not Found')
            ->body('UOM not found for the production order')
            ->icon('heroicon-o-x-circle')
            ->danger()
            ->send();
            $this->dispatch('refreshed', $this->pId, $this->pOrder);
        }
        else
        {
            $latestProduction = ProductionQuantity::where('plant_id', $this->pId)
            ->where('production_order', $this->pOrder)
            ->latest()
            ->first();

            $this->pItem = $latestProduction
                ? Item::where('id', $latestProduction->item_id)->value('code')
                : null;


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

            $this->dispatch('loadItems', $this->pId, $this->pOrder);
        }

    }

    public static function canAccess(): bool
    {
        return Auth::check() && Auth::user()->can('view production data send to sap');
    }

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

