@extends('admin-layouts.master')

@section('content')
<div class="container-fluid">
    <!-- Page Heading -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Manajemen Layanan</h1>
        <div class="btn-group">
            <a href="{{ route('services.create') }}" class="btn btn-primary">
                <i class="fas fa-plus"></i> Tambah Layanan
            </a>
            <a href="{{ route('service-categories.index') }}" class="btn btn-info">
                <i class="fas fa-list"></i> Kelola Kategori
            </a>
        </div>
    </div>

    <!-- Filter Card -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Filter & Pencarian</h6>
        </div>
        <div class="card-body">
            <form method="GET" action="{{ route('services.index') }}" id="filterForm">
                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Kategori:</label>
                            <select class="form-control" name="category_id" id="categoryFilter">
                                <option value="">Semua Kategori</option>
                                @foreach($categories as $category)
                                    <option value="{{ $category->id }}" {{ request('category_id') == $category->id ? 'selected' : '' }}>
                                        {{ $category->name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Cari Layanan:</label>
                            <input type="text" class="form-control" name="search" placeholder="Nama layanan..." value="{{ request('search') }}">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>Harga Min:</label>
                            <input type="number" class="form-control" name="min_price" placeholder="0" value="{{ request('min_price') }}">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>Harga Max:</label>
                            <input type="number" class="form-control" name="max_price" placeholder="1000000" value="{{ request('max_price') }}">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <div class="d-flex">
                                <button type="submit" class="btn btn-primary mr-2">
                                    <i class="fas fa-search"></i> Filter
                                </button>
                                <a href="{{ route('services.index') }}" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> Reset
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                Total Layanan
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                {{ $services->total() }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-concierge-bell fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                Kategori Aktif
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                {{ $categories->count() }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-list fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                Rata-rata Harga
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                Rp {{ number_format($services->avg('harga') ?? 0, 0, ',', '.') }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-chart-line fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                Harga Tertinggi
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                Rp {{ number_format($services->max('harga') ?? 0, 0, ',', '.') }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-crown fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Services List -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Daftar Layanan</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Nama Layanan</th>
                            <th>Kategori</th>
                            <th>Satuan</th>
                            <th>Harga</th>
                            <th>PPN</th>
                            <th>Harga + PPN</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse ($services as $service)
                        <tr>
                            <td>{{ $service->id }}</td>
                            <td>
                                <strong>{{ $service->name }}</strong>
                            </td>
                            <td>
                                <span class="badge badge-info">{{ $service->category->name }}</span>
                            </td>
                            <td>{{ $service->satuan }}</td>
                            <td>
                                <strong class="text-primary">{{ $service->formatted_price }}</strong>
                            </td>
                            <td>
                                <span class="badge badge-warning">{{ $service->formatted_ppn }}</span>
                            </td>
                            <td>
                                <strong class="text-success">{{ $service->formatted_price_with_ppn }}</strong>
                            </td>
                            <td>
                                <div class="btn-group" role="group">
                                    {{-- <a href="{{ route('services.show', $service) }}" class="btn btn-info btn-sm" title="Detail">
                                        <i class="fas fa-eye"></i>
                                    </a> --}}
                                    <a href="{{ route('services.edit', $service) }}" class="btn btn-warning btn-sm" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <button class="btn btn-danger btn-sm" onclick="deleteService({{ $service->id }})" title="Hapus">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <button class="btn btn-secondary btn-sm" onclick="calculatePrice({{ $service->id }})" title="Hitung Harga">
                                        <i class="fas fa-calculator"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="8" class="text-center py-4">
                                <i class="fas fa-concierge-bell fa-3x text-gray-400 mb-3"></i>
                                <p class="text-gray-500">Tidak ada layanan ditemukan</p>
                                <a href="{{ route('services.create') }}" class="btn btn-primary">
                                    <i class="fas fa-plus"></i> Tambah Layanan Pertama
                                </a>
                            </td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            
            <!-- Pagination -->
            @if($services->hasPages())
            <div class="d-flex justify-content-center mt-4">
                {{ $services->appends(request()->query())->links() }}
            </div>
            @endif
        </div>
    </div>
</div>

<!-- Price Calculator Modal -->
<div class="modal fade" id="priceCalculatorModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Kalkulator Harga</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="calculatorContent">
                    <!-- Content will be loaded here -->
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>

<script>
function deleteService(id) {
    Swal.fire({
        title: 'Konfirmasi Hapus',
        text: 'Apakah Anda yakin ingin menghapus layanan ini?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Ya, Hapus!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: `/services/${id}`,
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil!',
                            text: response.message,
                            timer: 2000,
                            showConfirmButton: false
                        }).then(() => {
                            location.reload();
                        });
                    }
                },
                error: function(xhr) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal!',
                        text: xhr.responseJSON?.message || 'Gagal menghapus layanan'
                    });
                }
            });
        }
    });
}

