<?php 
require_once $_SERVER['DOCUMENT_ROOT'].'/admin/system/includes/AdminCheck.php';
require $_SERVER['DOCUMENT_ROOT'].'/admin/system/includes/Header.php';



if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['order'])) {
        $order = json_decode($_POST['order'], true);
        foreach ($order as $index => $provider) {
            $stmt = $DB->prepare("UPDATE provider SET `sira` = :order WHERE id = :id");
            $stmt->execute([':order' => $index + 1, ':id' => $provider['id']]);
        }
        echo json_encode(['status' => 'success']);
        exit;
    }

    if (isset($_POST['providerSil'])) {
        $providerID = $_POST['providerSil'];
        $stmt = $DB->prepare("DELETE FROM provider WHERE id = :id");
        $stmt->execute([':id' => $providerID]);
        echo json_encode(['status' => 'success']);
        exit;
    }
}

// Veritabanından verileri çekelim
$bak = $DB->prepare("SELECT * FROM provider ORDER BY `sira` ASC");
$bak->execute();
$providers = $bak->fetchAll(PDO::FETCH_ASSOC);

?>
<!-- BEGIN: Content-->
<div class="app-content content">
    <div class="content-overlay"></div>
    <div class="header-navbar-shadow"></div>
    <div class="content-wrapper container-xxl p-0">
        <div class="content-header row"></div>
        <div class="content-body">
            <section class="invoice-list-wrapper">
                <div class="card">
                    <div class="card-datatable table-responsive">
                        <div id="DataTables_Table_0_wrapper" class="dataTables_wrapper dt-bootstrap5 no-footer">
                            <div class="row d-flex justify-content-between align-items-center m-1">
                                <div class="col-lg-6 d-flex align-items-center">
                                    <div class="dt-action-buttons text-xl-end text-lg-start text-lg-end text-start">
                                        <div class="dt-buttons">
                                            <a href="provider-add">
                                                <button class="dt-button btn btn-primary btn-add-record ms-2" tabindex="0" aria-controls="DataTables_Table_0" type="button">
                                                    <span>Yeni Çalışan Ekle</span>
                                                </button>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <table class="invoice-list-table table dataTable no-footer dtr-column" id="providerTable" role="grid" aria-describedby="DataTables_Table_0_info">
                                <thead>
                                    <tr role="row">
                                        <th>ID</th>
                                        <th>Çalışan Adı</th>
                                        <th>Email</th>
                                        <th>Çalışma Aralığı</th>
                                        <?php if($settings['vestedSystem']=='1'){ ?>
                                            <th>Hakediş</th>
                                        <?php } ?>
                                        <th>Düzenle</th>
                                    </tr>
                                </thead>
                                <tbody id="sortable">
                                    <?php foreach ($providers as $provider) { ?>
                                    <tr id="provider-<?=$provider['id']?>" data-id="<?=$provider['id']?>">
                                        <td><?=$provider['id']?></td>
                                        <td><?=$provider['name']?></td>
                                        <td><?=$provider['email']?></td>
                                        <td><?=$provider['workingTime']?></td>
                                        <?php if($settings['vestedSystem']=='1'){ ?>
                                            <td>
                                                <?php if(empty($provider['vestedAmount'])){
                                                    echo '0₺';
                                                } else { ?>
                                                    <?=$provider['vestedAmount']."₺"?>
                                                <?php } ?>
                                                <a class="vestedPayed btn btn-success" providerID="<?=$provider['id']?>">Öde</a>
                                            </td>
                                        <?php } ?>
                                        <td>
                                            <a href="provider/<?=$provider['id']?>" class="btn btn-primary">Düzenle</a>
                                            <a href="#" class="btn btn-danger providerSil" data-id="<?=$provider['id']?>">Sil</a>
                                        </td>
                                    </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>
</div>
<!-- jQuery ve Sortable.js'yi yükleyin -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.14.0/Sortable.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    $(document).ready(function() {
        var table = $('#providerTable').DataTable({
            "language": {
                "url": "//cdn.datatables.net/plug-ins/1.10.25/i18n/Turkish.json"
            },
            "ordering": false, // Otomatik sıralamayı kapatıyoruz
            "searching": false, // Arama özelliğini kapatıyoruz
            "paging": false // Sayfalama özelliğini kapatıyoruz
        });

        var sortable = new Sortable(document.getElementById('sortable'), {
            animation: 150,
            onEnd: function (/**Event*/evt) {
                var sortedData = [].map.call(evt.from.children, function(el, index) {
                    return {
                        id: el.getAttribute('data-id'),
                        order: index + 1
                    };
                });

                $.ajax({
                    type: "POST",
                    url: "",
                    data: { order: JSON.stringify(sortedData) },
                    success: function(response) {
                        Swal.fire({
                            title: "Başarılı!",
                            text: "Sıralama başarıyla güncellendi.",
                            icon: "success",
                            confirmButtonText: "Tamam"
                        });
                    },
                    error: function() {
                        Swal.fire({
                            title: "Hata!",
                            text: "Sıralama güncellenirken bir hata oluştu.",
                            icon: "error",
                            confirmButtonText: "Tamam"
                        });
                    }
                });
            }
        });

        $(".providerSil").click(function() {
            var providerID = $(this).data('id');
            Swal.fire({
                title: 'Çalışanı silmek istediğinize emin misiniz?',
                showDenyButton: true,
                confirmButtonText: 'Evet',
                denyButtonText: 'Vazgeç',
                confirmButtonColor: '#7367f0',
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        type: 'POST',
                        url: '',
                        data: { providerSil: providerID },
                        success: function() {
                            Swal.fire('Silindi!', '', 'success').then(() => {
                                location.reload();
                            });
                        },
                        error: function() {
                            Swal.fire('Hata!', 'Çalışan silinirken bir hata oluştu.', 'error');
                        }
                    });
                } else if (result.isDenied) {
                    Swal.fire('Silinmedi', '', 'info');
                }
            });
        });

        $(".vestedPayed").click(function() {
            var providerID = $(this).attr('providerID');
            Swal.fire({  
                title: 'Çalışanın hakedişini ödemek istediğinize emin misiniz?',  
                showDenyButton: true,   
                confirmButtonText: 'Evet',  
                denyButtonText: 'Vazgeç',
                confirmButtonColor: '#7367f0',
            }).then((result) => {  
                if (result.isConfirmed) {    
                    var title = "Tebrikler!";
                    var text = "Hakediş başarıyla ödendi!";
                    $.ajax({
                        type: 'post',
                        url: '../../eral',
                        data: {
                            vestedPayed: '1',
                            providerID: providerID,
                        },
                        success: function() {
                            Swal.fire({
                                title: title,
                                text: text,
                                icon: 'success',
                                confirmButtonColor: '#7367f0',
                                confirmButtonText: "Tamam"
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    location.reload();
                                }
                                if (result.isDismissed) {
                                    location.reload();
                                }
                            })
                        }
                    });
                } else if (result.isDenied) {    
                    Swal.fire('Hakediş ödenmedi.', '', 'info')  
                }
            });
        });
    });
</script>
<?php require $_SERVER['DOCUMENT_ROOT'].'/admin/system/includes/Footer.php'; ?>
