<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");  

$debug = true;  // 디버그 모드 활성화 (운영 시 false로 변경)

$mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';  
$tablename = isset($_REQUEST['tablename']) ? $_REQUEST['tablename'] : '';  

header("Content-Type: application/json");

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

include "_request.php";

// _request.php 에서 전달된 변수:
// $num, $major_category, $seconditem, $model_name, $spec, $finishing_type, $unitprice, 
// $description, $created_at, $updated_at, $update_log, $is_deleted, $savejson
// 그리고 새로 추가된 컬럼들:
$box_width = $_REQUEST['box_width'] ?? '';
$box_height = $_REQUEST['box_height'] ?? '';
$front_bottom_width = $_REQUEST['front_bottom_width'] ?? '';
$rail_width = $_REQUEST['rail_width'] ?? '';
$exit_direction = $_REQUEST['exit_direction'] ?? '';

// 만약 savejson 값이 배열이면 JSON 문자열로 변환
if (is_array($savejson)) {
    $savejson = json_encode($savejson, JSON_UNESCAPED_UNICODE);
}

// 디버그 정보를 응답 배열에 추가하는 함수
function sendDebugResponse($errorMessage, $debugInfo = []) {
    global $debug;
    $response = ["error" => $errorMessage];
    if ($debug && !empty($debugInfo)) {
        $response["debug"] = $debugInfo;
    }
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit;
}

