<?php

namespace App\Services;

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

class ProjectImportService
{
    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 (Company Name, Contact Person, Mobile)
                if (empty($row[0]) || empty($row[1]) || empty($row[2])) {
                    $errors[] = "Row {$rowNumber}: Missing required fields (Company Name, Contact Person, or Mobile)";
                    continue;
                }

                $project = Project::create([
                    'company_name' => $row[0],
                    'contact_person' => $row[1],
                    'mobile' => $row[2],
                    'purpose' => $row[3] ?? null,
                    'deadline' => isset($row[4]) ? date('Y-m-d', strtotime($row[4])) : null,
                    'status' => $row[5] ?? 'ongoing',
                    'notes' => $row[6] ?? null,
                    'created_by' => $createdBy,
                ]);

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

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

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