<?php
session_start();
if(!isset($_SESSION['user_id']) || $_SESSION['role']!= 'gembala') die('Akses ditolak');
?>
<div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">Inventaris Gereja</h1>
    <button type="button" class="btn btn-primary btn-sm" onclick="tambahInventaris()">
        <i class="fas fa-plus"></i> Tambah Inventaris
    </button>
</div>

<div class="card shadow mb-4">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-striped" width="100%">
                <thead>
                    <tr>
                        <th width="5%">No</th>
                        <th width="8%">Foto</th>
                        <th>Nama Barang</th>
                        <th>Kategori</th>
                        <th width="10%">Jumlah</th>
                        <th width="10%">Kondisi</th>
                        <th width="12%">Tgl Beli</th>
                        <th width="15%">Harga Beli</th>
                        <th width="10%">Aksi</th>
                    </tr>
                </thead>
                <tbody id="tabelBody"></tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalForm" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Form Inventaris Gereja</h5>
                <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <form id="formData" enctype="multipart/form-data">
                    <input type="hidden" name="id" id="id">
                    <input type="hidden" name="foto_lama" id="foto_lama">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Nama Barang <span class="text-danger">*</span></label>
                                <input type="text" name="nama_barang" class="form-control" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Kategori <span class="text-danger">*</span></label>
                                <select name="kategori" class="form-control" required>
                                    <option value="">- Pilih Kategori -</option>
                                    <option value="Peralatan Ibadah">Peralatan Ibadah</option>
                                    <option value="Sound System">Sound System</option>
                                    <option value="Elektronik">Elektronik</option>
                                    <option value="Furniture">Furniture</option>
                                    <option value="Alat Musik">Alat Musik</option>
                                    <option value="Lainnya">Lainnya</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Jumlah <span class="text-danger">*</span></label>
                                <input type="text" name="jumlah" class="form-control" placeholder="1 Unit" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Kondisi <span class="text-danger">*</span></label>
                                <select name="kondisi" class="form-control" required>
                                    <option value="Baik">Baik</option>
                                    <option value="Rusak Ringan">Rusak Ringan</option>
                                    <option value="Rusak Berat">Rusak Berat</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Tgl Beli</label>
                                <input type="date" name="tgl_beli" class="form-control">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Harga Beli</label>
                        <input type="number" name="harga_beli" class="form-control" placeholder="0">
                    </div>
                    <div class="form-group">
                        <label>Foto Barang</label>
                        <input type="file" name="foto" class="form-control-file" accept="image/*" onchange="previewGambar(this)">
                        <small class="text-muted">Max 2MB. Format: JPG, PNG</small>
                        <div id="preview" class="mt-2"></div>
                    </div>
                    <div class="form-group">
                        <label>Keterangan</label>
                        <textarea name="keterangan" class="form-control" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                <button type="button" class="btn btn-primary" onclick="simpanInventaris()"><i class="fa fa-save"></i> Simpan</button>
            </div>
        </div>
    </div>
</div>

<script>
function loadData(){
    $.get('api/get_inventaris.php', function(res){
        let html = '';
        if(res.data.length == 0){
            html = '<tr><td colspan="9" class="text-center">Belum ada data</td></tr>';
        } else {
            res.data.forEach((d, i) => {
                let badge = d.kondisi == 'Baik'? 'success' : d.kondisi == 'Rusak Ringan'? 'warning' : 'danger';
                let harga = d.harga_beli? 'Rp ' + parseInt(d.harga_beli).toLocaleString('id-ID') : '-';
                let tgl = d.tgl_beli? new Date(d.tgl_beli).toLocaleDateString('id-ID') : '-';
                let foto = d.gambar? `<img src="uploads/inventaris_gereja/${d.gambar}" class="img-thumbnail" width="50" style="cursor:pointer" onclick="window.open(this.src)">` : '<i class="fas fa-image text-muted"></i>';
                html += `<tr>
                    <td>${i+1}</td>
                    <td class="text-center">${foto}</td>
                    <td>${d.nama_barang}</td>
                    <td>${d.kategori}</td>
                    <td>${d.jumlah}</td>
                    <td><span class="badge badge-${badge}">${d.kondisi}</span></td>
                    <td>${tgl}</td>
                    <td>${harga}</td>
                    <td>
                        <button class="btn btn-warning btn-sm" onclick="editInventaris(${d.id})"><i class="fa fa-edit"></i></button>
                        <button class="btn btn-danger btn-sm" onclick="hapusInventaris(${d.id})"><i class="fa fa-trash"></i></button>
                    </td>
                </tr>`;
            });
        }
        $('#tabelBody').html(html);
    },'json');
}

function previewGambar(input){
    if(input.files && input.files[0]){
        let reader = new FileReader();
        reader.onload = function(e){
            $('#preview').html(`<img src="${e.target.result}" class="img-thumbnail" width="150">`);
        }
        reader.readAsDataURL(input.files[0]);
    }
}

function tambahInventaris(){
    $('#formData')[0].reset();
    $('#id').val('');
    $('#foto_lama').val('');
    $('#preview').html('');
    $('.modal-title').text('Tambah Inventaris Gereja');
    $('#modalForm').modal('show');
}

function editInventaris(id){
    $.get('api/get_inventaris.php?id='+id, function(res){
        if(res.status=='success'){
            let d = res.data;
            $('#id').val(d.id);
            $('#foto_lama').val(d.gambar);
            $('[name=nama_barang]').val(d.nama_barang);
            $('[name=kategori]').val(d.kategori);
            $('[name=jumlah]').val(d.jumlah);
            $('[name=kondisi]').val(d.kondisi);
            $('[name=tgl_beli]').val(d.tgl_beli);
            $('[name=harga_beli]').val(d.harga_beli);
            $('[name=keterangan]').val(d.keterangan);
            if(d.gambar){
                $('#preview').html(`<img src="uploads/inventaris_gereja/${d.gambar}" class="img-thumbnail" width="150"><br><small>Biarkan kosong jika tidak ganti foto</small>`);
            } else {
                $('#preview').html('');
            }
            $('.modal-title').text('Edit Inventaris Gereja');
            $('#modalForm').modal('show');
        }
    },'json');
}

function simpanInventaris(){
    let formData = new FormData($('#formData')[0]);
    $.ajax({
        url:'api/simpan_inventaris.php',
        type:'POST',
        data: formData,
        contentType: false,
        processData: false,
        dataType:'json',
        success:function(res){
            if(res.status=='success'){
                $('#modalForm').modal('hide');
                Swal.fire('Sukses',res.message,'success');
                loadData();
            } else {
                Swal.fire('Error',res.message,'error');
            }
        }
    });
}

function hapusInventaris(id){
    Swal.fire({
        title: 'Yakin hapus?', icon: 'warning', showCancelButton: true,
        confirmButtonText: 'Ya, hapus!', cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            $.get('api/hapus_inventaris.php?id='+id, function(res){
                Swal.fire('Terhapus!',res.message,'success');
                loadData();
            },'json');
        }
    });
}

loadData();
</script>