// ================= Model 처리 =================
if ($mode == "modify")  {    
    $update_log = date("Y-m-d H:i:s") . " - " . $_SESSION["name"] . " 수정" . "&#10";
    try {
        $pdo->beginTransaction();
        $sql = "UPDATE " . $DB . ".BDmodels SET 
                    model_name = ?, 
                    major_category = ?, 
                    seconditem = ?, 
                    spec = ?, 
                    finishing_type = ?, 
                    unitprice = ?, 
                    description = ?, 
                    update_log = ?, 
                    savejson = ?,
                    priceDate = ?,
                    check_type = ?,
                    box_width = ?,
                    box_height = ?,
                    front_bottom_width = ?,
                    rail_width = ?,
                    exit_direction = ?
                WHERE num = ? LIMIT 1";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $model_name, PDO::PARAM_STR);
        $stmh->bindValue(2, $major_category, PDO::PARAM_STR);
        $stmh->bindValue(3, $seconditem, PDO::PARAM_STR);
        $stmh->bindValue(4, $spec, PDO::PARAM_STR);
        $stmh->bindValue(5, $finishing_type, PDO::PARAM_STR);
        $stmh->bindValue(6, $unitprice, PDO::PARAM_STR);
        $stmh->bindValue(7, $description, PDO::PARAM_STR);
        $stmh->bindValue(8, $update_log, PDO::PARAM_STR);
        $stmh->bindValue(9, $savejson, PDO::PARAM_STR);
        $stmh->bindValue(10, $priceDate, PDO::PARAM_STR);
        $stmh->bindValue(11, $check_type, PDO::PARAM_STR);
        $stmh->bindValue(12, $box_width, PDO::PARAM_STR);
        $stmh->bindValue(13, $box_height, PDO::PARAM_STR);
        $stmh->bindValue(14, $front_bottom_width, PDO::PARAM_STR);
        $stmh->bindValue(15, $rail_width, PDO::PARAM_STR);
        $stmh->bindValue(16, $exit_direction, PDO::PARAM_STR);
        $stmh->bindValue(17, $num, PDO::PARAM_INT);
        $stmh->execute();
        $pdo->commit();
    } catch (PDOException $Exception) {
        $pdo->rollBack();
        sendDebugResponse($Exception->getMessage(), [
            "sql" => $sql,
            "params" => [
                $model_name, $major_category, $seconditem, $spec, $finishing_type, 
                $unitprice, $description, $update_log, $savejson, $priceDate, 
                $check_type, $box_width, $box_height, $front_bottom_width, $rail_width, 
                $exit_direction,
                $num
            ],
            "phase" => "model modify"
        ]);
    }
} elseif ($mode == "copy")  {
    // 복사 모드: 기존 모델 정보를 그대로 복사하여 새 모델로 INSERT
    $update_log = date("Y-m-d H:i:s") . " - " . $_SESSION["name"] . " 복사" . "&#10";
    try {
        $pdo->beginTransaction();
        $sql = "INSERT INTO " . $DB . ".BDmodels 
                (model_name, major_category, seconditem, spec, finishing_type, unitprice, description, update_log, savejson, priceDate, check_type, box_width, box_height, front_bottom_width, rail_width, exit_direction) 
                VALUES (?, ?, ?, ?, ?,   ?, ?, ?, ?, ?,    ?, ?, ?, ?, ?,   ?)";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $model_name, PDO::PARAM_STR);
        $stmh->bindValue(2, $major_category, PDO::PARAM_STR);
        $stmh->bindValue(3, $seconditem, PDO::PARAM_STR);
        $stmh->bindValue(4, $spec, PDO::PARAM_STR);
        $stmh->bindValue(5, $finishing_type, PDO::PARAM_STR);
        $stmh->bindValue(6, $unitprice, PDO::PARAM_STR);
        $stmh->bindValue(7, $description, PDO::PARAM_STR);
        $stmh->bindValue(8, $update_log, PDO::PARAM_STR);
        $stmh->bindValue(9, $savejson, PDO::PARAM_STR);
        $stmh->bindValue(10, $priceDate, PDO::PARAM_STR);
        $stmh->bindValue(11, $check_type, PDO::PARAM_STR);
        $stmh->bindValue(12, $box_width, PDO::PARAM_STR);
        $stmh->bindValue(13, $box_height, PDO::PARAM_STR);
        $stmh->bindValue(14, $front_bottom_width, PDO::PARAM_STR);
        $stmh->bindValue(15, $rail_width, PDO::PARAM_STR);
        $stmh->bindValue(16, $exit_direction, PDO::PARAM_STR);
        $stmh->execute();
        $pdo->commit();
    } catch (PDOException $Exception) {
        $pdo->rollBack();
        sendDebugResponse($Exception->getMessage(), [
            "sql" => $sql,
            "params" => [
                $model_name, $major_category, $seconditem, $spec, $finishing_type, 
                $unitprice, $description, $update_log, $savejson, $priceDate, 
                $check_type, $box_width, $box_height, $front_bottom_width, $rail_width, $exit_direction
            ],
            "phase" => "model copy"
        ]);
    }
    // 마지막 INSERT된 모델 ID 가져오기 (신규 모델 ID)
    $sql = "SELECT num FROM " . $DB . ".BDmodels ORDER BY num DESC LIMIT 1";
    try {
        $stmh = $pdo->query($sql);
        $rowNew = $stmh->fetch(PDO::FETCH_ASSOC);
        $num = $rowNew["num"];
    } catch (PDOException $Exception) {
        sendDebugResponse($Exception->getMessage(), [
            "sql" => $sql,
            "phase" => "model id select"
        ]);
    }
} elseif ($mode == "insert")  {    
    $update_log = date("Y-m-d H:i:s") . " - " . $_SESSION["name"] . " 등록" . "&#10";    
	
    try {
        $pdo->beginTransaction();
        $sql = "INSERT INTO " . $DB . ".BDmodels 
                (model_name, major_category, seconditem, spec, finishing_type, unitprice, description, update_log, is_deleted, savejson, created_at, updated_at, priceDate, check_type, box_width, box_height, front_bottom_width, rail_width, exit_direction)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $model_name, PDO::PARAM_STR);
        $stmh->bindValue(2, $major_category, PDO::PARAM_STR);
        $stmh->bindValue(3, $seconditem, PDO::PARAM_STR);
        $stmh->bindValue(4, $spec, PDO::PARAM_STR);
        $stmh->bindValue(5, $finishing_type, PDO::PARAM_STR);
        $stmh->bindValue(6, $unitprice, PDO::PARAM_STR);
        $stmh->bindValue(7, $description, PDO::PARAM_STR);
        $stmh->bindValue(8, $update_log, PDO::PARAM_STR);
        $stmh->bindValue(9, 0, PDO::PARAM_INT);
        $stmh->bindValue(10, $savejson, PDO::PARAM_STR);
        $stmh->bindValue(11, $created_at, PDO::PARAM_STR);
        $stmh->bindValue(12, $updated_at, PDO::PARAM_STR);
        $stmh->bindValue(13, $priceDate, PDO::PARAM_STR);
        $stmh->bindValue(14, $check_type, PDO::PARAM_STR);
        $stmh->bindValue(15, $box_width, PDO::PARAM_STR);
        $stmh->bindValue(16, $box_height, PDO::PARAM_STR);
        $stmh->bindValue(17, $front_bottom_width, PDO::PARAM_STR);
        $stmh->bindValue(18, $rail_width, PDO::PARAM_STR);
        $stmh->bindValue(19, $exit_direction, PDO::PARAM_STR);
        $stmh->execute();
        $pdo->commit();
    } catch (PDOException $Exception) {
        $pdo->rollBack();
        sendDebugResponse($Exception->getMessage(), [
            "sql" => $sql,
            "params" => [
                $model_name, $major_category, $seconditem, $spec, $finishing_type, 
                $unitprice, $description, $update_log, 0, $savejson, $created_at, $updated_at, 
                $priceDate, $check_type, $box_width, $box_height, $front_bottom_width, $rail_width, $exit_direction
            ],
            "phase" => "model insert"
        ]);
    }
    // 마지막 INSERT된 모델 ID 가져오기
    $sql = "SELECT num FROM " . $DB . ".BDmodels ORDER BY num DESC LIMIT 1";
    try {
        $stmh = $pdo->query($sql);
        $rowNew = $stmh->fetch(PDO::FETCH_ASSOC);
        $num = $rowNew["num"];
    } catch (PDOException $Exception) {
        sendDebugResponse($Exception->getMessage(), [
            "sql" => $sql,
            "phase" => "model id select"
        ]);
    }
} elseif ($mode == "delete")  {   
    try {
        $pdo->beginTransaction();
        $sql = "UPDATE " . $DB . ".BDmodels SET is_deleted = 1 WHERE num = ?";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $num, PDO::PARAM_INT);
        $stmh->execute();
        $pdo->commit();
    } catch (Exception $ex) {
        $pdo->rollBack();
        sendDebugResponse($ex->getMessage(), [
            "sql" => $sql,
            "params" => [$num],
            "phase" => "model delete"
        ]);
    }

    // === 응답조립 ===
    $response = [
        'success' => true,
        'mode'    => $mode,
        'num'     => $num
    ];
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit;
}

// === 응답조립 ===
$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;