<?php



namespace App\Imports;



use Carbon\Carbon;

use App\Models\Accessory;

use App\Models\Branch;

use App\Models\CarExchange;

use App\Models\ExtandWarranty;

use App\Models\Fasttag;

use App\Models\Finance;

use App\Models\Insurance;

use App\Models\Lead;

use App\Models\OBF;

use App\Models\Product;

use App\Models\Tax;

use App\Models\User;

use App\Models\Inventory;

use App\Models\TransitInventory;

use App\Models\Category;

use App\Models\Fuletype;

use App\Models\Carmodel;

use App\Models\Carvarient;

use App\Models\Interiorcolor;

use App\Models\Exteriorcolor;

use Maatwebsite\Excel\Concerns\ToModel;

use Maatwebsite\Excel\Concerns\Importable;

use Maatwebsite\Excel\Concerns\SkipsErrors;

use Maatwebsite\Excel\Concerns\SkipsFailures;

use Maatwebsite\Excel\Concerns\SkipsOnError;

use Maatwebsite\Excel\Concerns\SkipsOnFailure;

use Maatwebsite\Excel\Concerns\WithStartRow;

use Maatwebsite\Excel\Concerns\WithProgressBar;

use DB;

use Illuminate\Support\Arr;



class ImportTransitInventory implements ToModel , WithStartRow , SkipsOnError, SkipsOnFailure ,WithProgressBar

{

    use Importable ,SkipsErrors ,SkipsFailures ;



    public function startRow(): int

    {

        return 2;

    }

    public function model(array $row)

