<?php

namespace App\Imports;

use App\Models\Contact;
use App\Models\ContactPoint;
use App\Models\Contacttype;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Carbon\Carbon;

class ContactImport implements ToCollection, WithHeadingRow
{
    protected $created = [];
    protected $skipped = [];

    private function extractValue(array $row, array $keys)
    {
        foreach ($keys as $key) {
            if (isset($row[$key])) {
                $v = is_string($row[$key]) ? trim($row[$key]) : $row[$key];
                if (!empty($v)) {
                    return $v;
                }
            }
        }
        return null;
    }

    public function collection(Collection $rows)
    {
        foreach ($rows as $row) {
            $rowArray = $row->toArray();

            $name = $this->extractValue($rowArray, ['name', 'nama', 'contact_name']);
            if (empty($name)) {
                continue;
            }

            // Check duplicate by name
            $exists = Contact::where('name', $name)->exists();
            if ($exists) {
                $this->skipped[] = [
                    'name' => $name,
                    'reason' => 'Already exists'
                ];
                continue;
            }

            // Handle type
            $typeInput = $this->extractValue($rowArray, ['type', 'tipe', 'contact_type', 'jenis_kontak']);
            $typeId = null;

            if ($typeInput) {
                if (is_numeric($typeInput)) {
                    $typeId = $typeInput;
                } else {
                    $contactType = Contacttype::where('name', $typeInput)->first();
                    if ($contactType) {
                        $typeId = $contactType->id;
                    }
                }
            }

            if (!$typeId) {
                $this->skipped[] = [
                    'name' => $name,
                    'reason' => 'Type not found or invalid'
                ];
                continue;
            }

            $data = new Contact;
            $data->name = $name;
            $data->desc = $this->extractValue($rowArray, ['desc', 'deskripsi', 'description']);
            $data->address = $this->extractValue($rowArray, ['address', 'alamat']);
            $data->contact = $this->extractValue($rowArray, ['contact', 'kontak', 'phone', 'telepon']);
            $data->npwp = $this->extractValue($rowArray, ['npwp']);
            $data->bank_account_name = $this->extractValue($rowArray, ['bank_account_name', 'nama_rekening']);
            $data->bank_account_number = $this->extractValue($rowArray, ['bank_account_number', 'nomor_rekening']);
            $data->type = $typeId;

            // Optional fields not strictly required by user but good to have if in excel
            $data->contact_title = $this->extractValue($rowArray, ['contact_title', 'title']);
            $data->contact_email = $this->extractValue($rowArray, ['contact_email', 'email']);

            $data->save();

            // Create ContactPoint
            $contactPoint = new ContactPoint;
            $contactPoint->contact_id = $data->id;
            $contactPoint->total_point = 0;
            $contactPoint->last_updated = Carbon::now()->format('Y-m-d');
            $contactPoint->save();

            $this->created[] = $data;
        }
    }

    public function getResults()
    {
        return [
            'created' => $this->created,
            'skipped' => $this->skipped,
        ];
    }
}
