<?php

namespace App\Imports;

use App\Models\Teammaster;
use App\Models\Carmodel;
use App\Models\Branch;
use App\Models\Department;
use App\Models\Carvarient;
use App\Models\pricelist;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use DB;

class ImportPriceList implements ToModel ,WithHeadingRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */

    public function startRow(): int
    {
        return 6;
    }

    public function model(array $row)
    {
        // $branch = (object)'';
        // if(isset($row['branch_name']) && !empty($row['branch_name'])){
        //     $branch = Branch::select('id')->where(['name' => $row['branch_name']])->where(['status' => 'active'])->first();
        //     if(!$branch){
        //         session(['error' => 'No Branch Found In at least one record!']);
        //         return null;
        //     }
        // }else{
        //     $branch->id = null;
        // }
        
        $branch_ids = null;

        if (isset($row['branch_name']) && !empty($row['branch_name'])) {
            // Split multiple branch names by comma
            $branch_names = explode(',', $row['branch_name']);
            $branch_ids_arr = [];
        
            foreach ($branch_names as $branch_name) {
                $branch_name = trim($branch_name);
                $branch = Branch::select('id')
                    ->where(['name' => $branch_name, 'status' => 'active'])
                    ->first();
        
                if ($branch) {
                    $branch_ids_arr[] = $branch->id;
                } else {
                    session(['error' => "Branch '{$branch_name}' not found in at least one record!"]);
                    return null;
                }
            }
        
            // Join IDs with comma
            if (!empty($branch_ids_arr)) {
                $branch_ids = implode(',', $branch_ids_arr);
            }
        }

        $Carmodel = (object)'';
        if(isset($row['car_model']) && !empty($row['car_model'])){
            $Carmodel = Carmodel::select('id')->where(['name' => $row['car_model']])->where(['status' => 'active'])->first();
            if(!$Carmodel){
                session(['error' => 'No car model Found on records!']);
                return null;
            }
        }else{
            $Carmodel->id = null;
        }

        $fuel_type = (object)'';
        if(isset($row['fuel_type']) && !empty($row['fuel_type'])){
            $fuel_type = DB::table('fule_type')->where(['title' => $row['fuel_type']])->where(['status' => 'active'])->first();
            if(!$fuel_type){
                session(['error' => 'No Fuel Type Found on records!']);
                return null;
            }
        }else{
            $fuel_type->id = null;
        }
        //dd($row);

        $Carvarient = (object)'';
        if(isset($row['car_variant']) && !empty($row['car_variant'])){
            $Carvarient = Carvarient::select('id')->where(['name' => $row['car_variant']])->where(['status' => 'active'])->first();
            if(!$Carvarient){
                session(['error' => 'No Carvarient Found on records!']);
                return null;
            }
        }else{
            $Carvarient->id = null;
        }

        $transmission = (object)'';
        if(isset($row['transmission']) && !empty($row['transmission'])){
            $transmission = DB::table('transmission')->where(['name' => $row['transmission']])->where(['status' => 'active'])->first();
            if(!$transmission){
                session(['error' => 'No transmission Found on records!']);
                return null;
            }
        }else{
            $transmission->id = null;
        }

        $tone_selection = (object)'';
        if(isset($row['tone_selection']) && !empty($row['tone_selection'])){
            $tone_selection = DB::table('colortone')->where(['name' => $row['tone_selection']])->where(['status' => 'active'])->first();
            if(!$tone_selection){
                session(['error' => 'No tone selection Found on records!']);
                return null;
            }
        }else{
            $tone_selection->id = null;
        }


        $fasttags = (object)'';
        if(isset($row['fasttag']) && !empty($row['fasttag'])){
            $fasttags = DB::table('fasttags')->where(['brand_name' => $row['fasttag']])->where(['status' => 'active'])->first();
            if(!$fasttags){
               session(['error' => 'No fasttags Found on records!']);
               return null;
            }
        }else{
           $fasttags->id = null;
        }

        $rsa_master = (object)'';
        if(isset($row['rsa_master']) && !empty($row['rsa_master'])){
            $rsa_master = DB::table('rsa')->where(['name' => $row['rsa_master']])->where(['status' => 'active','car_model'=>$Carmodel->id])->first();
            if(!$rsa_master){
               session(['error' => 'No rsa Found on records!']);
               return null;
            }
        }else{
           $rsa_master->id = null;
        }

        $mcp = (object)'';
        if(isset($row['my_convinience_program']) && !empty($row['my_convinience_program'])){
            $mcp = DB::table('mcp')->where(['name' => $row['my_convinience_program']])->where(['status' => 'active'])->first();
            if(!$mcp){
               session(['error' => 'No my convinience program Found on records!']);
               return null;
            }
        }else{
           $mcp->id = null;
        }

        $extand_warranties = (object)'';
        if(isset($row['extended_warranty']) && !empty($row['extended_warranty'])){
           $extand_warranties = DB::table('extand_warranties')->where(['years' => $row['extended_warranty']])->where(['status' => 'active'])->first();
           if(!$extand_warranties){
               session(['error' => 'No extand warranties Found on records!']);
               return null;
           }
        }else{
           $extand_warranties->id = null;
        }

        $other_one = (object)'';
        $other_one_data_get = null;
        if(isset($row['other_details_1']) && !empty($row['other_details_1'])){

            $row['other_details_1'] = explode(',', $row['other_details_1']);

            $other_one_arr = [];
            if(!empty($row['other_details_1'])){
                foreach ($row['other_details_1'] as $value_new) {
                    $other_one = DB::table('other_one')->where(['name' => $value_new])->first();
                    if(!empty($other_one)){
                      array_push($other_one_arr, @$other_one->id);
                    }
                }
                $other_one_data_get = implode(' ,', $other_one_arr);
            }else{
                $other_one_data_get = null;     
            }
        }else{
           $other_one_data_get = null;
        }

        $other_two = (object)'';
        $other_two_data_get = null;
        if(isset($row['other_details_2']) && !empty($row['other_details_2'])){

            $row['other_details_2'] = explode(',', $row['other_details_2']);

            $other_two_arr = [];
            if(!empty($row['other_details_2'])){
                foreach ($row['other_details_2'] as $value_new) {
                    $other_two = DB::table('other_two')->where(['name' => $value_new])->first();
                    if(!empty($other_two)){
                      array_push($other_two_arr, @$other_two->id);
                    }
                }
                $other_two_data_get = implode(' ,', $other_two_arr);
            }else{
                $other_two_data_get = null;     
            }
        }else{
           $other_two_data_get = null;
        }

        $detail_value_arr_json = '';
        if(isset($row['detail_value']) && !empty($row['detail_value'])){
           $detail_value_arr = [];

           $row['detail_value'] = substr(trim($row['detail_value']), 0, -1);

           $row['detail_value'] = str_replace("Detail-","",$row['detail_value']);
           $row['detail_value'] = str_replace("Value-","",$row['detail_value']);

           $first_arr = explode(',', $row['detail_value']); 

            if(!empty($first_arr)){
                foreach ($first_arr as $value_new) {            
                    $second_arr = explode('and', $value_new);  

                    $detail_value_sub_arr = [];
                    $detail_value_sub_arr['detail_field'] = trim(@$second_arr[0]);
                    $detail_value_sub_arr['value_field'] = trim(@$second_arr[1]);
                    $detail_value_arr[] = $detail_value_sub_arr;
                }

                if(!empty($detail_value_arr)){
                  $detail_value_arr_json = json_encode($detail_value_arr);  
                }else{
                  $detail_value_arr_json = null;
                }
                
            }else{
                 $detail_value_arr_json = null;   
            }
        }else{
           $detail_value_arr_json = null;
        }

        if(isset($row['price_list_name']) && !empty($row['price_list_name'])){
            $exist_data = pricelist::select('id')->where(['price_list_name' => $row['price_list_name'],'status' => 'active'])->first();
                
            $data = [];
            if($exist_data){
                session(['error' => 'Some pricelist is already available on records!']);
            }else{  
                if($row['csd'] == 'Yes' || $row['csd'] == 'yes') {
                    $data = [
                        'price_list_name' => $row['price_list_name'],    
                        'is_csd' => $row['csd'],
                        'rto_type' => $row['rto_type'],
                        'car_model' => $Carmodel->id,
                        'fule_type' => $fuel_type->id,
                        'car_variant' => $Carvarient->id,
                        'rto_custome_handling_charges' => $row['rto_custom_handling_charges'],
                        'colour_type' => $tone_selection->id,
                        // 'branch_id' => $branch->id,
                        'branch_id' => $branch_ids,
                        'transmission' => $transmission->id,
                        'basic' => $row['basic'],
                        'csd_selling_price' => $row['csd_selling_price'] ?? '',
                        'ls_order_amount' => $row['ls_order_amount'] ?? '',
                        'gst_percentage' => $row['gst'],
                        'gst_amount' => $row['gst_amount'],
                        'cess_percentage' => $row['cess'],
                        'cess_amount' => $row['cess_amount'],
                        'registration_individual_charges' => $row['registration_individual_charges'],
                        'insurance' => $row['insurance'],
                        'fasttag' => $fasttags->id,
                        'on_road_individual_charges' => $row['on_road_individual_charges'],
                        'rsa_master' => $rsa_master->id,
                        'extended_warranty' => $extand_warranties->id,
                        'convinience_program' => $mcp->id,
                        'on_road_price_individual' => $row['final_on_road_price_individual'] ?? '',
                        'other_details_1' => $other_one_data_get,
                        'other_details_2' => $other_two_data_get,
                        'detail_value' => $detail_value_arr_json,
                        'status' => 'active',
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s')
                    ]; 
                } else {
                    $data = [
                        'price_list_name' => $row['price_list_name'],    
                        'is_csd' => $row['csd'],
                        'rto_type' => $row['rto_type'],
                        'car_model' => $Carmodel->id,
                        'fule_type' => $fuel_type->id,
                        'car_variant' => $Carvarient->id,
                        'rto_custome_handling_charges' => $row['rto_custom_handling_charges'],
                        'colour_type' => $tone_selection->id,
                        // 'branch_id' => $branch->id,
                        'branch_id' => $branch_ids,
                        'transmission' => $transmission->id,
                        'basic' => $row['basic'],
                        'gst_percentage' => $row['gst'],
                        'gst_amount' => $row['gst_amount'],
                        'cess_percentage' => $row['cess'],
                        'cess_amount' => $row['cess_amount'],
                        'ex_showroom_price' => $row['ex_showroom_price'],
                        'tcs' => $row['tcs'],
                        'registration_individual_charges' => $row['registration_individual_charges'],
                        'registration_corporate_charges' => $row['registration_corporate_charges'],
                        'insurance' => $row['insurance'],
                        'fasttag' => $fasttags->id,
                        'on_road_individual_charges' => $row['on_road_individual_charges'],
                        'on_road_corporate_charges' => $row['on_road_corporate_charges'],
                        'rsa_master' => $rsa_master->id,
                        'extended_warranty' => $extand_warranties->id,
                        'convinience_program' => $mcp->id,
                        'on_road_price_individual' => $row['final_on_road_price_individual'] ?? '',
                        'on_road_price_corporate' => $row['final_on_road_corporate_charges'] ?? '',
                        'other_details_1' => $other_one_data_get,
                        'other_details_2' => $other_two_data_get,
                        'detail_value' => $detail_value_arr_json,
                        'status' => 'active',
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s')
                    ];
                }           
            }
        }

        $pricelist = [];
        if(!empty($data)){
            //dd($data);
             $pricelist = pricelist::create($data);
        }        
        return $pricelist;      
    }
}
