<?php

namespace App\Imports;

use App\Models\Location;
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 LocationsImport 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
            $company_id = ($isSystemAdmin && isset($row['company_id'])) ? $row['company_id'] : $user->company_id;

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

            // Determine customer_id
            $customer_id = null;
            if (isset($row['customer_id'])) {
                $customer_id = $row['customer_id'];
            } elseif (isset($row['customer_name'])) {
                $customer = Customer::where('name', $row['customer_name'])
                    ->where('company_id', $company_id)
                    ->first();
                if ($customer) {
                    $customer_id = $customer->id;
                }
            }

            if (!$customer_id || empty($row['name'])) {
                $this->skippedCount++;
                continue;
            }

            // Check if location already exists
            $existingLocation = Location::where('name', $row['name'])
                ->where('company_id', $company_id)
                ->where('customer_id', $customer_id)
                ->first();

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

            // Create new location
            Location::create([
                'company_id' => $company_id,
                'customer_id' => $customer_id,
                'branch_id' => $row['branch_id'] ?? $user->branch_id,
                'name' => $row['name'],
                'address' => $row['address'] ?? null,
                'city' => $row['city'] ?? null,
                'state' => $row['state'] ?? null,
                'country' => $row['country'] ?? null,
                'postal_code' => $row['postal_code'] ?? null,
                'contact_person' => $row['contact_person'] ?? null,
                'contact_phone' => $row['contact_phone'] ?? null,
                'contact_email' => $row['contact_email'] ?? null,
                'location_type' => $row['location_type'] ?? 'other',
                'latitude' => $row['latitude'] ?? null,
                'longitude' => $row['longitude'] ?? null,
                'google_maps_link' => $row['google_maps_link'] ?? null,
                'notes' => $row['notes'] ?? null,
            ]);

            $this->importedCount++;
        }
    }

    /**
     * Validation rules
     */
    public function rules(): array
    {
        return [
            'name' => 'required|max:255',
            'customer_name' => 'required_without:customer_id',
            'customer_id' => 'required_without:customer_name',
        ];
    }
}
