<?php

namespace App\Imports;

use DB;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Branch;
use App\Models\Target;
use App\Models\Fuletype;
use App\Models\Carmodel;
use App\Models\Teammaster;
use Illuminate\Support\Arr;
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;

class ImportTarget implements ToModel , WithStartRow , SkipsOnError, SkipsOnFailure ,WithProgressBar {

    use Importable ,SkipsErrors ,SkipsFailures ;

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

    public function model(array $row)
    {
        /** branch_id */

        $branch = (object)'';
        if(isset($row[1]) && !empty($row[1])){
            $branch = Branch::select('id')->where(['name' => $row[1]])->first();
            if(!$branch){
                session(['error' => 'No branch found on records!']);
                return null;
            }
        } else {
            $branch->id = null;
        }
        
        
        /** Carmodel */
        
        $Carmodel = (object)'';
        if(isset($row[4]) && !empty($row[4])) {
            $Carmodel = Carmodel::select('id')->where(['name' => $row[4]])->where('status', 'active')->first();
            if(!$Carmodel){
                session(['error' => 'No car model found on records!']);
                return null;
            }
        } else {
            $Carmodel->id = null;
        }
        

        /** fuel type */

        $fuel = (object)'';
        if(isset($row[5]) && !empty($row[5])){
            $fuel = Fuletype::select('id')->where(['title' => $row[5]])->first();
            if(!$fuel){
                session(['error' => 'No fuel type found on records!']);
                return null;
            }
        } else {
            $fuel->id = null;
        }
        
        
        /** TL */

        $team_leader = (object)'';
        if(isset($row[6]) && !empty($row[6])){
            $team_leader = Teammaster::select('id')->where(['team_name' => $row[6]])->first();
            if(!$team_leader){
                session(['error' => 'No team leader found on records!']);
                return null;
            }
        } else {
            $team_leader->id = null;
        }
        
        
        /** KEC */
        
        $kec = (object)'';
        if(isset($row[7]) && !empty($row[7])){
            $name = trim($row[7]);
            $kec = User::select('id')
            ->where(function ($query) use ($name) {
                $query->where('first_name', 'LIKE', "%$name%")
                      ->orWhere('last_name', 'LIKE', "%$name%")
                      ->orWhereRaw("CONCAT(first_name,' ',last_name) LIKE ?", ["%$name%"]);
            })->first();
            if(!$kec){
                session(['error' => 'No kec found on records!']);
                return null;
            }
        } else {
            $kec->id = null;
        }
        
        $dateInfo = $this->getFormattedDate($row[0]);
        $exist_data = Target::where('target_type', $row[2])->where('model', $Carmodel->id)->where('fuel_type', $fuel->id)->where('date', $dateInfo['formatted_date'])->whereNull('deleted_at')->first(); 

        $data = [];

        if($exist_data){
            $dateInfo = $this->getFormattedDate($row[0]);
            $exist_data->date = $dateInfo['formatted_date'];
            $exist_data->target_type = $row[2];
            $exist_data->branch = $branch->id;
            $exist_data->model = $Carmodel->id;
            $exist_data->fuel_type = $fuel->id;
            $exist_data->target_value = $row[3];
            $exist_data->team_id = $team_leader->id;
            $exist_data->kec_name = $kec->id;
            $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[0]);
            $data = [
                'date' => $dateInfo['formatted_date'],
                'target_type' => $row[2],
                'branch' => $branch->id,
                'model' => $Carmodel->id,
                'fuel_type' => $fuel->id,
                'target_value' => $row[3],
                'team_id' => $team_leader->id,
                'kec_name' => $kec->id, 
                '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
            ];
        }
        
        $target = [];
        if(!empty($data)){
            $target = Target::create($data);
        }
        return $target;
    }

    public function rules(): array{
        return [
            '*.10' => ['email' ,'unique:users,email']
        ];
    }

    private function getFormattedDate($date){
        try {
            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)) {
                    $formattedDate = Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($date))->format('Y-m-d');
                }

                if ($formattedDate) {
                    $dateFrom = Carbon::parse($formattedDate);
                    $dateTo = Carbon::now();
                    return [
                        'formatted_date' => $formattedDate,
                    ];
                }
            }
        } catch (\Exception $e) {
            dd($e);
        }

        return [
            'formatted_date' => null,
        ];
    }
} 