<?php

namespace App\Services;

use App\Models\Business;
use PhpOffice\PhpSpreadsheet\IOFactory;

class BusinessImportService
{
    public function importFromExcel($filePath, $teamIds, $createdBy)
    {
        $spreadsheet = IOFactory::load($filePath);
        $worksheet = $spreadsheet->getActiveSheet();
        $rows = $worksheet->toArray();

        $imported = 0;
        $errors = [];

        // Skip header row
        foreach (array_slice($rows, 1) as $index => $row) {
            $rowNumber = $index + 2; 

            try {
                // Validate required fields (Person Name, Company Name)
                if (empty($row[0]) || empty($row[1])) {
                    $errors[] = "Row {$rowNumber}: Missing required fields (person name or company name)";
                    continue;
                }

                $business = Business::create([
                    'person_name' => $row[0],
                    'company_name' => $row[1],
                    'email' => $row[2] ?? '',
                    'mobile' => $row[3] ?? '',
                    'purpose' => $row[4] ?? null,
                    'size' => $row[5] ?? null,
                    'notes' => $row[6] ?? null,
                    'linkedin_url' => $row[7] ?? null,
                    'next_followup_date' => isset($row[8]) ? date('Y-m-d', strtotime($row[8])) : null,
                    'created_by' => $createdBy,
                ]);

                // Optional Assignment
                if (!empty($teamIds)) {
                    $business->assignedTo()->attach($teamIds);
                }

                $imported++;
            } catch (\Exception $e) {
                $errors[] = "Row {$rowNumber}: " . $e->getMessage();
            }
        }

        return [
            'imported' => $imported,
            'errors' => $errors,
        ];
    }
}
