theloftstore/public/userarea/import_save.php

77 lines
3.0 KiB
PHP

<?php
include('include/headscript.php');
require_once(__DIR__ . '/class/db-functions.php'); // usa la tua classe PDO
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
// Ottieni dati dal POST
$rows = isset($_POST['rows']) ? json_decode($_POST['rows'], true) : [];
$idclient = isset($_POST['idclient']) ? intval($_POST['idclient']) : null;
// Recupera utente loggato
$iduser = $_SESSION['iduserlogin'] ?? null;
if (!$rows || !is_array($rows) || count($rows) === 0) {
echo json_encode(['status' => 'error', 'message' => 'No rows to import.']);
exit;
}
if (empty($idclient)) {
echo json_encode(['status' => 'error', 'message' => 'Client not specified.']);
exit;
}
try {
$pdo->beginTransaction();
$sql = "
INSERT INTO importdb
(collection, category, model, model_description, mod_code, description, finish_code, finishing_description, available_qty, wh, price, source_file, iduser, idclient)
VALUES
(:collection, :category, :model, :model_description, :mod_code, :description, :finish_code, :finishing_description, :available_qty, :wh, :price, :source_file, :iduser, :idclient)
ON DUPLICATE KEY UPDATE
collection = VALUES(collection),
category = VALUES(category),
model = VALUES(model),
model_description = VALUES(model_description),
description = VALUES(description),
finish_code = VALUES(finish_code),
finishing_description = VALUES(finishing_description),
available_qty = VALUES(available_qty),
wh = VALUES(wh),
price = VALUES(price),
updated_on = CURRENT_TIMESTAMP()
";
$stmt = $pdo->prepare($sql);
foreach ($rows as $r) {
if (isset($r['avalable_qty']) && !isset($r['available_qty'])) {
$r['available_qty'] = $r['avalable_qty'];
}
$stmt->execute([
':collection' => $r['collection'] ?? null,
':category' => $r['category'] ?? null,
':model' => $r['model'] ?? null,
':model_description' => $r['model_description'] ?? null,
':mod_code' => $r['mod_code'] ?? null,
':description' => $r['description'] ?? null,
':finish_code' => $r['finish_code'] ?? null,
':finishing_description' => $r['finishing_description'] ?? null,
':available_qty' => is_numeric($r['available_qty']) ? intval($r['available_qty']) : null,
':wh' => $r['wh'] ?? null,
':price' => isset($r['price']) && is_numeric($r['price']) ? floatval($r['price']) : null,
':source_file' => basename($_POST['source_file'] ?? 'upload.xlsx'),
':iduser' => $iduser,
':idclient' => $idclient
]);
}
$pdo->commit();
echo json_encode(['status' => 'ok', 'message' => count($rows) . ' rows imported/updated.']);
} catch (Exception $e) {
$pdo->rollBack();
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}