<?php
session_start();
header('Content-Type: application/json');
include '../config/database.php';
$db = new Database();
$conn = $db->getConnection();

$action = $_REQUEST['action']?? 'get';

if($action == 'get'){
    function getTree($conn, $parent_id = 0){
        $stmt = $conn->prepare("SELECT id, parent_id, jabatan, nama_lengkap as nama_pejabat, foto, urutan FROM pengurus_dpw WHERE parent_id =? AND status = 'Aktif' ORDER BY urutan ASC, id ASC");
        $stmt->execute([$parent_id]);
        $data = [];
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            $row['children'] = getTree($conn, $row['id']);
            $data[] = $row;
        }
        return $data;
    }
    $tree = getTree($conn);
    echo json_encode(['status'=>'success', 'data'=>$tree]);
    exit;
}

if($action == 'simpan'){
    $id = $_POST['id'];
    $parent_id = $_POST['parent_id']?? 0;
    $stmt = $conn->prepare("UPDATE pengurus_dpw SET parent_id=?, urutan=? WHERE id=?");
    $stmt->execute([$parent_id, $_POST['urutan'], $id]);
    echo json_encode(['status'=>'sukses', 'message'=>'Struktur berhasil diupdate']);
    exit;
}
?>