<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
use GuzzleHttp\Client;
class EANGenerator {
    private $client;
    public function __construct() {
        $this->client = new Client();
    }
    public function generateEansInExcel($filePath) {
        $spreadsheet = IOFactory::load($filePath);
        $sheet = $spreadsheet->getActiveSheet();
        $row = 2;
        while (true) {
            $title = $sheet->getCell('A' . $row)->getValue();
            
            if (!$title) {
                break;
            }
            $ean = $this->generateEanFromApi($title);
            if ($ean) {
                $sheet->setCellValue('B' . $row, $ean);
                echo "EAN за ред $row: $ean\n";
            } else {
                echo "Грешка при генериране на EAN за ред $row\n";
            }
            $row++;
        }
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save($filePath);
        echo "Обработката на файла приключи. Всички EAN кодове са добавени.\n";
    }
    private function generateEanFromApi($title) {
        $response = $this->client->post('https://api.openai.com/v1/engines/gpt-3.5-turbo/completions', [
            'headers' => [
                'Authorization' => 'Bearer YOUR_API_KEY',
                'Content-Type' => 'application/json',
            ],
            'json' => [
                'prompt' => "Generate a unique 13-digit EAN code for product: \"$title\".",
                'max_tokens' => 10,
            ],
        ]);
        $data = json_decode($response->getBody(), true);
        if (isset($data['choices'][0]['text'])) {
            return trim($data['choices'][0]['text']);
        }
        return null;
    }
}
$eanGenerator = new EANGenerator();
$eanGenerator->generateEansInExcel('data.xlsx');