<?php

namespace App\Imports;

use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToModel;
use Modules\Sector\Models\Sector;
use Modules\Sector\Models\SectorDescription;
use Modules\Company\Models\Company;
use Modules\Company\Models\CompanyDescription;
use Modules\ContactList\Models\ContactList;
use Modules\ContactList\Models\ContactListDescription;
use Modules\Country\Models\Country;
use Modules\ContactList\Models\ContactListPhone;

class DataImport implements ToModel
{
    /**
     * @param array $row
     *
     * @return User|null
     */
    public function model(array $row)
    {
        // add sector
        // if(is_numeric($row[0]))
        // {
        //     $desc = SectorDescription::where('title',$row['2'])->first();
        //     if(!$desc)
        //     {
        //         $sector = Sector::create();
        //         SectorDescription::create([
        //             'title'=>$row['2'],
        //             'description'=>null,
        //             'sector_id'=>$sector->id,
        //             'language_id'=>2
        //         ]);
        //     }
        // }
        
        //add company
        // if(is_numeric($row[0]))
        // {
        //     $desc = CompanyDescription::where('title',$row['1'])->first();
        //     if(!$desc)
        //     {
        //         $sector_id = SectorDescription::where('title',$row['2'])->first()->sector_id ?? null;
        //         $company = Company::create([
        //             'domain'=>filter_var($row[16], FILTER_VALIDATE_URL) ? $row[16] : null ,
        //             'image'=>'logo.png',
        //             'sector_id'=>$sector_id
        //         ]);
        //         $address = !is_null($row[9]) ? ($row[9] != 'x' ? $row[9] : null) : null ;
        //         $city = !is_null($row[10]) ? ($row[10] != 'x' ? $row[10] : null) : null ;
        //         CompanyDescription::create([
        //             'title'=>$row[1],
        //             'description'=>null,
        //             'address'=>$city .' '. $address,
        //             'company_id'=>$company->id,
        //             'language_id'=>2
        //         ]);
        //     }
        // }
        
        //add contactlist
        // if(is_numeric($row[0]))
        // {
        //     $desc = ContactListDescription::where('title',$row['3'])->first();
            
        //         $company_id = CompanyDescription::where('title',$row['1'])->first()->company_id ?? null;
        //         $code = $this->getCountryCode($row[6]);
        //         $country_id = null;
        //         if($code)
        //         {
        //             $country_id = Country::where('country_key','00'.$code)->first()->id ?? null;
        //         }
        //         $phone = str_replace(' ', '', $row[6]);
        //         $contactList = ContactList::create([
        //             'email'=>filter_var($row[7], FILTER_VALIDATE_EMAIL) ? $row[7] : null ,
        //             'phone'=>is_numeric($phone) ? $phone : null  ,
        //             'is_top_customer'=>0,
        //             'status'=>1,
        //             'company_website'=>filter_var($row[16], FILTER_VALIDATE_URL) ? $row[16] : null ,
        //             'budget'=>$this->parseAmount($row['13']),
        //             'avg_stand_annual'=>$this->parseAmount($row['14']),
        //             'avg_events_annual'=>$this->parseAmount($row['15']),
        //             'role'=>$row['5'],
        //             'note'=>$row['11'],
        //             'company_id'=>$company_id,
        //             'country_id'=>$country_id,
        //         ]);
        //         $address = !is_null($row[9]) ? ($row[9] != 'x' ? $row[9] : null) : null ;
        //         $city = !is_null($row[10]) ? ($row[10] != 'x' ? $row[10] : null) : null ;
        //         ContactListDescription::create([
        //             'title'=>$row[3],
        //             'address'=>$city .' '. $address,
        //             'contact_list_id'=>$contactList->id,
        //             'language_id'=>2
        //         ]);
            
        // }
        if(is_numeric($row[0]))
        {
            $desc = ContactListDescription::where('title',$row['3'])->first();
            if($desc)
            {
                $phones = $this->extractPhones($row[6]);
                if(is_array($phones))
                {
                    foreach($phones as $phone)
                    {
                        ContactListPhone::create([
                            'phone'=>$phone,
                            'contact_list_id'=>$desc->contact_list_id,
                        ]);
                    }
                }
            }
        }
        
    }
    private function extractPhones(?string $cell): ?array
    {
        $cell = trim($cell ?? '');
    
        if ($cell === '' || stripos($cell, 'x') !== false) {
            return null;
        }
    
        preg_match_all('/\+?\d[\d\-\s]{3,}\d/', $cell, $matches);
    
        $phones = [];
    
        foreach ($matches[0] as $match) {
            $clean = preg_replace('/[^\d\+]/', '', $match);
    
            if (strlen($clean) > 15) {
                $chunks = str_split($clean, 12);
                foreach ($chunks as $chunk) {
                    if (strlen($chunk) >= 7) {
                        $phones[] = $chunk;
                    }
                }
            } elseif (strlen($clean) >= 5) {
                $phones[] = $clean;
            }
        }
    
        return empty($phones) ? null : array_values($phones);
    }
    private function getCountryCode($input)
    {
        $input = trim($input);
    
        if ($input === '' || preg_match('/^(X|NA|Private)$/i', $input)) {
            return null;
        }

        if (filter_var($input, FILTER_VALIDATE_EMAIL)) {
            return null;
        }
    
        $clean = preg_replace('/[^0-9+Ee]/', '', $input);
    
        if (preg_match('/[Ee]\+?/', $clean)) {
            $num = (string)(float)$clean;
            $clean = preg_replace('/[^0-9]/', '', $num);
        }
    
        if (preg_match('/^(?:\+|00)?(\d{2,3})/', $clean, $match)) {
            return $match[1];
        }
    
        return null;
    }

    
    private function parseAmount($value)
    {
        $value = trim(strtolower($value));
    
        $value = preg_replace('/[,\.](?=[a-z])/', '', $value);
    
        if (
            $value === '' ||
            preg_match('/^(x|n\/?a|a|b|c|low|high|medium|medium\-?high|various|introduction.*)$/i', $value)
        ) {
            return 0;
        }
    
        if (preg_match('/\d+\s*-\s*\d+/', $value)) {
            return 0;
        }
    
        if (preg_match('/([\d\.]+)\s*(k|mill?ion?|m)\+?/i', $value, $match)) {
            $num = (float)$match[1];
            $unit = strtolower($match[2]);
    
            if ($unit === 'k') {
                return (int)($num * 1000);
            }
    
            if (preg_match('/^m(ill?ion?)?$/', $unit)) {
                return (int)($num * 1000000);
            }
        }
    
        if (is_numeric($value)) {
            return (float)$value;
        }
    
        return 0;
    }
}
