<?php
// /bending/insert.php
// —————————————————————————————
// * 최상단에 절대 빈 줄, BOM, print/echo 금지 *
// —————————————————————————————

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

// JSON 헤더
header('Content-Type: application/json; charset=utf-8');

// 파라미터
$tablename       = $_REQUEST['tablename'] ?? '';
$mode            = $_REQUEST['mode']      ?? '';
$num             = $_REQUEST['num']       ?? 0;

// 폼 데이터 로딩 (_request.php 에서 필요한 변수 세팅)
include $_SERVER['DOCUMENT_ROOT'] . '/bending/_request.php';

// 이미 JSON 문자열로 넘어온 리스트 필드
$inputList       = $_REQUEST['inputList']       ?? '[]';
$bendingrateList = $_REQUEST['bendingrateList'] ?? '[]';
$sumList         = $_REQUEST['sumList']         ?? '[]';
$colorList       = $_REQUEST['colorList']       ?? '[]';
$AList           = $_REQUEST['AList']           ?? '[]';

try {
    $pdo->beginTransaction();
    // === 파일 업로드 처리 (insert, copy, modify) ===    
    // if (!empty($_FILES['upfile']['tmp_name'][0])) {
    //         $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/bending/img/';
    //         $orig      = $_FILES['upfile']['name'][0];
    //         $tmp       = $_FILES['upfile']['tmp_name'][0];
    //         $ext       = pathinfo($orig, PATHINFO_EXTENSION);
    //         $base      = pathinfo($orig, PATHINFO_FILENAME);
    //         $newName   = date('Y_m_d_H_i_s') . "_{$base}.{$ext}";
    //         if (!move_uploaded_file($tmp, $uploadDir . $newName)) {
    //             throw new Exception('파일 업로드 실패');
    //         }
    //         $imgdata = $newName;
    // }
    // === 모드별 DB 처리 ===
    if ($mode === 'modify') {
        $update_log = date('Y-m-d H:i:s') . " - {$_SESSION['name']} " . ($update_log ?? '') . "\n";
        $sql = "UPDATE {$DB}.{$tablename} SET
                  memo=?, item_bending=?, update_log=?, parentnum=?, registration_date=?,
                  itemName=?, material=?, inputList=?, bendingrateList=?,
                  sumList=?, colorList=?, AList=?, item_sep=?, item_spec=?, widthsum=?, model_UA=?, author=?, search_keyword=?,
                  exit_direction=?, front_bottom_width=?, rail_width=?, box_width=?, box_height=? 
                WHERE num=? LIMIT 1";
        $st = $pdo->prepare($sql);
        $st->execute([
            $memo, $item_bending, $update_log, $parentnum, $registration_date,
            $itemName, $material, $inputList, $bendingrateList,
            $sumList, $colorList, $AList, $item_sep, $item_spec,
            str_replace(',', '', $widthsum), $model_UA, $author, $search_keyword,
            $exit_direction, $front_bottom_width, $rail_width, $box_width, $box_height,
            $num
        ]);
    }
    elseif (in_array($mode, ['insert','copy','write'], true)) {
        $update_log = date('Y-m-d H:i:s') . " - {$_SESSION['name']} " . ($update_log ?? '') . "\n";
        $sql = "INSERT INTO {$DB}.{$tablename} (
                  memo, item_bending, update_log, parentnum, registration_date,
                  itemName, material, inputList, bendingrateList,
                  sumList, colorList, AList, item_sep, item_spec, widthsum, model_UA, author, search_keyword,
                  exit_direction, front_bottom_width, rail_width, box_width, box_height
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,      ?, ?, ?, ?, ?,    ?, ?, ?, ?, ?,     ?, ?, ?, ?)";
        $st = $pdo->prepare($sql);
        $st->execute([
            $memo, $item_bending, $update_log, $parentnum, $registration_date,
            $itemName, $material, $inputList, $bendingrateList,
            $sumList, $colorList, $AList, $item_sep, $item_spec,
            str_replace(',', '', $widthsum), $model_UA, $author, $search_keyword,
            $exit_direction, $front_bottom_width, $rail_width, $box_width, $box_height
        ]);
        $num = $pdo->lastInsertId();
    }
    elseif ($mode === 'delete') {
        $st = $pdo->prepare("UPDATE {$DB}.{$tablename} SET is_deleted=1 WHERE num=? LIMIT 1");
        $st->execute([$num]);
        $pdo->commit();
        // 삭제는 rowHtml 없이 즉시 리턴
        echo json_encode([
            'success' => true,
            'mode'    => 'delete',
            'num'     => $num
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
    else {
        throw new Exception("Unknown mode: {$mode}");
    }

    // === 트랜잭션 커밋 ===
    $pdo->commit();

    // === 응답조립 ===
    $response = [
        'success' => true,
        'mode'    => $mode,
        'num'     => $num
    ];

    // delete가 아닐 때만 rowHtml 생성
    $stmt = $pdo->prepare("SELECT * FROM {$DB}.{$tablename} WHERE num = ? LIMIT 1");
    $stmt->execute([$num]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (is_array($row)) {
        extract($row, EXTR_OVERWRITE);
        ob_start();
        include __DIR__ . '/_rowinput.php';
        $response['rowHtml'] = ob_get_clean();
    } else {
        $response['rowHtml'] = '';
    }

    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit;
}
catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
    exit;
}