@extends('layouts.layoutMaster')

@section('title', __('Product Details'))

@section('vendor-style')
@vite([
    'resources/assets/vendor/libs/sweetalert2/sweetalert2.scss'
])
@endsection

@section('vendor-script')
@vite([
    'resources/assets/vendor/libs/sweetalert2/sweetalert2.js'
])
@endsection

@section('content')
<x-breadcrumb
    :title="$product->name"
    :breadcrumbs="[
        ['name' => __('System Core'), 'url' => route('systemcore.dashboard')],
        ['name' => __('Products'), 'url' => route('systemcore.products.index')],
        ['name' => __('Details')]
    ]"
/>

<div class="row">
    <!-- Product Information -->
    <div class="col-xl-4 col-lg-5 col-md-5">
        <div class="card mb-4">
            <div class="card-body">
                <div class="d-flex align-items-center mb-3">
                    @if($product->thumbnail)
                    <div class="me-3">
                        <img src="{{ asset('storage/' . $product->thumbnail) }}" alt="{{ $product->name }}"
                             class="rounded" width="64" height="64" style="object-fit: cover;">
                    </div>
                    @else
                    <div class="avatar avatar-lg me-3">
                        <span class="avatar-initial rounded-circle bg-label-success">
                            {{ strtoupper(substr($product->name, 0, 2)) }}
                        </span>
                    </div>
                    @endif
                    <div class="flex-grow-1">
                        <h5 class="mb-0">{{ $product->name }}</h5>
                        <span class="badge bg-label-success">{{ $product->product_code }}</span>
                    </div>
                </div>

                <div class="info-container">
                    <ul class="list-unstyled">
                        <li class="mb-2">
                            <span class="fw-medium me-1">{{ __('SKU:') }}</span>
                            <span>{{ $product->sku ?? '-' }}</span>
                        </li>
                        @if($product->barcode)
                        <li class="mb-2">
                            <span class="fw-medium me-1">{{ __('Barcode:') }}</span>
                            <span>{{ $product->barcode }}</span>
                        </li>
                        @endif
                        <li class="mb-2">
                            <span class="fw-medium me-1">{{ __('Category:') }}</span>
                            <span>{{ $product->category?->name ?? '-' }}</span>
                        </li>
                        @if($product->brand)
                        <li class="mb-2">
                            <span class="fw-medium me-1">{{ __('Brand:') }}</span>
                            <span>{{ $product->brand }}</span>
                        </li>
                        @endif
                        <li class="mb-2">
                            <span class="fw-medium me-1">{{ __('Status:') }}</span>
                            <span class="badge bg-{{ $product->status->color() }}">{{ $product->status->label() }}</span>
                        </li>
                        <li class="mb-2">
                            <span class="fw-medium me-1">{{ __('Unit:') }}</span>
                            <span>{{ $product->unit_of_measure ?? '-' }}</span>
                        </li>
                    </ul>

                    @if($product->description)
                    <div class="mt-3">
                        <h6 class="fw-semibold">{{ __('Description') }}</h6>
                        <p class="text-muted">{{ $product->description }}</p>
                    </div>
                    @endif

                    <div class="d-flex gap-2 mt-4">
                        @can('systemcore.edit-product')
                        <a href="{{ route('systemcore.products.edit', $product->id) }}" class="btn btn-primary">
                            <i class="bx bx-edit me-1"></i>{{ __('Edit') }}
                        </a>
                        @endcan
                        @can('systemcore.delete-product')
                        <button class="btn btn-danger delete-product" data-id="{{ $product->id }}">
                            <i class="bx bx-trash me-1"></i>{{ __('Delete') }}
                        </button>
                        @endcan
                        <a href="{{ route('systemcore.products.index') }}" class="btn btn-label-secondary">
                            <i class="bx bx-arrow-back me-1"></i>{{ __('Back') }}
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Inventory Summary -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">{{ __('Inventory Summary') }}</h5>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <h6 class="fw-semibold">{{ __('Total Stock') }}</h6>
                    <h4>{{ $totalStock }} {{ $product->unit_of_measure ?? '' }}</h4>
                </div>
                <div class="mb-3">
                    <h6 class="fw-semibold">{{ __('Reorder Point') }}</h6>
                    <p>{{ $product->reorder_point ?? $product->reorder_level ?? __('Not set') }}</p>
                </div>
                <div class="mb-3">
                    <h6 class="fw-semibold">{{ __('Inventory Value') }}</h6>
                    <p>{{ \App\Helpers\FormattingHelper::formatCurrency($totalValue) }}</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Pricing & Details -->
    <div class="col-xl-8 col-lg-7 col-md-7">
        <!-- Pricing Cards -->
        <div class="row mb-4">
            <div class="col-sm-6 col-lg-3 mb-4">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex align-items-center">
                            <div class="badge rounded-pill bg-label-info me-3 p-2">
                                <i class="bx bx-purchase-tag bx-sm"></i>
                            </div>
                            <div class="card-info">
                                <h5 class="mb-0">{{ number_format($stats['base_price'], 2) }}</h5>
                                <small>{{ __('Base Price') }}</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-lg-3 mb-4">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex align-items-center">
                            <div class="badge rounded-pill bg-label-warning me-3 p-2">
                                <i class="bx bx-dollar bx-sm"></i>
                            </div>
                            <div class="card-info">
                                <h5 class="mb-0">{{ number_format($stats['cost_price'], 2) }}</h5>
                                <small>{{ __('Cost Price') }}</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-lg-3 mb-4">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex align-items-center">
                            <div class="badge rounded-pill bg-label-success me-3 p-2">
                                <i class="bx bx-cart bx-sm"></i>
                            </div>
                            <div class="card-info">
                                <h5 class="mb-0">{{ number_format($stats['selling_price'], 2) }}</h5>
                                <small>{{ __('Selling Price') }}</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-lg-3 mb-4">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex align-items-center">
                            <div class="badge rounded-pill bg-label-primary me-3 p-2">
                                <i class="bx bx-line-chart bx-sm"></i>
                            </div>
                            <div class="card-info">
                                <h5 class="mb-0">{{ number_format($stats['profit_margin'], 1) }}%</h5>
                                <small>{{ __('Profit Margin') }}</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Stock by Warehouse -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="bx bx-buildings me-1"></i>{{ __('Stock by Warehouse') }}</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>{{ __('Warehouse') }}</th>
                                <th>{{ __('Available Quantity') }}</th>
                                <th>{{ __('Reserved Quantity') }}</th>
                                <th>{{ __('Value') }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($warehouseStock as $stock)
                            <tr>
                                <td>{{ $stock->warehouse->name }}</td>
                                <td>{{ $stock->available_quantity }} {{ $product->unit_of_measure ?? '' }}</td>
                                <td>{{ $stock->reserved_quantity }} {{ $product->unit_of_measure ?? '' }}</td>
                                <td>{{ $stock->value }}</td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="4" class="text-center">{{ __('No stock information available') }}</td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Recent Transactions -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="bx bx-transfer me-1"></i>{{ __('Recent Transactions') }}</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>{{ __('Date') }}</th>
                                <th>{{ __('Type') }}</th>
                                <th>{{ __('Reference') }}</th>
                                <th>{{ __('Warehouse') }}</th>
                                <th>{{ __('Quantity') }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($transactions as $transaction)
                            <tr>
                                <td>{{ \Carbon\Carbon::parse($transaction->created_at)->format('Y-m-d H:i') }}</td>
                                <td>{{ ucfirst($transaction->transaction_type) }}</td>
                                <td>{{ $transaction->reference_type }} #{{ $transaction->reference_id }}</td>
                                <td>{{ $transaction->warehouse->name }}</td>
                                <td>
                                    @if(in_array($transaction->transaction_type, ['inbound', 'purchase', 'return', 'void']))
                                    <span class="text-success">+{{ abs($transaction->quantity) }}</span>
                                    @else
                                    <span class="text-danger">-{{ abs($transaction->quantity) }}</span>
                                    @endif
                                </td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="5" class="text-center">{{ __('No transactions found') }}</td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Product Variants -->
        @if($product->has_variants && $product->variants->count() > 0)
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="bx bx-grid me-1"></i>{{ __('Product Variants') }}
                    <span class="badge bg-label-primary ms-2">{{ $stats['variants_count'] }}</span>
                </h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>{{ __('Variant SKU') }}</th>
                                <th>{{ __('Name') }}</th>
                                <th>{{ __('Attributes') }}</th>
                                <th>{{ __('Price') }}</th>
                                <th>{{ __('Status') }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($product->variants as $variant)
                            <tr>
                                <td>{{ $variant->variant_sku }}</td>
                                <td>{{ $variant->variant_name }}</td>
                                <td>
                                    @if($variant->attributes)
                                        @foreach($variant->attributes as $key => $value)
                                            <span class="badge bg-label-info">{{ $key }}: {{ $value }}</span>
                                        @endforeach
                                    @else
                                        -
                                    @endif
                                </td>
                                <td>{{ number_format($variant->price, 2) }}</td>
                                <td>
                                    <span class="badge bg-{{ $variant->is_active ? 'success' : 'secondary' }}">
                                        {{ $variant->is_active ? __('Active') : __('Inactive') }}
                                    </span>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        @endif
    </div>
</div>
@endsection

@section('page-script')
<script>
const pageData = {
    urls: {
        destroy: '{{ route("systemcore.products.destroy", $product->id) }}',
        index: '{{ route("systemcore.products.index") }}'
    },
    labels: {
        confirmDelete: @json(__('Are you sure?')),
        deleteWarning: @json(__("You won't be able to revert this!")),
        yesDelete: @json(__('Yes, delete it!')),
        cancel: @json(__('Cancel')),
        deleted: @json(__('Deleted!')),
        deletedText: @json(__('Product has been deleted.')),
        error: @json(__('Error!')),
        deleteError: @json(__('Could not delete product.'))
    }
};

$(function () {
    $.ajaxSetup({
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
    });

    $('.delete-product').on('click', function () {
        Swal.fire({
            title: pageData.labels.confirmDelete,
            text: pageData.labels.deleteWarning,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: pageData.labels.yesDelete,
            cancelButtonText: pageData.labels.cancel,
            customClass: {
                confirmButton: 'btn btn-danger me-3',
                cancelButton: 'btn btn-label-secondary'
            },
            buttonsStyling: false
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: pageData.urls.destroy,
                    type: 'DELETE',
                    success: function () {
                        Swal.fire({
                            title: pageData.labels.deleted,
                            text: pageData.labels.deletedText,
                            icon: 'success',
                            customClass: { confirmButton: 'btn btn-success' },
                            buttonsStyling: false
                        }).then(() => {
                            window.location.href = pageData.urls.index;
                        });
                    },
                    error: function (xhr) {
                        const msg = xhr.responseJSON?.message || pageData.labels.deleteError;
                        Swal.fire({
                            title: pageData.labels.error,
                            text: msg,
                            icon: 'error',
                            customClass: { confirmButton: 'btn btn-danger' },
                            buttonsStyling: false
                        });
                    }
                });
            }
        });
    });
});
</script>
@endsection