    {      

        //Carmodel

        $Carmodel = (object)'';

        if(isset($row[1]) && !empty($row[1])){

            $Carmodel = Carmodel::select('id')->where(['name' => $row[1]])->where('status', 'active')->first();

            if(!$Carmodel){

                session(['error' => 'No Carmodel Found on records!']);

                return null;

            }

        }else{

            $Carmodel->id = null;

        }



        //Carvarient

        $Carvarient = (object)'';

        if(isset($row[3]) && !empty($row[3])){

            $Carvarient = Carvarient::select('id')->where(['name' => $row[3]])->where('status', 'active')->first();

            //dd($Carvarient);

            if(!$Carvarient){

                session(['error' => 'No Carvarient Found on records!']);

                return null;

            }

        }else{

            $Carvarient->id = null;

        }



        //Interiorcolor

        $Interiorcolor = (object)'';

        if(isset($row[5]) && !empty($row[5])){

            $Interiorcolor = Interiorcolor::select('id')->where(['name' => $row[5]])->where('status', 'active')->first();

            if(!$Interiorcolor){

                $Interiorcolor->id = null;
                
                // session(['error' => 'No Interiorcolor Found on records!']);

                // return null;

            }

        }else{

            $Interiorcolor->id = null;

        }



        //Exteriorcolor

        $Exteriorcolor = (object)'';

        if(isset($row[4]) && !empty($row[4])){

            $Exteriorcolor = Exteriorcolor::select('id')->where(['name' => $row[4]])->where('status', 'active')->first();

            if(!$Exteriorcolor){

                session(['error' => 'No Exteriorcolor Found on records!']);

                return null;

            }

        }else{

            $Exteriorcolor->id = null;

        }



        //Product

        $Product = (object)'';

        if($Carmodel->id != null && $Carvarient->id != null && $Interiorcolor->id != null && $Exteriorcolor->id != null){

            $Product = Product::select('id')->where(['car_model' => $Carmodel->id,'veriant' => $Carvarient->id,'interior_color' => $Interiorcolor->id,'exterior_color' => $Exteriorcolor->id])->first();

            if(!$Product){

                session(['error' => 'No Product Found on records!']);

                return null;

            }

        }else{

            $Product->id = null;

        }



        //branch_id

        $branch = (object)'';

        if(isset($row[0]) && !empty($row[0])){

            $branch = Branch::select('id')->where(['name' => $row[0]])->first();

            if(!$branch){

                session(['error' => 'No Branch Found on records!']);

                return null;

            }

        }else{

            $branch->id = null;

        }



        //fuel type

        $fuel = (object)'';

        //if(isset($row[14]) && !empty($row[12])){

        if(!empty($row[2])){

            $fuel = Fuletype::select('id')->where(['title' => $row[2]])->first();



            if(!$fuel){

                session(['error' => 'No Fuel Type Found on records!']);

                return null;

            }

        }else{

            $fuel->id = null;

        }



        $exist_data = TransitInventory::select('id')->where(['vin_number' => $row[11],'status' => 'active'])->first();

        

        $aging_days = null;

        if (!empty($row[7])) { // Assuming $row[5] is the kin_invoice_date

            $dateFrom = Carbon::parse($row[7]);

            $dateTo = Carbon::now();

            $aging_days = $dateFrom->diffInDays($dateTo);

        }

                 

        $data = [];

        if($exist_data){

            $dateInfo = $this->getFormattedDate($row[7]);

            $exist_data->name = $Product->id;

            $exist_data->branch_id = $branch->id;

            $exist_data->fuel_type = $fuel->id;

            $exist_data->kin_invoice_no = $row[6];

            $exist_data->kin_invoice_date = $dateInfo['formatted_date'];

            $exist_data->key_number = $row[9];

            $exist_data->engine_number = $row[10];

            $exist_data->vin_number = $row[11];

            $exist_data->purchase_price = $row[12];    

            $exist_data->inventory_type = $row[13];        

            $exist_data->remark = $row[14];

            $exist_data->offer_applicable = $row[15]; 

            $exist_data->manufacturing_year = $row[8];

            $exist_data->aging_days = $dateInfo['aging_days'];

            $exist_data->status = 'active';

            $exist_data->created_at = date('Y-m-d H:i:s');

            $exist_data->created_by = auth()->user()->id;

            $exist_data->updated_at = date('Y-m-d H:i:s');

            $exist_data->updated_by = auth()->user()->id;

            $exist_data->save();

        }else{  

            $dateInfo = $this->getFormattedDate($row[7]);

            $data = [

                'name' => $Product->id,

                'branch_id' => $branch->id,

                'fuel_type' => $fuel->id,

                'kin_invoice_no' => $row[6],

                'kin_invoice_date' => $dateInfo['formatted_date'],

                'key_number' => $row[9],

                'engine_number' => $row[10],

                'vin_number' => $row[11], 

                'purchase_price' => $row[12],

                'aging_days' => $dateInfo['aging_days'],

                'inventory_type' => $row[13],

                'remark' => $row[14],  

                'manufacturing_year' => $row[8],

                'offer_applicable' => $row[15],

                'status' => 'active',

                'created_at' => date('Y-m-d H:i:s'),

                'created_by' => auth()->user()->id,

                'updated_at' => date('Y-m-d H:i:s'),

                'updated_by' => auth()->user()->id

            ];

        }

         

        $Inventory = [];

        if(!empty($data)){

            $Inventory = TransitInventory::create($data);

        }        

        return $Inventory;     

    }





    

    public function rules(): array

    {

        return [

            '*.10' => ['email' ,'unique:users,email']

        ];

    }

    

    

    private function getFormattedDate($date)

    {

        try {

            // Check if the value is not empty and is a valid date string

            if (!empty($date)) {

                $formattedDate = null;

                

                if (\DateTime::createFromFormat('d-m-Y', $date)) {

                    $formattedDate = Carbon::createFromFormat('d-m-Y', $date)->format('Y-m-d');

                } elseif (\DateTime::createFromFormat('d/m/Y', $date)) {

                    $formattedDate = Carbon::createFromFormat('d/m/Y', $date)->format('Y-m-d');

                } elseif (is_numeric($date)) {

                    // Handle Excel numeric date (e.g., 44560)

                    $formattedDate = Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($date))->format('Y-m-d');

                }

    

                // Calculate aging days if the date is successfully formatted

                if ($formattedDate) {

                    $dateFrom = Carbon::parse($formattedDate);

                    $dateTo = Carbon::now();

                    $agingDays = $dateFrom->diffInDays($dateTo);

    

                    // Return both the formatted date and aging days

                    return [

                        'formatted_date' => $formattedDate,

                        'aging_days' => $agingDays,

                    ];

                }

            }

        } catch (\Exception $e) {

            // Log the exception if needed: Log::error($e->getMessage());

        }

    

        // Return nulls if date is not valid

        return [

            'formatted_date' => null,

            'aging_days' => null,

        ];

    }



} 

