<?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\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 ImportInventory implements ToModel , WithStartRow , SkipsOnError, SkipsOnFailure ,WithProgressBar
{
    use Importable ,SkipsErrors ,SkipsFailures ;
    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function startRow(): int
    {
        return 2;
    }
    public function model(array $row)
    {      
        /*var_dump($row[0]);
        die('s');
        */
        //Category
        /*$Category = (object)'';
        if(isset($row[0]) && !empty($row[0])){
            $Category = Category::select('id')->where(['name' => $row[0]])->first();
            if(!$Category){
                session(['error' => 'No Category Found on records!']);
                return null;
            }
        }else{
            $Category->id = null;
        }*/
           // dd($row[1]);
        //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;
        }

        /*var_dump($Carmodel->id);
        die('s');*/

        //Carvarient
        $Carvarient = (object)'';
        if(isset($row[2]) && !empty($row[2])){
            $Carvarient = Carvarient::select('id')->where(['name' => $row[2]])->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[4]) && !empty($row[4])){
            $Interiorcolor = Interiorcolor::select('id')->where(['name' => $row[4]])->where('status', 'active')->first();
            if(!$Interiorcolor){
                session(['error' => 'No Interiorcolor Found on records!']);
                return null;
            }
        }else{
            $Interiorcolor->id = null;
        }

        //Exteriorcolor
        $Exteriorcolor = (object)'';
        if(isset($row[3]) && !empty($row[3])){
            $Exteriorcolor = Exteriorcolor::select('id')->where(['name' => $row[3]])->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[12])){
            $fuel = Fuletype::select('id')->where(['title' => $row[12]])->first();

            if(!$fuel){
                session(['error' => 'No Fuel Type Found on records!']);
                return null;
            }
        }else{
            $fuel->id = null;
        }
        /*var_dump($row);
        die('s');*/

        // $exist_data = Inventory::select('id')->where(['name' => $Product->id,'branch_id' => $branch->id,'status' => 'active'])->first();
        $exist_data = Inventory::select('id')->where(['vin_number' => $row[8],'status' => 'active'])->first();
        
        $aging_days = null;
        if (!empty($row[5])) { // Assuming $row[5] is the kin_invoice_date
            $dateFrom = Carbon::parse($row[5]);
            $dateTo = Carbon::now();
            $aging_days = $dateFrom->diffInDays($dateTo);
        }
                       
       $data = [];
       if($exist_data){
           // session(['error' => 'Some Inventory is already available on records!']);
        $dateInfo = $this->getFormattedDate($row[5]);
        $exist_data->name = $Product->id;
        $exist_data->branch_id = $branch->id;
        $exist_data->fuel_type = $fuel->id;
        // $exist_data->kin_invoice_date = date("Y-m-d",strtotime($row[5]));
        $exist_data->kin_invoice_date = $dateInfo['formatted_date'];
        $exist_data->key_number = $row[6];
        $exist_data->engine_number = $row[7];
        //$exist_data->chassis_number = $row[8];
        $exist_data->vin_number = $row[8];
        $exist_data->ex_showroom_price = $row[9];
        $exist_data->purchase_price = $row[10];
        $exist_data->kin_margin = $row[11];        
        $exist_data->inventory_type = $row[12];        
        $exist_data->remark = $row[13]; 
        // $exist_data->aging_days = $aging_days;
        $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();
        // die('sss');
           // return null;
       }else{  
        $dateInfo = $this->getFormattedDate($row[5]);
        $data = [            
            //'category_id' => $Category->id,
            'name' => $Product->id,
            'branch_id' => $branch->id,
            'fuel_type' => $fuel->id,
            // 'kin_invoice_date' => $this->getFormattedDate($row[5]),
            'kin_invoice_date' => $dateInfo['formatted_date'],
            'key_number' => $row[6],
            'engine_number' => $row[7],
            //'chassis_number' => $row[8],
            'vin_number' => $row[8],
            'ex_showroom_price' => $row[9],   
            'purchase_price' => $row[10], 
            'kin_margin' => $row[11],  
            // 'aging_days' => $aging_days,   
            'aging_days' => $dateInfo['aging_days'],
            '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
        ];

        }

        // die('sto[p');

        /*var_dump($data);
        die('s');*/
        
        /*$obf = Inventory::create($data);
        session(['success' => 'Record Imported Succesfully']);
        return $obf;*/

        $Inventory = [];
        if(!empty($data)){
             $Inventory = Inventory::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,
        ];
    }

} 
