<?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 => $service) {
            $stmt = $DB->prepare("UPDATE services SET `sira` = :order WHERE id = :id");
            $stmt->execute([':order' => $index + 1, ':id' => $service['id']]);
        }
        echo json_encode(['status' => 'success']);
        exit;
    }

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

// Veritabanından verileri çekelim
$bak = $DB->prepare("SELECT * FROM services ORDER BY `sira` ASC");
$bak->execute();
$services = $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="services-add">
                                                <button class="dt-button btn btn-primary btn-add-record ms-2" tabindex="0" aria-controls="DataTables_Table_0" type="button">
                                                    <span>Yeni Hizmet Ekle</span>
                                                </button>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <table class="invoice-list-table table dataTable no-footer dtr-column" id="servicesTable" role="grid" aria-describedby="DataTables_Table_0_info">
                                <thead>
                                    <tr role="row">
                                        <th>ID</th>
                                        <th>Hizmet Adı</th>
                                        <th>Açıklama</th>
                                        <th>İşlem Süresi</th>
                                        <th>Düzenle</th>
                                    </tr>
                                </thead>
                                <tbody id="sortable">
                                    <?php foreach ($services as $service) { ?>
                                    <tr id="service-<?=$service['id']?>" data-id="<?=$service['id']?>">
                                        <td><?=$service['id']?></td>
                                        <td><?=$service['serviceName']?></td>
                                        <td><?=$service['serviceDesc']?></td>
                                        <td><?=$service['hour']?> Dakika</td>
                                        <td>
                                            <a href="services/<?=$service['id']?>" class="btn btn-primary">Düzenle</a>
                                            <a href="#" class="btn btn-danger hizmetSil" data-id="<?=$service['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 = $('#servicesTable').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"
                        });
                    }
                });
            }
        });

        $(".hizmetSil").click(function() {
            var hizmetID = $(this).data('id');
            Swal.fire({
                title: 'Hizmeti silmek istediğinize emin misiniz?',
                showDenyButton: true,
                confirmButtonText: 'Evet',
                denyButtonText: 'Vazgeç',
                confirmButtonColor: '#7367f0',
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        type: 'POST',
                        url: '',
                        data: { hizmetSil: hizmetID },
                        success: function() {
                            Swal.fire('Silindi!', '', 'success').then(() => {
                                location.reload();
                            });
                        },
                        error: function() {
                            Swal.fire('Hata!', 'Hizmet silinirken bir hata oluştu.', 'error');
                        }
                    });
                } else if (result.isDenied) {
                    Swal.fire('Silinmedi', '', 'info');
                }
            });
        });
    });
</script>
<?php require $_SERVER['DOCUMENT_ROOT'].'/admin/system/includes/Footer.php'; ?>
