<?php

namespace App\Imports;

use App\Schedule;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class ImportSchedule implements ToModel, WithStartRow
{
    private $data; 
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */

    public function __construct(array $data = [])
    {
        $this->data = $data; 
    }


    public function model(array $row)
    {

        // dd($this->data['user_id']);
        // dd(Carbon::parse($row[1])->format('Y-m-d H:i:s'));
        // dd(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[1])->format("Y-m-d H:i:s"));
        $tgl = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[1])->format("Y-m-d");
        $time = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[2])->format("H:i:s");
        $time2 = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[3])->format("H:i:s");
        // dd(date('Y-m-d H:i:s', strtotime("$tgl $time")));
        if($time > $time2){
            $tgl2 = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[1])->modify('+1 day')->format("Y-m-d");
        }else{
            $tgl2 = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[1])->format("Y-m-d");
        };
        $start = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[1])->format("Y-m-d H:i:s");

        $schedule = Schedule::where('start', $start)->where('user_id', $this->data['user_id'])->get();
        
        if($schedule->count() < 1){
                return new Schedule([
                                'title' => $row[0],
                                'start' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[1])->format("Y-m-d H:i:s"),
                                'end' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[1])->modify('+1 day')->format("Y-m-d H:i:s"),
                                'start_plot' => date('Y-m-d H:i:s', strtotime("$tgl $time")),
                                'end_plot' => date('Y-m-d H:i:s', strtotime("$tgl2 $time2")),
                                'user_id' => $this->data['user_id'],
                                'partner_id' => $this->data['partner_id'],            
                ]);
            }
    }
    public function startRow(): int
    {
        return 2;
    }
}