<?php

namespace App\Imports;

use App\Models\Customer;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Illuminate\Support\Facades\Auth;

class CustomersImport implements ToCollection, WithHeadingRow, WithValidation
{
    public $importedCount = 0;
    public $skippedCount = 0;
    public $duplicateCount = 0;

    /**
     * @param Collection $rows
     */
    public function collection(Collection $rows)
    {
        $user = Auth::user();
        $isSystemAdmin = $user->isSystemAdmin();

        foreach ($rows as $row) {
            // Determine company_id:
            // 1. From row if system admin
            // 2. From user's company_id otherwise
            $company_id = ($isSystemAdmin && isset($row['company_id'])) ? $row['company_id'] : $user->company_id;

            if (!$company_id) {
                $this->skippedCount++;
                continue;
            }

            // Verificar si ya existe un cliente con este nombre y correo electrónico en la misma empresa
            $existingCustomer = Customer::where('name', $row['name'])
                ->where('company_id', $company_id)
                ->where(function ($query) use ($row) {
                    if (!empty($row['email'])) {
                        $query->where('email', $row['email']);
                    }
                })
                ->first();

            if ($existingCustomer) {
                $this->duplicateCount++;
                continue;
            }

            // Crear el nuevo cliente
            Customer::create([
                'company_id' => $company_id,
                'branch_id' => $row['branch_id'] ?? $user->branch_id,
                'user_id' => $row['user_id'] ?? $user->id,
                'name' => $row['name'],
                'contact_person' => $row['contact_person'] ?? null,
                'contact_phone' => $row['contact_phone'] ?? null,
                'contact_position' => $row['contact_position'] ?? null,
                'email' => $row['email'] ?? null,
                'phone' => $row['phone'] ?? null,
                'mobile' => $row['mobile'] ?? null,
                'address' => $row['address'] ?? null,
                'city' => $row['city'] ?? null,
                'state' => $row['state'] ?? null,
                'country' => $row['country'] ?? null,
                'postal_code' => $row['postal_code'] ?? null,
                'tax_number' => $row['tax_number'] ?? null,
                'notes' => $row['notes'] ?? null,
                'type' => $row['type'] ?? 'individual',
                'status' => $row['status'] ?? 'active',
                'is_active' => true,
            ]);

            $this->importedCount++;
        }
    }

    /**
     * Reglas de validación
     */
    public function rules(): array
    {
        return [
            'name' => 'required|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|max:20',
            'type' => 'nullable|in:individual,company,government',
            'status' => 'nullable|in:active,inactive,lead,prospect',
            'branch_id' => 'nullable|exists:branches,id',
            'user_id' => 'nullable|exists:users,id',
        ];
    }
}
