getConnection(); $rows = json_decode($_POST['rows'] ?? '[]', true); $idclient = intval($_POST['idclient'] ?? 0); if (!$idclient) { throw new Exception('Missing idclient.'); } if (empty($rows) || !is_array($rows)) { throw new Exception('No rows provided.'); } // Recupera il SOURCE_ID del listino $stmt = $pdo->prepare(" SELECT source_id FROM client_files WHERE idclient = :idclient AND file_type = 'pricelist' AND source_id IS NOT NULL ORDER BY upload_date DESC LIMIT 1 "); $stmt->execute([':idclient' => $idclient]); $sourceId = $stmt->fetchColumn(); if (!$sourceId) { throw new Exception('No valid pricelist (source_id) found for this client.'); } // Helper format codice $formatRef = function (string $modCode): ?string { $code = preg_replace('/\s+/', '', strtoupper($modCode)); if (strlen($code) < 12) return null; $core = substr($code, 3, -2); if (strlen($core) < 7) return null; return substr($core, 0, 3) . ' ' . substr($core, 3, 2) . ' ' . substr($core, 5, 2); }; // Helper estrazione prezzo $extractPrice = function (string $text): ?float { if (preg_match('/(\d{1,6}[.,]\d{2})/', $text, $m)) { $num = str_replace(',', '.', $m[1]); return floatval($num); } return null; }; $chatpdf = new ChatPDFHelper(); $updated = 0; $results = []; $pdo->beginTransaction(); foreach ($rows as $r) { $modCode = $r['mod_code'] ?? ''; $rowId = $r['id'] ?? 0; if (!$modCode) { $results[] = ['id' => $rowId, 'mod_code' => $modCode, 'status' => 'skip']; continue; } $formattedRef = $formatRef($modCode); if (!$formattedRef) { $results[] = ['id' => $rowId, 'mod_code' => $modCode, 'status' => 'invalid_format']; continue; } $question = "In this price list, find the price in euros for the code reference: {$formattedRef}. Return only the number (e.g. 123,45)."; $answer = $chatpdf->askPdf($sourceId, $question); $price = $extractPrice($answer ?? ''); if ($price) { $stmtU = $pdo->prepare(" UPDATE importdb SET price = :price, updated_on = NOW() WHERE mod_code = :code AND idclient = :idclient "); $stmtU->execute([ ':price' => $price, ':code' => $modCode, ':idclient' => $idclient ]); if ($stmtU->rowCount() > 0) { $updated++; $results[] = [ 'id' => $rowId, 'mod_code' => $modCode, 'status' => 'updated', 'price' => $price ]; } } else { $results[] = [ 'id' => $rowId, 'mod_code' => $modCode, 'status' => 'notfound', 'answer' => $answer ]; } } $pdo->commit(); ob_clean(); echo json_encode(['status' => 'ok', 'updated' => $updated, 'details' => $results], JSON_UNESCAPED_UNICODE); } catch (Exception $e) { if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); } ob_clean(); echo json_encode(['status' => 'error', 'message' => $e->getMessage()], JSON_UNESCAPED_UNICODE); } exit;