<?php
session_start();
if(!isset($_SESSION['user_id'])) die('Akses ditolak');
$role = $_SESSION['role'];
?>
<style>
.struktur-wrapper {
    background: #f8f9fc;
    padding: 30px 15px;
    border-radius: 8px;
    min-height: 600px;
    overflow-x: auto;
}
.struktur-tree ul {
    padding-top: 20px;
    position: relative;
    display: flex;
    justify-content: center;
}
.struktur-tree li {
    list-style-type: none;
    text-align: center;
    position: relative;
    padding: 20px 5px 0 5px;
}
/* Garis vertikal */
.struktur-tree li::before, .struktur-tree li::after {
    content: '';
    position: absolute;
    top: 0;
    right: 50%;
    border-top: 2px solid #4e73df;
    width: 50%;
    height: 20px;
}
.struktur-tree li::after {
    right: auto;
    left: 50%;
    border-left: 2px solid #4e73df;
}
/* Hapus garis kiri-kanan untuk anak tunggal */
.struktur-tree li:only-child::after, .struktur-tree li:only-child::before { display: none; }
.struktur-tree li:only-child { padding-top: 0; }
.struktur-tree li:first-child::before, .struktur-tree li:last-child::after { border: 0 none; }
.struktur-tree li:last-child::before { border-right: 2px solid #4e73df; border-radius: 0 5px 0 0; }
.struktur-tree li:first-child::after { border-radius: 5px 0 0 0; }
/* Garis dari parent ke anak */
.struktur-tree ul ul::before {
    content: '';
    position: absolute;
    top: 0;
    left: 50%;
    border-left: 2px solid #4e73df;
    width: 0;
    height: 20px;
}
.struktur-card {
    border: 2px solid #4e73df;
    padding: 10px;
    text-decoration: none;
    color: #333;
    background: #fff;
    display: inline-block;
    border-radius: 8px;
    min-width: 180px;
    box-shadow: 0 3px 6px rgba(0,0,0,0.16);
    transition: all 0.3s;
    position: relative;
}
.struktur-card:hover {
    background: #4e73df;
    color: #fff;
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(78,115,223,0.4);
}
.struktur-card:hover .jabatan { color: #fff; }
.struktur-card img {
    width: 65px;
    height: 65px;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid #4e73df;
    margin-bottom: 8px;
    background: #fff;
}
.struktur-card:hover img { border-color: #fff; }
.struktur-card .nama {
    font-size: 13px;
    font-weight: 700;
    margin-bottom: 2px;
}
.struktur-card .jabatan {
    font-size: 11px;
    color: #858796;
}
.btn-edit-node {
    position: absolute;
    top: -10px;
    right: -10px;
    border-radius: 50%;
    width: 28px;
    height: 28px;
    padding: 0;
    line-height: 28px;
    display: none;
}
.struktur-card:hover .btn-edit-node { display: block; }
</style>

<h1 class="h3 mb-4 text-gray-800">Struktur Organisasi DPW</h1>
<div class="alert alert-info">
    <i class="fa fa-info-circle"></i> Data bagan diambil otomatis dari <b>Pengurus DPW</b>. Klik <i class="fa fa-sitemap"></i> untuk atur atasan.
</div>

<div class="card shadow mb-4">
    <div class="card-header py-3">
        <button class="btn btn-info btn-sm" onclick="loadStruktur()"><i class="fas fa-sync"></i> Refresh</button>
        <button class="btn btn-success btn-sm" onclick="exportStruktur()"><i class="fas fa-download"></i> Export PNG</button>
    </div>
    <div class="card-body struktur-wrapper">
        <div id="chart-container" class="struktur-tree">
            <div class="text-center text-muted py-5">
                <i class="fa fa-spinner fa-spin fa-3x"></i><br><br>Loading struktur...
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalStruktur" tabindex="-1">
<div class="modal-dialog"><div class="modal-content">
    <form id="formStruktur">
    <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">Atur Atasan Langsung</h5>
        <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
    </div>
    <div class="modal-body">
        <input type="hidden" name="id" id="id">
        <input type="hidden" name="action" value="simpan">
        <div class="form-group">
            <label>Nama Pejabat</label>
            <input type="text" id="nama_pejabat" class="form-control" readonly>
        </div>
        <div class="form-group">
            <label>Jabatan</label>
            <input type="text" id="jabatan" class="form-control" readonly>
        </div>
        <div class="form-group">
            <label>Atasan Langsung <span class="text-danger">*</span></label>
            <select name="parent_id" id="parent_id" class="form-control" required>
                <option value="0">- Paling Atas / Ketua -</option>
            </select>
        </div>
        <div class="form-group">
            <label>Urutan Tampil</label>
            <input type="number" name="urutan" id="urutan" class="form-control" value="0">
            <small class="text-muted">0 = paling kiri, angka besar = ke kanan</small>
        </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
        <button type="submit" class="btn btn-primary" id="btnSimpanStruktur"><i class="fa fa-save"></i> Update</button>
    </div>
    </form>
</div></div></div>

<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script>
function loadStruktur(){
    $('#chart-container').html('<div class="text-center text-muted py-5"><i class="fa fa-spinner fa-spin fa-3x"></i><br><br>Loading struktur...</div>');

    $.get('api/struktur_organisasi.php?action=get', function(res){
        if(res.status=='success' && res.data.length > 0){
            function buildHTML(nodes){
                let html = '<ul>';
                nodes.forEach(d => {
                    let imgPath = 'assets/img/pengurus/' + (d.foto || 'default.png');
                    html += `<li>
                        <div class="struktur-card">
                            <?php if($role=='admin_dpw'):?>
                            <button class="btn btn-warning btn-sm btn-edit-node" data-id="${d.id}" title="Atur Atasan">
                                <i class="fa fa-sitemap"></i>
                            </button>
                            <?php endif;?>
                            <img src="${imgPath}" onerror="this.src='assets/img/users/default.png'">
                            <div class="nama">${d.nama_pejabat}</div>
                            <div class="jabatan">${d.jabatan}</div>
                        </div>`;
                    if(d.children && d.children.length > 0){
                        html += buildHTML(d.children);
                    }
                    html += `</li>`;
                });
                html += '</ul>';
                return html;
            }
            $('#chart-container').html(buildHTML(res.data));
        } else {
            $('#chart-container').html('<div class="alert alert-warning text-center"><i class="fa fa-info-circle fa-2x"></i><br><br><b>Belum ada data</b><br>Input dulu di menu "Pengurus DPW"</div>');
        }
    },'json');
}

function exportStruktur(){
    html2canvas(document.querySelector("#chart-container")).then(canvas => {
        let link = document.createElement('a');
        link.download = 'struktur-organisasi-dpw.png';
        link.href = canvas.toDataURL();
        link.click();
    });
}

$(document).on('click', '.btn-edit-node', function(e){
    e.stopPropagation();
    let id = $(this).data('id');
    
    $.get('api/pengurus_dpw.php?action=detail&id='+id, function(res){
        if(res.status=='success'){
            let d = res.data;
            $('#id').val(d.id);
            $('#nama_pejabat').val(d.nama_lengkap);
            $('#jabatan').val(d.jabatan);
            $('#urutan').val(d.urutan);

            $.get('api/pengurus_dpw.php?action=get', function(res2){
                let opt = '<option value="0">- Paling Atas / Ketua -</option>';
                res2.data.forEach(p => {
                    if(p.id!= d.id){
                        opt += `<option value="${p.id}" ${p.id==d.parent_id?'selected':''}>${p.jabatan} - ${p.nama_lengkap}</option>`;
                    }
                });
                $('#parent_id').html(opt);
                $('#modalStruktur').modal('show');
            });
        }
    },'json');
});

$('#formStruktur').submit(function(e){
    e.preventDefault();
    $('#btnSimpanStruktur').html('<i class="fa fa-spinner fa-spin"></i> Menyimpan...').prop('disabled', true);
    $.ajax({
        url:'api/struktur_organisasi.php',
        type:'POST',
        data:$(this).serialize(),
        dataType:'json',
        success:function(res){
            if(res.status=='sukses'){
                $('#modalStruktur').modal('hide');
                Swal.fire('Sukses',res.message,'success');
                loadStruktur();
            } else {
                Swal.fire('Error',res.message,'error');
            }
        },
        complete: function(){
            $('#btnSimpanStruktur').html('<i class="fa fa-save"></i> Update').prop('disabled', false);
        }
    });
});

$(document).ready(function(){
    loadStruktur();
});
</script>