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

$debug = false ;  // 디버그 모드 활성화 (운영 시 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";

// 디버그 정보를 응답 배열에 추가하는 함수
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 . ".models SET 
                model_name = ?, major_category = ?, finishing_type = ?, description = ?, update_log = ?, guiderail_type = ? 
                WHERE model_id = ? LIMIT 1";
        $stmh = $pdo->prepare($sql);
        $params = [$model_name, $major_category, $finishing_type, $description, $update_log, $guiderail_type, $model_id]; // 마지막에 model_id 적용
        $stmh->execute($params);
        $pdo->commit();
    } catch (PDOException $Exception) {
        $pdo->rollBack();
        sendDebugResponse($Exception->getMessage(), ["sql" => $sql, "params" => $params, "phase" => "model modify"]);
    }
} elseif ($mode == "copy")  {
    // 복사 모드: 기존 모델 정보를 그대로 복사하여 새 모델로 INSERT
    // (모델 수정 화면에서 읽어온 $row 값이 있다고 가정합니다)
    $update_log = date("Y-m-d H:i:s") . " - " . $_SESSION["name"] . " 복사" . "&#10";
    try {
        $pdo->beginTransaction();
        $sql = "INSERT INTO " . $DB . ".models 
                (model_name, major_category, finishing_type, description, update_log, guiderail_type ) 
                VALUES (?, ?, ?, ?, ?, ? )";
        $stmh = $pdo->prepare($sql);
		 $params = [$model_name, $major_category, $finishing_type, $description, $update_log, $guiderail_type];
        $stmh->execute($params);
        $pdo->commit();
    } catch (PDOException $Exception) {
        $pdo->rollBack();
        sendDebugResponse($Exception->getMessage(), ["sql" => $sql, "params" => $params, "phase" => "model copy"]);
    }
    // 마지막 INSERT된 모델 ID 가져오기 (신규 모델 ID)
    $sql = "SELECT model_id FROM " . $DB . ".models ORDER BY model_id DESC LIMIT 1";
    try {
        $stmh = $pdo->query($sql);
        $rowNew = $stmh->fetch(PDO::FETCH_ASSOC);
        $model_id = $rowNew["model_id"];
    } 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 . ".models 
                (model_name, major_category, finishing_type, description, update_log, guiderail_type ) 
                VALUES (?, ?, ?, ?, ?, ?)";
        $stmh = $pdo->prepare($sql);
        $params = [$model_name, $major_category, $finishing_type, $description, $update_log, $guiderail_type];
        $stmh->execute($params);
        $pdo->commit();
    } catch (PDOException $Exception) {
        $pdo->rollBack();
        sendDebugResponse($Exception->getMessage(), ["sql" => $sql, "params" => $params, "phase" => "model insert"]);
    }
    // 마지막 INSERT된 모델 ID 가져오기
    $sql = "SELECT model_id FROM " . $DB . ".models ORDER BY model_id DESC LIMIT 1";
    try {
        $stmh = $pdo->query($sql);
        $rowNew = $stmh->fetch(PDO::FETCH_ASSOC);
        $model_id = $rowNew["model_id"];
    } catch (PDOException $Exception) {
        sendDebugResponse($Exception->getMessage(), ["sql" => $sql, "phase" => "model id select"]);
    }
} elseif ($mode == "delete")  {   
    try {
        $pdo->beginTransaction();
        $sql = "UPDATE " . $DB . ".models SET is_deleted = 1 WHERE model_id = ?";
        $stmh = $pdo->prepare($sql);
        $params = [$model_id];
        $stmh->execute($params);
        $pdo->commit();
    } catch (Exception $ex) {
        $pdo->rollBack();
        sendDebugResponse($ex->getMessage(), ["sql" => $sql, "params" => $params, "phase" => "model delete"]);
    }
}

