<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");  
header("Content-Type: application/json");

$tablename = 'KDunitprice'; // ✅ 테이블명 수정

function pipetocomma($str) {
    return str_replace('|', ',', $str);
}

$col1 = $_REQUEST["col1"] ?? '';
$col2 = $_REQUEST["col2"] ?? '';
$col3 = $_REQUEST["col3"] ?? '';
$col4 = $_REQUEST["col4"] ?? '';
$col5 = $_REQUEST["col5"] ?? '';
$col6 = $_REQUEST["col6"] ?? '';

$colarr1 = explode(",", $col1[0]);
$colarr2 = explode(",", $col2[0]);
$colarr3 = explode(",", $col3[0]);
$colarr4 = explode(",", $col4[0]);
$colarr5 = explode(",", $col5[0]);
$colarr6 = explode(",", $col6[0]);

require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();

for ($i = 0; $i < count($colarr1); $i++) {
    if ($colarr1[$i] != '') {
        // 파이프를 콤마로 다시 복원
        $prodcode   = pipetocomma($colarr1[$i]);
        $item_name  = pipetocomma($colarr2[$i]);
        $item_div   = pipetocomma($colarr3[$i]);
        $spec       = pipetocomma($colarr4[$i]);
        $unit       = pipetocomma($colarr5[$i]);
        $unitprice  = str_replace(',', '', pipetocomma($colarr6[$i]));

        $searchtag = $prodcode . ' ' . $item_name . ' ' . $item_div . ' ' . $spec . ' ' . $unit . ' ' . $unitprice;

        try {
            $pdo->beginTransaction();

            $sql = "INSERT INTO {$DB}.{$tablename} 
                    (prodcode, item_name, item_div, spec, unit, unitprice, searchtag)
                    VALUES (?, ?, ?, ?, ?, ?, ?)";

            $stmh = $pdo->prepare($sql);

            $stmh->bindValue(1, $prodcode);
            $stmh->bindValue(2, $item_name);
            $stmh->bindValue(3, $item_div);
            $stmh->bindValue(4, $spec);
            $stmh->bindValue(5, $unit);
            $stmh->bindValue(6, $unitprice);
            $stmh->bindValue(7, $searchtag);

            $stmh->execute();
            $pdo->commit();
        } catch (PDOException $Exception) {
            $pdo->rollBack();
            echo json_encode(["error" => $Exception->getMessage()]);
            exit;
        }
    }
}

echo json_encode(["status" => "success"]);
?>
