<?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 = isset($_GET['level']) ? intval($_GET['level']) : 0;
$id    = isset($_GET['id'])    ? intval($_GET['id'])    : 0;

try {
    // 유효성 검사
    if ($level < 1 || $level > 4) {
        throw new Exception("invalid level");
    }
    if ($id < 1) {
        throw new Exception("invalid id");
    }

    // level에 따라 삭제할 테이블 결정
    switch($level){
        case 1:
            // L1 삭제 → 외래키 CASCADE로 L2/L3/L4도 함께 삭제됨
            $sql="DELETE FROM {$DB}.category_l1 WHERE id=:id";
            break;
        case 2:
            $sql="DELETE FROM {$DB}.category_l2 WHERE id=:id";
            break;
        case 3:
            $sql="DELETE FROM {$DB}.category_l3 WHERE id=:id";
            break;
        case 4:
            $sql="DELETE FROM {$DB}.category_l4 WHERE id=:id";
            break;
    }

    $st = $pdo->prepare($sql);
    $st->bindValue(':id', $id, PDO::PARAM_INT);
    $st->execute();

    // 성공 응답
    echo json_encode(["result" => "ok"]);
} catch(Exception $e) {
    // 오류 응답
    echo json_encode(["result" => "error", "msg" => $e->getMessage()]);
}