// ================= 2단계 부품(parts) 처리 =================
if(isset($_POST['part_name']) && is_array($_POST['part_name'])) {
    try {
        $pdo->beginTransaction();
        
        if($mode == "copy") {
            $partCount = count($_POST['part_name']);
            $partMapping = [];
            for($i = 0; $i < $partCount; $i++) {
                $part_name = $_POST['part_name'][$i];
                $spec = $_POST['spec'][$i];
                $unit = $_POST['unit'][$i];
                $quantity = $_POST['quantity'][$i];
                $unitprice = $_POST['unitprice'][$i]; // 추가된 unitprice
                $memo = $_POST['memo'][$i];
                
                $sqlIns = "INSERT INTO " . $DB . ".parts 
                           (model_id, part_name, spec, unit, quantity, unitprice, memo, is_deleted) 
                           VALUES (?, ?, ?, ?, ?, ?, ?, 0)";
                $stmtIns = $pdo->prepare($sqlIns);
                $params = [$model_id, $part_name, $spec, $unit, $quantity, $unitprice, $memo];
                $stmtIns->execute($params);
                $newPartId = $pdo->lastInsertId();
                
                $oldPartId = (isset($_POST['part_id'][$i]) && trim($_POST['part_id'][$i]) !== '') 
                             ? trim($_POST['part_id'][$i]) : '';
                if($oldPartId !== '') {
                    $partMapping[$oldPartId] = $newPartId;
                } else {
                    $partMapping[$i] = $newPartId;
                }
            }
        } else {
            $sql = "SELECT part_id FROM " . $DB . ".parts WHERE model_id = ? AND is_deleted = 0";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$model_id]);
            $existingParts = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
            $submittedParts = [];
            if (isset($_POST['part_id']) && is_array($_POST['part_id'])) {
                foreach ($_POST['part_id'] as $pid) {
                    if (trim($pid) !== '') {
                        $submittedParts[] = $pid;
                    }
                }
            }
            
            foreach ($existingParts as $existingPartId) {
                if (!in_array($existingPartId, $submittedParts)) {
                    $sqlDel = "UPDATE " . $DB . ".parts SET is_deleted = 1 WHERE part_id = ? LIMIT 1";
                    $stmtDel = $pdo->prepare($sqlDel);
                    $stmtDel->execute([$existingPartId]);
                }
            }
            
            $partCount = count($_POST['part_name']);
            for($i = 0; $i < $partCount; $i++) {
                $part_id = isset($_POST['part_id'][$i]) ? trim($_POST['part_id'][$i]) : '';
                $part_name = $_POST['part_name'][$i];
                $spec = $_POST['spec'][$i];
                $unit = $_POST['unit'][$i];
                $quantity = $_POST['quantity'][$i];
                $unitprice = $_POST['unitprice'][$i]; // 추가된 unitprice
                $memo = $_POST['memo'][$i];
                
                if($part_id != '') {
                    $sqlUpd = "UPDATE " . $DB . ".parts 
                               SET part_name = ?, spec = ?, unit = ?, quantity = ?, unitprice = ?, memo = ?, is_deleted = 0 
                               WHERE part_id = ? LIMIT 1";
                    $stmtUpd = $pdo->prepare($sqlUpd);
                    $params = [$part_name, $spec, $unit, $quantity, $unitprice, $memo, $part_id];
                    $stmtUpd->execute($params);
                } else {
                    $sqlIns = "INSERT INTO " . $DB . ".parts 
                               (model_id, part_name, spec, unit, quantity, unitprice, memo, is_deleted) 
                               VALUES (?, ?, ?, ?, ?, ?, ?, 0)";
                    $stmtIns = $pdo->prepare($sqlIns);
                    $params = [$model_id, $part_name, $spec, $unit, $quantity, $unitprice, $memo];
                    $stmtIns->execute($params);
                }
            }
        }
        $pdo->commit();
    } catch (PDOException $e) {
        $pdo->rollBack();
        sendDebugResponse($e->getMessage(), ["phase" => "parts processing"]);
    }
}

