<?php
// ------------------- ذخیره ترتیب -------------------
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action'] ?? '')==='save_order') {
    header('Content-Type: application/json; charset=utf-8');
    $level = (int)($_POST['level'] ?? 0);
    $parent_id = $_POST['parent_id']!=='' ? (int)$_POST['parent_id'] : null;
    $order = $_POST['order'] ?? [];

    try {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("UPDATE Category SET SortOrder=:sort, ParentID=:parent, Level=:level WHERE CategoryID=:id");
        $s=1;
        foreach($order as $id){
            $stmt->execute([':sort'=>$s++, ':parent'=>$parent_id, ':level'=>$level, ':id'=>(int)$id]);
        }
        $pdo->commit();
        echo json_encode(['success'=>true]);
    } catch(Exception $e){
        $pdo->rollBack();
        echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
    }
    exit;
}
