@extends('backoffice.layouts.app')

@section('title', 'Siteler')

@section('content')
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h2 class="mb-1">
                        <i class="bi bi-globe2 me-2"></i>
                        Siteler
                    </h2>
                    <p class="text-muted">Coklu site baglantilarini yonetin</p>
                </div>
                @if(can_access('sites', 'create'))
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createSiteModal">
                    <i class="bi bi-plus-circle me-2"></i>Yeni Site
                </button>
                @endif
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table id="sitesTable" class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Site</th>
                            <th>Redirect URL</th>
                            <th>SID</th>
                            <th>KEY</th>
                            <th>Durum</th>
                            <th>Islem Sayisi</th>
                            <th>Olusturulma</th>
                            <th width="140" class="text-center">Islemler</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="createSiteModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-plus-circle me-2"></i>Yeni Site</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="createSiteForm" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Site Adi <span class="text-danger">*</span></label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Redirect URL <span class="text-danger">*</span></label>
                            <input type="url" name="redirect_url" class="form-control" required placeholder="https://example.com">
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Secret Key <span class="text-danger">*</span></label>
                            <input type="text" name="secret_key" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Withdraw URL <span class="text-danger">*</span></label>
                            <input type="url" name="withdraw_url" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Notify URL <span class="text-danger">*</span></label>
                            <input type="url" name="notify_url" class="form-control" required>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Deposit Callback URL <span class="text-danger">*</span></label>
                            <input type="url" name="deposit_callback_url" class="form-control" required>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Withdrawal Callback URL</label>
                            <input type="url" name="withdrawal_callback_url" class="form-control" placeholder="https://example.com/withdraw-callback">
                            <small class="text-muted">Bos birakilirsa finance panel withdraw approve/decline callback gondermez.</small>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Logo</label>
                            <input type="file" name="logo" id="createLogoInput" class="form-control" accept=".jpg,.jpeg,.png,.webp,.svg">
                            <small class="text-muted">JPG, PNG, WEBP veya SVG. Maksimum 2 MB.</small>
                            <div class="mt-2 d-none" id="createLogoPreviewWrap">
                                <img id="createLogoPreview" src="" alt="Logo Preview" style="width: 56px; height: 56px; object-fit: contain; border: 1px solid #e5e7eb; border-radius: 8px; padding: 4px;">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Iptal</button>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle me-2"></i>Kaydet</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="editSiteModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-pencil me-2"></i>Site Duzenle</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editSiteForm" enctype="multipart/form-data">
                <input type="hidden" id="editSiteId">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Site Adi <span class="text-danger">*</span></label>
                            <input type="text" name="name" id="editName" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Redirect URL <span class="text-danger">*</span></label>
                            <input type="url" name="redirect_url" id="editRedirectUrl" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">SID</label>
                            <input type="text" id="editSid" class="form-control" readonly>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">KEY</label>
                            <input type="text" id="editApiKey" class="form-control" readonly>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Secret Key <span class="text-danger">*</span></label>
                            <input type="text" name="secret_key" id="editSecretKey" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Withdraw URL <span class="text-danger">*</span></label>
                            <input type="url" name="withdraw_url" id="editWithdrawUrl" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Notify URL <span class="text-danger">*</span></label>
                            <input type="url" name="notify_url" id="editNotifyUrl" class="form-control" required>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Deposit Callback URL <span class="text-danger">*</span></label>
                            <input type="url" name="deposit_callback_url" id="editDepositCallbackUrl" class="form-control" required>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Withdrawal Callback URL</label>
                            <input type="url" name="withdrawal_callback_url" id="editWithdrawalCallbackUrl" class="form-control">
                            <small class="text-muted">Bos birakilirsa finance panel withdraw approve/decline callback gondermez.</small>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Logo</label>
                            <input type="file" name="logo" id="editLogoInput" class="form-control" accept=".jpg,.jpeg,.png,.webp,.svg">
                            <small class="text-muted">Bos birakirsan mevcut logo korunur.</small>
                            <div class="mt-2 d-none" id="editLogoPreviewWrap">
                                <img id="editLogoPreview" src="" alt="Logo Preview" style="width: 56px; height: 56px; object-fit: contain; border: 1px solid #e5e7eb; border-radius: 8px; padding: 4px;">
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="editIsActive">
                                <label class="form-check-label" for="editIsActive">Aktif</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Iptal</button>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle me-2"></i>Guncelle</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