// ================= 3단계 하위 부품(parts_sub) 처리 =================
// 하위 부품 데이터는 각 부품별로 제출되며, 부모 부품 ID는 parent_part_id[] 배열로 전달됨
if(isset($_POST['subpart_name']) && is_array($_POST['subpart_name'])) {
    try {
        $pdo->beginTransaction();
        
        if($mode == "copy") {
            $subCount = count($_POST['subpart_name']);
            for($i = 0; $i < $subCount; $i++) {
                $subpart_name = $_POST['subpart_name'][$i] ?? '';
                $material = $_POST['material'][$i] ?? '';
                $bendSum = $_POST['bendSum'][$i] ?? '';
                $plateSum = $_POST['plateSum'][$i] ?? '';
                $finalSum = $_POST['finalSum'][$i] ?? '';
                $unitPrice = $_POST['unitPrice'][$i] ?? '';
                $computedPrice = $_POST['computedPrice'][$i] ?? '';
                $quantity = $_POST['quantity'][$i] ?? '';
                $lineTotal = $_POST['lineTotal'][$i] ?? '';
                $image_url = $_POST['image_url'][$i] ?? '';
                $oldParentPartId = isset($_POST['parent_part_id'][$i]) ? $_POST['parent_part_id'][$i] : '';
                
                if(empty($oldParentPartId) || !isset($partMapping[$oldParentPartId])) {
                    continue;
                }
                $newParentPartId = $partMapping[$oldParentPartId];
                
                $sqlIns = "INSERT INTO " . $DB . ".parts_sub 
                           (part_id, subpart_name, material, bendSum, plateSum, finalSum, unitPrice, computedPrice, quantity, lineTotal, image_url, is_deleted) 
                           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)";
                $stmtIns = $pdo->prepare($sqlIns);
                $params = [$newParentPartId, $subpart_name, $material, $bendSum, $plateSum, $finalSum, $unitPrice, $computedPrice, $quantity, $lineTotal, $image_url];
                $stmtIns->execute($params);
            }
        } else {
            $sql = "SELECT subpart_id FROM " . $DB . ".parts_sub 
                    WHERE part_id IN (SELECT part_id FROM " . $DB . ".parts WHERE model_id = ? AND is_deleted = 0)
                    AND is_deleted = 0";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$model_id]);
            $existingSubparts = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
            $submittedSubparts = [];
            if(isset($_POST['subpart_id']) && is_array($_POST['subpart_id'])) {
                foreach ($_POST['subpart_id'] as $spid) {
                    if(trim($spid) !== '') {
                        $submittedSubparts[] = $spid;
                    }
                }
            }
            
            foreach ($existingSubparts as $existingSubpartId) {
                if (!in_array($existingSubpartId, $submittedSubparts)) {
                    $sqlDel = "UPDATE " . $DB . ".parts_sub SET is_deleted = 1 WHERE subpart_id = ? LIMIT 1";
                    $stmtDel = $pdo->prepare($sqlDel);
                    $stmtDel->execute([$existingSubpartId]);
                }
            }
            
            $subCount = count($_POST['subpart_name']);
            for($i = 0; $i < $subCount; $i++) {
                $subpart_id = isset($_POST['subpart_id'][$i]) ? trim($_POST['subpart_id'][$i]) : '';
                $subpart_name = $_POST['subpart_name'][$i] ?? '';
                $material = $_POST['material'][$i] ?? '';
                $bendSum = $_POST['bendSum'][$i] ?? '';
                $plateSum = $_POST['plateSum'][$i] ?? '';
                $finalSum = $_POST['finalSum'][$i] ?? '';
                $unitPrice = $_POST['unitPrice'][$i] ?? '';
                $computedPrice = $_POST['computedPrice'][$i] ?? '';
                $quantity = $_POST['quantity'][$i] ?? '';
                $lineTotal = $_POST['lineTotal'][$i] ?? '';
                $image_url = $_POST['image_url'][$i] ?? '' ;
                $parent_part_id = isset($_POST['parent_part_id'][$i]) ? $_POST['parent_part_id'][$i] : '';
                
                if(empty($parent_part_id)) {
                    if($debug) {
                        error_log("Skipping subpart at index $i: missing parent_part_id");
                    }
                    continue;
                }
                
                if($subpart_id != '') {
                    $sqlUpd = "UPDATE " . $DB . ".parts_sub 
                               SET subpart_name = ?, material = ?, bendSum = ?, plateSum = ?, finalSum = ?, unitPrice = ?, computedPrice = ?, quantity = ?, lineTotal = ?, image_url = ?, is_deleted = 0 
                               WHERE subpart_id = ? LIMIT 1";
                    $stmtUpd = $pdo->prepare($sqlUpd);
                    $params = [$subpart_name, $material, $bendSum, $plateSum, $finalSum, $unitPrice, $computedPrice, $quantity, $lineTotal, $image_url, $subpart_id];
                    $stmtUpd->execute($params);
                } else {
                    $sqlIns = "INSERT INTO " . $DB . ".parts_sub 
                               (part_id, subpart_name, material, bendSum, plateSum, finalSum, unitPrice, computedPrice, quantity, lineTotal, image_url, is_deleted) 
                               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)";
                    $stmtIns = $pdo->prepare($sqlIns);
                    $params = [$parent_part_id, $subpart_name, $material, $bendSum, $plateSum, $finalSum, $unitPrice, $computedPrice, $quantity, $lineTotal, $image_url];
                    $stmtIns->execute($params);
                }
            }
        }
        $pdo->commit();
    } catch (PDOException $e) {
        $pdo->rollBack();
        sendDebugResponse($e->getMessage(), ["phase" => "parts_sub processing"]);
    }
}


$data = [   
    'model_id' => $model_id,
    'mode' => $mode,
	'subpart_name' => $_POST['subpart_name']
]; 

echo json_encode($data, JSON_UNESCAPED_UNICODE);
?>
