<?php
// /guiderail/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'] . '/guiderail/_request.php';

try {
    $pdo->beginTransaction();

    // === 파일 업로드 처리 (insert, copy, modify) ===
    if (in_array($mode, ['insert','copy','modify'], true)) {
        if (!empty($_FILES['upfile']['tmp_name'][0])) {
            $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/guiderail/images/';
            $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;
        }
        elseif (in_array($mode, ['modify','copy'], true)) {
            // 기존 이미지 유지
            $stmt = $pdo->prepare("SELECT imgdata FROM {$DB}.{$tablename} WHERE num = ? LIMIT 1");
            $stmt->execute([$num]);
            $imgdata = $stmt->fetchColumn() ?: '';
        }
        else {
            $imgdata = '';
        }
    }

    // === 모드별 DB 처리 ===
    if ($mode === 'modify') {
        $update_log = date('Y-m-d H:i:s') . " - {$_SESSION['name']} " . ($update_log ?? '') . "\n";
        $sql = "UPDATE {$DB}.{$tablename} SET
                  registration_date=?, author=?, remark=?, rail_length=?, rail_width=?,
                  firstitem=?, model_UA=?, check_type=?, model_name=?, finishing_type=?,
                  search_keyword=?, imgdata=?, update_log=?
                WHERE num=? LIMIT 1";
        $st = $pdo->prepare($sql);
        $st->execute([
            $registration_date, $author, $remark, $rail_length, $rail_width,
            $firstitem, $model_UA, $check_type, $model_name, $finishing_type,
            $search_keyword, $imgdata, $update_log,
            $num
        ]);
    }
    elseif (in_array($mode, ['insert','copy'], true)) {
        $update_log = date('Y-m-d H:i:s') . " - {$_SESSION['name']} " . ($update_log ?? '') . "\n";
        $sql = "INSERT INTO {$DB}.{$tablename} (
                  registration_date, author, remark, rail_length, rail_width,
                  firstitem, model_UA, check_type, model_name, finishing_type,
                  search_keyword, imgdata, update_log
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $st = $pdo->prepare($sql);
        $st->execute([
            $registration_date, $author, $remark, $rail_length, $rail_width,
            $firstitem, $model_UA, $check_type, $model_name, $finishing_type,
            $search_keyword, $imgdata, $update_log
        ]);
        $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;
} 