function calculatePrice(serviceId) {
    $.ajax({
        url: `/services/${serviceId}`,
        method: 'GET',
        headers: {
            'Accept': 'application/json'
        },
        success: function(service) {
            const content = `
                <div class="service-info mb-3">
                    <h6>${service.name}</h6>
                    <p class="text-muted">Satuan: ${service.satuan} | Harga: ${service.formatted_price} | PPN: ${service.formatted_ppn}</p>
                </div>
                <div class="form-group">
                    <label>Jumlah:</label>
                    <input type="number" id="quantity" class="form-control" value="1" min="1">
                </div>
                <div id="calculationResult" class="mt-3"></div>
                <button type="button" class="btn btn-primary" onclick="doCalculation(${serviceId})">Hitung</button>
            `;

            $('#calculatorContent').html(content);

            // pastikan modal function tersedia
            if (typeof $.fn.modal === 'function') {
                $('#priceCalculatorModal').modal('show');
            } else {
                alert('Modal gagal ditampilkan. Pastikan jQuery dan Bootstrap JS sudah di-load.');
            }
        }
    });
}


function doCalculation(serviceId) {
    const quantity = $('#quantity').val();
    
    $.ajax({
        url: '/services/calculate-price',
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
            'Accept': 'application/json'
        },
        data: {
            service_id: serviceId,
            quantity: quantity
        },
        success: function(response) {
            if (response.success) {
                const result = response.formatted;
                const resultHtml = `
                    <div class="alert alert-success">
                        <table class="table table-borderless mb-0">
                            <tr>
                                <td>Harga Satuan:</td>
                                <td class="text-right">${result.unit_price}</td>
                            </tr>
                            <tr>
                                <td>Subtotal (${quantity}x):</td>
                                <td class="text-right">${result.subtotal}</td>
                            </tr>
                            <tr>
                                <td>PPN:</td>
                                <td class="text-right">${result.ppn_amount}</td>
                            </tr>
                            <tr class="font-weight-bold">
                                <td>Total:</td>
                                <td class="text-right text-success">${result.total}</td>
                            </tr>
                        </table>
                    </div>
                `;
                $('#calculationResult').html(resultHtml);
            }
        },
        error: function(xhr) {
            $('#calculationResult').html(`
                <div class="alert alert-danger">
                    Gagal menghitung harga: ${xhr.responseJSON?.message || 'Unknown error'}
                </div>
            `);
        }
    });
}

// Auto calculate on quantity change
$(document).on('input', '#quantity', function() {
    const serviceId = $(this).data('service-id');
    if (serviceId) {
        doCalculation(serviceId);
    }
});

// Handle success messages
@if(session('success'))
    Swal.fire({
        title: 'Berhasil!',
        text: '{{ session("success") }}',
        icon: 'success',
        timer: 3000,
        showConfirmButton: false
    });
@endif
</script>
@endpush
@endsection