<?php

namespace App\Imports;

use App\Models\Holiday;
use Maatwebsite\Excel\Concerns\ToModel;

use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\SkipsErrors;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Maatwebsite\Excel\Validators\Failure;
use Hash;
use Throwable;
use App\Models\Customer;
use App\Models\CustomerSetting;
use App\Mail\mailmailablesend;
use Mail;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Carbon\Carbon;

class HolidaysImport implements ToModel, WithHeadingRow,SkipsOnError, WithValidation
{
    use Importable, SkipsErrors;
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public $hasData = false;
    public function model(array $row)
    {
        if (!empty($row['occasion'])) {
            $this->hasData = true;            
        }
        $startdate = Carbon::parse($row['startdate']);
        $enddate = Carbon::parse($row['enddate']);

        if ($enddate->lt($startdate)) {
            $this->errors[] = 'The end date for the holiday "' . $row['occasion'] . '" must be greater than or equal to the start date.';
        }
        if($row['backgroundcolor']){
            $primary_color = $row['backgroundcolor'];
        }else{
            $primary_color = "rgba(0, 0, 0, 1)";
        }

        if($row['textcolor']){
            $secondary_color = $row['textcolor'];
        }else{
            $secondary_color = "rgba(0, 0, 0, 1)";
        }

        $isRepetitive = isset($row['is_repetitive']) && strtolower(trim($row['is_repetitive'])) === 'yes' ? 1 : null;
        if (empty($this->errors)) {
            $holiday =  Holiday::create([
                'occasion' => $row['occasion'],
                'startdate' => Carbon::parse($row['startdate']),
                'enddate' => Carbon::parse($row['enddate']),
                'holidaydescription' => $row['holidaydescription'],
                'primaray_color' => $primary_color,
                'secondary_color' => $secondary_color,
                'status' => '1',
                'is_fixed' => $isRepetitive,
            ]);

            return $holiday;
        }

        return null;
    }

    public function rules(): array
    {
        return  [
            '*.occasion' => ['required','string',],
            '*.startdate' => ['required','date', 'after_or_equal:' . now()->format('Y-m-d')],
            '*.enddate' => ['required','date', 'after_or_equal:' . now()->format('Y-m-d')],
            '*.holidaydescription' => ['required'],
            '*.is_repetitive' => ['nullable', Rule::in(['Yes', 'No', 'yes', 'no'])],
        ];


    }
    public function getErrors()
    {
        return $this->errors;
    }

}