$(document).ready(function() {
    const canCreateSites = {!! can_access('sites', 'create') ? 'true' : 'false' !!};
    const canUpdateSites = {!! can_access('sites', 'update') ? 'true' : 'false' !!};
    const canDeleteSites = {!! can_access('sites', 'delete') ? 'true' : 'false' !!};

    function escapeHtml(value) {
        return String(value ?? '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }

    const table = $('#sitesTable').DataTable({
        processing: true,
        serverSide: false,
        ajax: '{{ route("backoffice.sites.index") }}',
        columns: [
            {
                data: null,
                render: function(data) {
                    const name = escapeHtml(data.name || '-');
                    const logo = data.logo_url
                        ? '<img src="' + escapeHtml(data.logo_url) + '" alt="' + name + ' Logo" style="width:28px;height:28px;object-fit:contain;border:1px solid #e5e7eb;border-radius:6px;padding:2px;background:#fff;">'
                        : '<i class="bi bi-image text-muted"></i>';

                    return '<div class="d-flex align-items-center gap-2">' + logo + '<span>' + name + '</span></div>';
                }
            },
            {
                data: 'redirect_url',
                render: function(data) {
                    if (!data) return '-';
                    return '<a href="' + data + '" target="_blank" rel="noopener noreferrer">' + data + '</a>';
                }
            },
            { data: 'sid' },
            { data: 'api_key' },
            {
                data: 'is_active',
                render: function(data) {
                    return data
                        ? '<span class="badge bg-success">Aktif</span>'
                        : '<span class="badge bg-secondary">Pasif</span>';
                }
            },
            {
                data: 'transactions_count',
                render: function(data) {
                    return '<span class="badge bg-info">' + (data || 0) + '</span>';
                }
            },
            { data: 'created_at' },
            {
                data: null,
                orderable: false,
                render: function(data) {
                    const buttons = [];
                    const statusBtnClass = data.is_active ? 'btn-outline-warning' : 'btn-outline-success';
                    const statusIcon = data.is_active ? 'bi-pause-circle' : 'bi-play-circle';
                    const statusTitle = data.is_active ? 'Pasife Al' : 'Aktif Et';
                    if (canUpdateSites) {
                        buttons.push('<button class="btn btn-outline-primary btn-edit" data-id="' + data.id + '" title="Duzenle"><i class="bi bi-pencil"></i></button>');
                        buttons.push('<button class="btn ' + statusBtnClass + ' btn-toggle-status" data-id="' + data.id + '" title="' + statusTitle + '"><i class="bi ' + statusIcon + '"></i></button>');
                    }
                    if (canDeleteSites) {
                        buttons.push('<button class="btn btn-outline-danger btn-delete" data-id="' + data.id + '" title="Sil"><i class="bi bi-trash"></i></button>');
                    }
                    return '<div class="btn-group btn-group-sm">' + buttons.join('') + '</div>';
                }
            }
        ],
        order: [[0, 'asc']],
        pageLength: 25,
        language: {
            url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/tr.json'
        }
    });

    $('#createSiteForm').on('submit', function(e) {
        e.preventDefault();
        if (!canCreateSites) {
            return;
        }
        const formEl = document.getElementById('createSiteForm');
        const formData = new FormData(formEl);
        formData.append('_token', '{{ csrf_token() }}');

        $.ajax({
            url: '{{ route("backoffice.sites.store") }}',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                $('#createSiteModal').modal('hide');
                $('#createSiteForm')[0].reset();
                $('#createLogoPreviewWrap').addClass('d-none');
                $('#createLogoPreview').attr('src', '');
                Swal.fire('Basarili!', response.message, 'success');
                table.ajax.reload();
            },
            error: function(xhr) {
                if (xhr.status === 422 && xhr.responseJSON.errors) {
                    let errorMsg = '<ul class="text-start">';
                    Object.keys(xhr.responseJSON.errors).forEach(function(key) {
                        errorMsg += '<li>' + xhr.responseJSON.errors[key][0] + '</li>';
                    });
                    errorMsg += '</ul>';
                    Swal.fire('Dogrulama Hatasi!', errorMsg, 'error');
                } else {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
                }
            }
        });
    });

    $(document).on('click', '.btn-edit', function() {
        if (!canUpdateSites) {
            return;
        }
        const id = $(this).data('id');
        $.ajax({
            url: '{{ route("backoffice.sites.show", ":id") }}'.replace(':id', id),
            success: function(response) {
                const site = response.site;
                $('#editSiteId').val(site.id);
                $('#editName').val(site.name);
                $('#editRedirectUrl').val(site.redirect_url);
                $('#editSid').val(site.sid);
                $('#editApiKey').val(site.api_key);
                $('#editSecretKey').val(site.secret_key || '');
                $('#editWithdrawUrl').val(site.withdraw_url || '');
                $('#editNotifyUrl').val(site.notify_url || '');
                $('#editDepositCallbackUrl').val(site.deposit_callback_url || '');
                $('#editWithdrawalCallbackUrl').val(site.withdrawal_callback_url || '');
                $('#editIsActive').prop('checked', !!site.is_active);
                $('#editLogoInput').val('');
                if (site.logo_url) {
                    $('#editLogoPreview').attr('src', site.logo_url);
                    $('#editLogoPreviewWrap').removeClass('d-none');
                } else {
                    $('#editLogoPreview').attr('src', '');
                    $('#editLogoPreviewWrap').addClass('d-none');
                }
                $('#editSiteModal').modal('show');
            }
        });
    });

    $('#editSiteForm').on('submit', function(e) {
        e.preventDefault();
        if (!canUpdateSites) {
            return;
        }
        const id = $('#editSiteId').val();
        const formEl = document.getElementById('editSiteForm');
        const payload = new FormData(formEl);
        payload.append('is_active', $('#editIsActive').is(':checked') ? '1' : '0');
        payload.append('_token', '{{ csrf_token() }}');
        payload.append('_method', 'PUT');

        $.ajax({
            url: '{{ route("backoffice.sites.update", ":id") }}'.replace(':id', id),
            method: 'POST',
            data: payload,
            processData: false,
            contentType: false,
            success: function(response) {
                $('#editSiteModal').modal('hide');
                Swal.fire('Basarili!', response.message, 'success');
                table.ajax.reload(null, false);
            },
            error: function(xhr) {
                if (xhr.status === 422 && xhr.responseJSON.errors) {
                    let errorMsg = '<ul class="text-start">';
                    Object.keys(xhr.responseJSON.errors).forEach(function(key) {
                        errorMsg += '<li>' + xhr.responseJSON.errors[key][0] + '</li>';
                    });
                    errorMsg += '</ul>';
                    Swal.fire('Dogrulama Hatasi!', errorMsg, 'error');
                } else {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
                }
            }
        });
    });

    $('#createLogoInput').on('change', function() {
        const file = this.files && this.files[0] ? this.files[0] : null;
        if (!file) {
            $('#createLogoPreviewWrap').addClass('d-none');
            $('#createLogoPreview').attr('src', '');
            return;
        }
        const objectUrl = URL.createObjectURL(file);
        $('#createLogoPreview').attr('src', objectUrl);
        $('#createLogoPreviewWrap').removeClass('d-none');
    });

    $('#editLogoInput').on('change', function() {
        const file = this.files && this.files[0] ? this.files[0] : null;
        if (!file) {
            return;
        }
        const objectUrl = URL.createObjectURL(file);
        $('#editLogoPreview').attr('src', objectUrl);
        $('#editLogoPreviewWrap').removeClass('d-none');
    });

    $(document).on('click', '.btn-toggle-status', function() {
        if (!canUpdateSites) {
            return;
        }
        const id = $(this).data('id');
        $.ajax({
            url: '{{ route("backoffice.sites.toggle-status", ":id") }}'.replace(':id', id),
            method: 'POST',
            data: { _token: '{{ csrf_token() }}' },
            success: function(response) {
                Swal.fire('Basarili!', response.message, 'success');
                table.ajax.reload(null, false);
            },
            error: function(xhr) {
                Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
            }
        });
    });

    $(document).on('click', '.btn-delete', function() {
        if (!canDeleteSites) {
            return;
        }
        const id = $(this).data('id');
        Swal.fire({
            title: 'Emin misiniz?',
            text: 'Bu site silinecek.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Evet, Sil',
            cancelButtonText: 'Iptal',
            confirmButtonColor: '#dc3545'
        }).then((result) => {
            if (!result.isConfirmed) {
                return;
            }
            $.ajax({
                url: '{{ route("backoffice.sites.destroy", ":id") }}'.replace(':id', id),
                method: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    _method: 'DELETE'
                },
                success: function(response) {
                    Swal.fire('Basarili!', response.message, 'success');
                    table.ajax.reload(null, false);
                },
                error: function(xhr) {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
                }
            });
        });
    });
});
</script>
@endpush
