<?php
header('Content-Type: application/json; charset=utf-8');
require_once($_SERVER['DOCUMENT_ROOT'].'/session.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/lib/mydb.php');
$pdo = db_connect();

// GET 파라미터 level, id
$level = isset($_GET['level']) ? intval($_GET['level']) : 0;
$id    = isset($_GET['id'])    ? intval($_GET['id']) : 0;

// 여기선 level=1 만 처리한다고 가정
if($level !== 1) {
    echo json_encode(["result"=>"error","msg"=>"Only level=1 copy is implemented"]);
    exit;
}

// 트랜잭션 시작 (복사 도중 에러나면 rollback)
$pdo->beginTransaction();
try {
    // 1) 원본 L1 가져오기
    $sql = "SELECT * FROM {$DB}.category_l1 WHERE id = :id";
    $st  = $pdo->prepare($sql);
    $st->bindValue(':id', $id, PDO::PARAM_INT);
    $st->execute();
    $row_l1 = $st->fetch(PDO::FETCH_ASSOC);
    if(!$row_l1) {
        throw new Exception("원본 L1이 존재하지 않습니다.");
    }

    // 2) 새 L1 생성
    //   예: 이름에 (복사) 접미사 추가
    $newName = $row_l1['name'] . " (복사)";
    $sql = "INSERT INTO {$DB}.category_l1 (name, sortOrder) 
            VALUES (:name, :sortOrder)";
    $st = $pdo->prepare($sql);
    $st->bindValue(':name',      $newName);
    $st->bindValue(':sortOrder', $row_l1['sortOrder'] ?? 0);
    $st->execute();
    $new_l1_id = $pdo->lastInsertId(); // 새 L1의 ID

    // 3) 원본 L2 목록 가져오기
    $sql = "SELECT * FROM {$DB}.category_l2 WHERE parent_id = :pid";
    $st  = $pdo->prepare($sql);
    $st->bindValue(':pid', $id, PDO::PARAM_INT);
    $st->execute();
    $rows_l2 = $st->fetchAll(PDO::FETCH_ASSOC);

    // "구(old)->신(new)" ID 매핑 테이블
    $l2_map_id = []; 

    // 4) L2들 복사
    foreach($rows_l2 as $l2){
        // 새 L2 Insert
        $sql = "INSERT INTO {$DB}.category_l2 (name, parent_id, sortOrder)
                VALUES (:name, :p, :so)";
        $st2 = $pdo->prepare($sql);
        // 이름에 (복사) 붙일지 여부 => 선택
        $copyName = $l2['name'] ;
        $st2->bindValue(':name',    $copyName);
        $st2->bindValue(':p',       $new_l1_id, PDO::PARAM_INT);
        $st2->bindValue(':so',      $l2['sortOrder'] ?? 0, PDO::PARAM_INT);
        $st2->execute();
        $new_l2_id = $pdo->lastInsertId();

        // 구 -> 신 매핑
        $old_l2_id = $l2['id'];
        $l2_map_id[$old_l2_id] = $new_l2_id;
    }

    // 5) 원본 L3 전부 가져오기 (조건: parent_id in (원본 l2 ids))
    //    혹은 l2를 돌면서 l3를 가져와도 됨
    if(!empty($l2_map_id)){
        $old_l2_ids_str = implode(',', array_map('intval', array_keys($l2_map_id)));
        $sql = "SELECT * FROM {$DB}.category_l3 
                WHERE parent_id IN ($old_l2_ids_str)";
        $st = $pdo->prepare($sql);
        $st->execute();
        $rows_l3 = $st->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $rows_l3 = [];
    }

    $l3_map_id = [];

    // 6) L3 복사
    foreach($rows_l3 as $l3){
        $old_parent = $l3['parent_id']; // 원본 l2 id
        if(!isset($l2_map_id[$old_parent])) continue; // 무효
        $new_parent = $l2_map_id[$old_parent]; // 새로 생성된 l2 id
        $copyName = $l3['name'] ;

        $sql = "INSERT INTO {$DB}.category_l3 (name, parent_id, sortOrder)
                VALUES (:name, :p, :so)";
        $st3 = $pdo->prepare($sql);
        $st3->bindValue(':name', $copyName);
        $st3->bindValue(':p',    $new_parent, PDO::PARAM_INT);
        $st3->bindValue(':so',   $l3['sortOrder'] ?? 0, PDO::PARAM_INT);
        $st3->execute();
        $new_l3_id = $pdo->lastInsertId();

        $old_l3_id = $l3['id'];
        $l3_map_id[$old_l3_id] = $new_l3_id;
    }

    // 7) 원본 L4
    $l4_map_id = [];
    if(!empty($l3_map_id)){
        $old_l3_ids_str = implode(',', array_map('intval', array_keys($l3_map_id)));
        $sql = "SELECT * FROM {$DB}.category_l4 
                WHERE parent_id IN ($old_l3_ids_str)";
        $st = $pdo->prepare($sql);
        $st->execute();
        $rows_l4 = $st->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $rows_l4 = [];
    }

    // 8) L4 복사
    foreach($rows_l4 as $l4){
        $old_parent = $l4['parent_id']; 
        if(!isset($l3_map_id[$old_parent])) continue; 
        $new_parent = $l3_map_id[$old_parent];
        $copyName   = $l4['name'] ;

        $sql = "INSERT INTO {$DB}.category_l4 (name, parent_id, sortOrder)
                VALUES (:name, :p, :so)";
        $st4 = $pdo->prepare($sql);
        $st4->bindValue(':name', $copyName);
        $st4->bindValue(':p',    $new_parent, PDO::PARAM_INT);
        $st4->bindValue(':so',   $l4['sortOrder'] ?? 0, PDO::PARAM_INT);
        $st4->execute();
        $new_l4_id = $pdo->lastInsertId();

        $old_l4_id = $l4['id'];
        $l4_map_id[$old_l4_id] = $new_l4_id;
    }

    $pdo->commit(); // 전체 복사 성공
    echo json_encode(["result"=>"ok"]);
} catch(Exception $e){
    $pdo->rollBack();
    echo json_encode(["result"=>"error","msg"=>$e->getMessage()]);
}
