<?php

namespace App\Imports;

use App\Models\CampaignUserList;
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 Throwable;
use App\Models\Customer;
use App\Models\CustomerSetting;
use Exception;
use Illuminate\Support\Facades\Hash;

class CustomerImport implements  ToModel, WithHeadingRow,SkipsOnError, WithValidation
{
    use Importable, SkipsErrors;

    protected $batchName;
    protected $processedEmails = [];

    public function __construct($batchName)
    {
        $this->batchName = $batchName;
    }

    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        $email = $row['email'];

        if (in_array($email, $this->processedEmails)) {
            return null;
        }

        $emailExists = CampaignUserList::where('email', $email)->exists();
        if ($emailExists) {
            throw new Exception('userAlreadyExisted');
        }

        $this->processedEmails[] = $email;

        return CampaignUserList::create([
            'email' => $email,
            'source' => 'Imported',
            'batchName' => $this->batchName,
        ]);
    }


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