@extends('layouts.admin')
@section('content')

<div class="card">
    <div class="card-header">
        <p>{{ trans('global.show') }} {{ trans('cruds.product.title') }} </p>
    </div>
    <div class="card-body">
        <div class="d-flex justify-content-between">
            <div class="form-group">
                @if($product->product_type == 1)
                    <a class="btn btn-default" href="{{ route('admin.products.auction_product') }}">{{ trans('global.back_to_list') }}</a>
                @else
                    <a class="btn btn-default" href="{{ route('admin.products.sell_product') }}">{{ trans('global.back_to_list') }}</a>
                @endif
            </div>
            <div class="form-group">
                <div class="alert alert-success message_success d-none"></div>
            </div>
        </div>
        <ul class="nav nav-tabs" id="productTab" role="tablist">
            <li class="nav-item">
                <a class="nav-link {{ request('tab') == 'details' || !request('tab') ? 'active' : '' }}" id="details-tab" data-toggle="tab" href="#details" role="tab">{{ trans('global.tabbing.product_details') }}</a>
            </li>
            <li class="nav-item">
                <a class="nav-link {{ request('tab') == 'product_media' ? 'active' : '' }}" id="product_media-tab" data-toggle="tab" href="#product_media" role="tab">{{ trans('global.tabbing.product_media') }}</a>
            </li>
            <li class="nav-item">
                <a class="nav-link {{ request('tab') == 'shipping' ? 'active' : '' }}" id="shipping-tab" data-toggle="tab" href="#shipping" role="tab">{{ trans('global.tabbing.shipping_details') }}</a>
            </li>
            @if($product->product_type == 1)
                <li class="nav-item">
                    <a class="nav-link {{ request('tab') == 'bids' ? 'active' : '' }}" id="bids-tab" data-toggle="tab" href="#bids" role="tab">{{ trans('global.tabbing.product_bids') }}</a>
                </li>
                @if(isset($buyer_details) && !empty($buyer_details))
                    <li class="nav-item">
                        <a class="nav-link {{ request('tab') == 'buyer_address' ? 'active' : '' }}" id="buyer_address-tab" data-toggle="tab" href="#buyer_address" role="tab">{{ trans('global.tabbing.buyer_details') }}</a>
                    </li>
                @endif
            @endif
            @if(isset($product_receipt) && !empty($product_receipt))
                <li class="nav-item">
                    <a class="nav-link {{ request('tab') == 'product-shipment-detail' ? 'active' : '' }}" id="product-shipment-detail-tab" data-toggle="tab" href="#product-shipment-detail" role="tab">{{ trans('global.tabbing.product_shipment_detail') }}</a>
                </li>
            @endif
        </ul>
        <div class="tab-content mt-3" id="productTabContent">
            <!-- Product Details Tab -->
            <div class="tab-pane fade {{ request('tab') == 'details' || !request('tab') ? 'show active' : '' }}" id="details" role="tabpanel">
                <table class="table table-bordered table-striped">
                    <tbody>
                        <tr>
                            <th>{{ trans('cruds.product.fields.product_type') }}</th>
                            <td>{{ $product->product_type == 1 ? 'For Auction' : 'For Seller' }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.category') }}</th>
                            <td>{{ $product->category ? $product->category->name : '' }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.name') }} (In English)</th>
                            <td>{{ $product->name }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.name') }} (In Arabic)</th>
                            <td>{{ $product->name_ar }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.sku') }}</th>
                            <td>{{ $product->sku }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.purchase_price') }}</th>
                            <td>BHD {{ number_format($product->purchase_price, 2) }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.price') }}</th>
                            <td>BHD {{ number_format($product->price, 2) }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.product_quantity') }}</th>
                            <td>{{ $product->product_quantity }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.commission_percentage') }}</th>
                            <td>{{ $product->commission_percentage }}%</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.user_id') }}</th>
                            <td>{{ $product->user ? ucwords($product->user->first_name . ' ' . $product->user->last_name) : 'N/A' }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.description') }} (In English)</th>
                            <td>{{ $product->description }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.description') }} (In Arabic)</th>
                            <td>{{ $product->description_ar }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.live_date') }}</th>
                            <td>{{ $product->live_date }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.duration_day') }}</th>
                            <td>{{ $product->duration_day }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.finish_date') }}</th>
                            <td>{{ $product->finish_date }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.status') }}</th>
                            <td>{{ trans('cruds.product.status.' . strtolower($product->status)) }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.condition') }}</th>
                            <td>{{ $product->condition == 1 ? 'New' : ($product->condition == 2 ? 'Used' : '-') }}</td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.bidding_incremented_price') }}</th>
                            <td>BHD {{ number_format($product->bidding_incremented_price, 2) }}</td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Product Media Tab -->
            <div class="tab-pane fade {{ request('tab') == 'product_media' ? 'show active' : '' }}" id="product_media" role="tabpanel">
                <table class="table table-bordered table-striped">
                    <tbody>
                        <tr>
                            <th>{{ trans('cruds.product.fields.cover_image') }}</th>
                            <td>
                                <a href="{{ asset($product->cover_image) }}" class="fancybox-popup">
                                    <img src="{{ asset($product->cover_image) }}" width="100">
                                </a>
                            </td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.images') }}</th>
                            <td>
                                <div class="row">
                                    @foreach($product->images as $old_image)
                                        <div class="col-md-3">
                                            <a href="{{ asset($old_image->image) }}" class="fancybox-popup">
                                                <img src="{{ asset($old_image->image) }}" class="mt-2" width="100">
                                            </a>
                                        </div>
                                    @endforeach
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.product.fields.documents') }}</th>
                            <td>
                                <div class="row">
                                    @foreach($product->documents as $document)
                                        @php $extension = pathinfo($document->file_name, PATHINFO_EXTENSION); @endphp
                                       
                                        @if(strtolower($extension) == 'pdf')
                                            <div class="col-md-2">
                                                <a href="{{ asset($document->file_name) }}" class="fancybox-popup">
                                                    <img src="{{ asset('img/pdf.png') }}" class="mt-2 mb-2" width="100">
                                                </a>
                                                <span>{{ $document->name }}</span>
                                            </div>
                                        @else
                                            <div class="col-md-3">
                                                <a href="{{ asset($document->file_name) }}" class="fancybox-popup">
                                                    <img src="{{ asset($document->file_name) }}" class="mt-2 mb-2" width="100">
                                                </a>
                                                <span>{{ $document->name }}</span>
                                            </div>
                                        @endif
                                    @endforeach
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Product Shipping Details Tab -->
            <div class="tab-pane fade {{ request('tab') == 'shipping' ? 'show active' : '' }}" id="shipping" role="tabpanel">
                <table class="table table-bordered table-striped table-hover ajaxTable datatable datatable-shipping">
                    <thead>
                        <tr>
                            <th>{{ trans('cruds.product_shipping_details.fields.id') }}</th>
                            <th>{{ trans('cruds.product_shipping_details.fields.country') }}</th>
                            <th>{{ trans('cruds.product_shipping_details.fields.duration_day') }}</th>
                            <th>{{ trans('cruds.product_shipping_details.fields.shipping_fee') }}</th>
                        </tr>
                    </thead>
                </table>
            </div>

            <!-- Product Bids Tab -->
            <div class="tab-pane fade {{ request('tab') == 'bids' ? 'show active' : '' }}" id="bids" role="tabpanel">
                <table class="table table-bordered table-striped table-hover ajaxTable datatable datatable-bids">
                    <thead>
                        <tr>
                            <th>{{ trans('cruds.product_bids.fields.id') }}</th>
                            <th>{{ trans('cruds.product_bids.fields.user_name') }}</th>
                            <th>{{ trans('cruds.product_bids.fields.bid_amount') }}</th>
                            <th>{{ trans('cruds.product_bids.fields.created_date') }}</th>
                        </tr>
                    </thead>
                </table>
            </div>

            <!-- Buyer Address Tab -->
            <div class="tab-pane fade {{ request('tab') == 'buyer_address' ? 'show active' : '' }}" id="buyer_address" role="tabpanel">
                <table class="table table-bordered table-striped">
                    <tbody>
                        <tr>
                            <th>{{ trans('cruds.buyer_details.fields.buyer_name') }}</th>
                            <td>
                                @php
                                    if(isset($buyer_details->user) && !empty($buyer_details->user)){
                                        echo ucwords($buyer_details->user->first_name.' '.$buyer_details->user->last_name);
                                    } 
                                @endphp
                            </td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.buyer_details.fields.mobile_number') }}</th>
                            <td>
                                @php
                                    if(isset($buyer_details->user) && !empty($buyer_details->user)){
                                        $country_details = getCountrydetailsById($buyer_details->user->country_id);
                                        $mobile_number = '';
                                        if(isset($country_details->top_level_domain)){
                                            $mobile_number = '<span class="d-flex">';
                                                $mobile_number .= sprintf('<img src="%s/uploads/flags/%s.png"> %s (+%s)', env('app_url'), $country_details->top_level_domain, '&nbsp;', $country_details->phone_code).' '.$buyer_details->user->phone;
                                            $mobile_number .= '</span>';
                                        } 
                                        echo $mobile_number;
                                    } 
                                @endphp
                            </td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.buyer_details.fields.shipping_duration_day') }}</th>
                            <td>
                                @php
                                    if(isset($buyer_details->shippingDetails) && !empty($buyer_details->shippingDetails)){
                                        if($buyer_details->shippingDetails->duration_day != ''){
                                            echo $buyer_details->shippingDetails->duration_day;
                                        }
                                    } 
                                @endphp
                            </td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.buyer_details.fields.shipping_fee') }}</th>
                            <td>
                                @php
                                    if(isset($buyer_details->shippingDetails) && !empty($buyer_details->shippingDetails)){
                                        if($buyer_details->shippingDetails->shipping_fee != ''){
                                            echo $buyer_details->shippingDetails->shipping_fee;
                                        }
                                    } 
                                @endphp
                            </td>
                        </tr>
                        <tr>
                            <th>{{ trans('cruds.buyer_details.fields.shipping_address') }}</th>
                            <td>
                                @php
                                    if(isset($buyer_details->user) && !empty($buyer_details->user)){
                                        if($buyer_details->user->new_address != ''){
                                            echo $buyer_details->user->new_address;
                                        } else {
                                            echo $buyer_details->user->address;
                                        }    
                                    } 
                                @endphp
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Product Shipment Detail Tab -->
            <div class="tab-pane fade {{ request('tab') == 'product-shipment-detail' ? 'show active' : '' }}" id="product-shipment-detail" role="tabpanel">
                <table class="table table-bordered table-striped">
                    <tbody>
                        <tr>
                            <th>{{ trans('cruds.product.fields.product_receipt') }}</th>
                            <td>
                                @php
                                    $product_receipt_path = isset($product_receipt) && !empty($product_receipt) ? $product_receipt->file_path : '';

                                    $extension = strtolower(pathinfo($product_receipt_path, PATHINFO_EXTENSION));

                                    $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                                @endphp
                                @if($product_receipt_path)
                                    {{-- IMAGE FILE --}}
                                    @if(in_array($extension, $imageExtensions))
                                        <a href="{{ asset($product_receipt_path) }}" class="fancybox-popup">
                                            <img src="{{ asset($product_receipt_path) }}" width="100">
                                        </a>
                                    {{-- NON-IMAGE FILE --}}
                                    @else
                                        <a href="{{ asset($product_receipt_path) }}" target="_blank" class="btn btn-sm btn-primary"> View Receipt </a>
                                    @endif
                                @else
                                    <span class="text-muted">No Receipt</span>
                                @endif
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="form-group">
            <a class="btn btn-default" href="{{ route('admin.products.index') }}">{{ trans('global.back_to_list') }}</a>
        </div>
    </div>
</div>

<div class="modal fade" id="followupModal" tabindex="-1" aria-labelledby="followupModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="followupModalLabel">{{ trans('global.enter_follow_up_message') }}</h5>
                <button type="button" class="btn-close cancel_btn" data-bs-dismiss="modal" aria-label="Close">X</button>
            </div>
            <div class="modal-body">
                <form id="followupFormMessage">
                    <textarea id="followUpMessage" class="form-control" placeholder="Enter follow up message..."></textarea>
                    <input type="hidden" id="bid_id" value="">
                    <span class="follow_up_message_error text-danger"></span>
                    <span class="follow_up_message_success text-success"></span>
                    <div class="mt-3 text-right">
                        <button type="submit" class="btn btn-success submit-btn">
                            <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                            {{ trans('global.submit') }}
                        </button>
                        <button type="button" class="btn btn-secondary cancel_btn" data-bs-dismiss="modal">{{ trans('global.cancel') }}</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="expireConfirmModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">{{ trans('global.confirm_expired') }}</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body text-center">
                <p>{{ trans('global.confirm_expired_message') }}</p>
                <input type="hidden" id="expire_bid_id">
            </div>
            <div class="modal-footer justify-content-center">
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><p>{{ trans('global.cancel') }}</p></button>
                <button type="button" class="btn btn-danger" id="confirmExpireBtn"><p>{{ trans('global.yes_expire') }}</p></button>
            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            let tabs = document.querySelectorAll(".nav-link");
            
            tabs.forEach(tab => {
                tab.addEventListener("click", function (event) {
                    event.preventDefault();
                    let newTab = this.getAttribute("href").substring(1);
                    
                    let url = new URL(window.location.href);
                    url.searchParams.set("tab", newTab);
                    window.history.pushState({}, "", url); // Update the URL without reloading
                    
                    // Activate the selected tab
                    document.querySelectorAll(".tab-pane").forEach(pane => pane.classList.remove("show", "active"));
                    document.getElementById(newTab).classList.add("show", "active");

                    // Set active class on nav links
                    tabs.forEach(t => t.classList.remove("active"));
                    this.classList.add("active");
                });
            });
        });

        $(function () {
            let table = $('.datatable-bids').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "{{ route('admin.products.bids', $product->sku) }}"
                },
                columns: [
                    { data: 'id', name: 'id' },
                    { data: 'user_name', name: 'user_name' },
                    { data: 'amount', name: 'amount' },
                    { data: 'created_at', name: 'created_at' },
                ]
            });

            $(document).on('click', '.make_winner_btn', function () {
                var bid_id = $(this).data('id');
                var product_sku = $(this).attr('rel');

                $.ajax({
                    url: "{{ route('admin.products.admin_make_winner_user') }}",
                    type: "POST",
                    data: {
                        bid_id: bid_id,
                        product_sku: product_sku,
                        _token: "{{ csrf_token() }}"
                    },
                    success: function(response) {
                        $('.message_success').removeClass('d-none');
                        $('.message_success').text(response.message);

                        table.ajax.reload();
                        
                        // setTimeout(function () {
                        //     $('.message_success').text('');
                        // }, 3000);
                    }
                });
            });

            let shipping_table = $('.datatable-shipping').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "{{ route('admin.products.shipping_details', $product->sku) }}"
                },
                columns: [
                    { data: 'id', name: 'id' },
                    { data: 'country', name: 'country' },
                    { data: 'duration_day', name: 'duration_day' },
                    { data: 'shipping_fee', name: 'shipping_fee' },
                ]
            });

            $(document).on('click', '.followup-btn', function () {
                var bid_id = $(this).data('id');
                $('#bid_id').val(bid_id);

                $('#followupModal').modal('show');
            });

            $('.cancel_btn').click(function(e) {
                $('#followUpMessage').val('');
                $('#followupModal').modal('hide');
            });

            $('#followupFormMessage').submit(function(e) {
                e.preventDefault();
                let follow_up_message = $('#followUpMessage').val();

                if (follow_up_message == '') {
                    $('.follow_up_message_error').text("{{ trans('global.follow_up_message_error') }}");
                    return;
                }
                
                $('.follow_up_message_error').text('');
                
                let submitBtn = $('.submit-btn');
                submitBtn.prop('disabled', true);
                let spinner = $('.submit-btn .spinner-border');
                
                $.ajax({
                    url: "{{ route('admin.products.user_followup_bid_message') }}",
                    type: "POST",
                    data: {
                        bid_id: $('#bid_id').val(),
                        follow_up_message: follow_up_message,
                        _token: "{{ csrf_token() }}"
                    },
                    success: function(response) {
                        $('#followUpMessage').val('');
                        
                        $('.follow_up_message_success').text(response.message);
                        
                        spinner.addClass('d-none');
                        submitBtn.prop('disabled', false);

                        setTimeout(function () {
                            $('.follow_up_message_success').text('');
                            $('#followupModal').modal('hide');
                        }, 3000);
                    },
                    error: function(xhr) {
                        alert("{{ trans('global.something_went_wrong') }}");

                        spinner.addClass('d-none');
                        submitBtn.prop('disabled', false);
                    }
                });
            });

            $(document).on('click', '.expire_now', function () {
                let bidId = $(this).data('id');

                $('#expire_bid_id').val(bidId);
                $('#expireConfirmModal').modal('show');
            });

            $('#confirmExpireBtn').on('click', function () {
                let bidId = $('#expire_bid_id').val();

                $.ajax({
                    url: "{{ route('admin.products.user_bid_winner_expire') }}",
                    type: "POST",
                    data: {
                        _token: "{{ csrf_token() }}",
                        bid_id: bidId
                    },
                    success: function (response) {
                        $('#expireConfirmModal').modal('hide');

                        if (response.status === 'success') {
                            $('.message_success').removeClass('d-none');
                            $('.message_success').text(response.message);

                            table.ajax.reload();
                        }
                    },
                    error: function () {
                        alert("{{ trans('global.something_went_wrong') }}");
                    }
                });
            });
        });
    </script>
@endsection