@extends('frontend::layouts.app')
@section('title')
    {{ __('Checkout') }}
@endsection
@section('content')
    <form class="td-checkout has-sticky" action="{{ route('user.booking.place', $space?->id) }}" method="POST">
        @method('POST')
        @csrf
        <div class="container">
            <div class="row g-4">
                <div class="col-lg-7">
                    <div class="td-checkout-left">
                        <div class="td-checkout-left-title">
                            <h2>{{ __('Booking Details') }}</h2>
                        </div>
                        @foreach ($errors->all() as $error)
                            <div class="alert alert-danger">{{ $error }}</div>
                        @endforeach
                        <div class="td-checkout-left-forms common-form">
                            <div class="row g-2 g-sm-4">
                                <div class="col-lg-12">
                                    <div class="dropdown custom-select-dropdown">
                                        <button class="dropdown-toggle" type="button" id="dropdownMenuButton1"
                                            data-bs-toggle="dropdown" aria-expanded="false">
                                            @if ($space)
                                                <span class="custom-select-dropdown-full">
                                                    <span class="custom-select-full">
                                                        <span class="custom-select-full-left">
                                                            <span class="card-img">
                                                                <img src="{{ asset($space->banner_image) }}" alt="">
                                                            </span>
                                                            <span>
                                                                <span class="space-name">{{ $space->title }}</span>
                                                                <span
                                                                    class="space-duration">{{ ucfirst($space->price_type) }}</span>
                                                            </span>
                                                        </span>
                                                        <span
                                                            class="space-price">{{ $currencySymbol . $space->price }}</span>
                                                    </span>
                                                </span>
                                            @else
                                                <span>{{ __('Select Space') }}</span>
                                            @endif
                                        </button>
                                        <ul class="dropdown-menu custom-dropdown-menu overflow-y">
                                            @foreach ($spaces as $spaceList)
                                                <li
                                                    onclick="window.location.href = '{{ route('user.booking.checkout', encrypt($spaceList->id)) }}'">
                                                    <span
                                                        class="custom-select-dropdown-full custom-select-dropdown-full-option">
                                                        <span class="custom-select-full">
                                                            <span class="custom-select-full-left">
                                                                <span class="card-img">
                                                                    <img src="{{ asset($spaceList->banner_image) }}"
                                                                        alt="{{ $spaceList->title }}">
                                                                </span>
                                                                <span>
                                                                    <span class="space-name">{{ $spaceList->title }}</span>
                                                                    <span
                                                                        class="space-duration">{{ ucfirst($spaceList->price_type) }}</span>
                                                                </span>
                                                            </span>
                                                            <span
                                                                class="space-price">{{ $currencySymbol . $spaceList->price }}</span>
                                                        </span>
                                                    </Span>
                                                </li>
                                            @endforeach
                                        </ul>
                                    </div>
                                </div>
                                @if ($space)
                                    <div class="col-lg-12">
                                        <div class="form-floating common-form-item">
                                            <input type="number" name="stock" value="" class="form-control"
                                                placeholder="{{ __('Enter your stock') }}" min="1"
                                                max="{{ $space->stock ?? 0 }}" id="stock">
                                            <label for="stock">{{ __('Stock') }}*</label>
                                            <small class="text-success mt-1 d-block">
                                                {{ __('Available Stock') }}: {{ $space->stock ?? 0 }}
                                            </small>
                                        </div>
                                    </div>
                                    @php
                                        $label = match ($space->price_type) {
                                            'hourly' => __('Number Of Hours'),
                                            'weekly' => __('Number Of Week'),
                                            'daily' => __('Number Of Days'),
                                            'monthly' => __('Number Of Month'),
                                            'yearly' => __('Number Of Year'),
                                        };
                                    @endphp
                                    <div class="col-lg-12">
                                        <div class="form-floating common-form-item">
                                            <input type="number" name="duration"
                                                value="{{ $space->duration_type === 'fixed' ? $space->fixed_duration : '' }}"
                                                class="form-control" placeholder="{{ $label }} " min="1"
                                                id="duration" @readonly($space->duration_type === 'fixed')>
                                            <label for="duration">{{ $label }}*</label>
                                        </div>
                                    </div>
                                    <div class="col-lg-6">
                                        <div class="form-floating common-form-item">
                                            <input name="from_date" type="text" class="form-control"
                                                placeholder="YYYY-MM-DD" id="date-from" required>
                                            <label for="date-from">{{ __('Booking From') }}*</label>
                                        </div>
                                    </div>
                                    <div class="col-lg-6">
                                        <div class="form-floating common-form-item">
                                            <input name="to_date" type="text" class="form-control"
                                                placeholder="YYYY-MM-DD" id="date-to" readonly>
                                            <label for="date-to">{{ __('Booking To') }}*</label>
                                        </div>
                                    </div>
                                @endif
                            </div>
                        </div>
                    </div>
                    @if ($space)
                        <div class="td-checkout-left-title mt-5">
                            <h2>{{ __('Billing Details') }}</h2>
                        </div>
                        <div class="td-checkout-left-forms common-form">
                            <div class="row g-2 g-sm-4">
                                <div class="col-lg-6">
                                    <div class="form-floating common-form-item">
                                        <input type="text" class="form-control" id="floatingInput"
                                            placeholder="First Name" name="first_name" value="{{ $user->first_name }}"
                                            required>
                                        <label for="floatingInput">{{ __('First Name') }}</label>
                                    </div>
                                </div>
                                <div class="col-lg-6">
                                    <div class="form-floating common-form-item">
                                        <input type="text"name="last_name" value="{{ $user->last_name }}"
                                            class="form-control" id="floatingInput2" placeholder="Last Name" required>
                                        <label for="floatingInput2">{{ __('Last Name') }}</label>
                                    </div>
                                </div>
                                <div class="col-lg-6">
                                    <div class="form-floating common-form-item">
                                        <input type="email" name="email" value="{{ $user->email }}"
                                            class="form-control" id="floatingInput3" placeholder="Email" required>
                                        <label for="floatingInput3">{{ __('Email') }}</label>
                                    </div>
                                </div>
                                <div class="col-lg-6">
                                    <div class="form-floating common-form-item">
                                        <input type="text" name="phone" value="{{ $user->phone }}"
                                            class="form-control" id="floatingInput4" placeholder="Phone" required>
                                        <label for="floatingInput4">{{ __('Phone') }}</label>
                                    </div>
                                </div>
                                <div class="col-lg-6">
                                    <div class="form-floating common-form-item">
                                        <input type="text" name="address" value="{{ $user->address }}"
                                            class="form-control" id="floatingInput6" placeholder="Location" required>
                                        <label for="floatingInput6">{{ __('Address') }}</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endif
                </div>
                <div class="col-lg-5">
                    <div class="td-checkout-right">
                        <div class="td-checkout-right-title wow img-custom-anim-left" data-wow-duration="1.5s"
                            data-wow-delay="0.1s">
                            <h2>{{ __('Space Details') }}</h2>
                        </div>
                        @if ($space)
                            <div class="td-checkout-right-card">
                                <img class="wow img-custom-anim-top" data-wow-duration="1.5s" data-wow-delay="0.1s"
                                    src="{{ asset($space?->banner_image) }}" alt="">
                                <ul class="other-facilities">
                                    <h2>{{ __('Other Facilities') }}</h2>
                                    @foreach ($space?->facilities as $key => $facility)
                                        <li class="check-facilities">
                                            <div class="form-check">
                                                <input class="form-check-input facility-checkbox" type="checkbox"
                                                    name="facilities[]" value="{{ $key }}"
                                                    data-price="{{ $facility['price'] }}"
                                                    id="facility{{ $key }}">
                                                <label class="form-check-label" for="facility{{ $key }}">
                                                    {{ $facility['title'] }} - {{ $currencySymbol . $facility['price'] }}
                                                </label>
                                            </div>
                                        </li>
                                    @endforeach
                                </ul>

                                <div class="td-checkout-right-card-content">
                                    <div class="td-checkout-right-card-content-row">
                                        <p class="title">{{ 'From' }}</p>
                                        <p id="from-date-display">--/--/----</p>
                                    </div>
                                    <div class="td-checkout-right-card-content-row">
                                        <p class="title">{{ __('To') }}</p>
                                        <p id="to-date-display">--/--/----</p>
                                    </div>

                                    <div class="td-checkout-right-card-content-row">
                                        <p class="title">{{ __('Duration') }}</p>
                                        <p id="duration-display">--</p>
                                    </div>
                                    <div class="td-checkout-right-card-content-row">
                                        <p class="title">{{ __('Stock') }}</p>
                                        <p id="stock-display">--</p>
                                    </div>
                                    <div class="td-checkout-right-card-content-row">
                                        <p class="title">{{ __('Price') }}</p>
                                        <p>{{ $currencySymbol }}<span id="base-price-display">{{ $space?->price }}</span>
                                        </p>
                                    </div>
                                    <small>{{ $currencySymbol . $space?->price }} x <span
                                            id="space-duration-display"></span> x <span
                                            id="stock-calculation-display">1</span>
                                    </small>
                                    <div class="td-checkout-right-card-content-row">
                                        <p class="title">{{ __('Facilities Cost') }}</p>
                                        <p>{{ $currencySymbol }}<span id="facilities-cost-display">0.00</span></p>
                                    </div>
                                </div>

                                <div class="td-checkout-right-card-total">
                                    <div class="td-checkout-right-card-total-row">
                                        <p class="title">{{ __('Total Cost') }}</p>
                                        <p>{{ $currencySymbol }}<span id="total-cost-display">0.00</span></p>
                                    </div>
                                </div>
                            </div>
                        @else
                            <div class="td-checkout-right-card">
                                <h6>{{ __('Please Select Your Space.') }}</h6>
                            </div>
                        @endif

                        <div class="td-checkout-right-checkoutButton">
                            <button type="submit" class="td-btn td-btn-xl td-btn-fullWidth" @disabled(!$space)>
                                <span class="td-btn-wrap">
                                    <span class="td-btn-y-1">{{ __('Book Now') }}</span>
                                    <span class="td-btn-y-2">{{ __('Book Now') }}</span>
                                </span>
                                <i></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        </div>
    </form>
@endsection

@push('js')
    <script>
        $(document).ready(function() {
            "use strict";

            $('#date-from').flatpickr({
                dateFormat: "d/m/Y h:i K",
                time_24hr: false,
                enableTime: true,
            });

            // Redirecting after change space selection
            $('select[name=space_id]').on('change', function() {
                const spaceBookingUrl = $(this).val();
                window.location.href = spaceBookingUrl;
            });

            const dateFromInput = document.getElementById('date-from');
            const dateToInput = document.getElementById('date-to');
            const fromDateDisplay = document.getElementById('from-date-display');
            const toDateDisplay = document.getElementById('to-date-display');
            const enterDurationInput = document.getElementById('duration');
            const priceType = @json($space?->price_type)

            dateFromInput.addEventListener('input', function() {
                fromDateDisplay.textContent = this.value || '--/--/----';
                calculateBookingTo();
            });

            function parseDate(dateString) {
                const parts = dateString.split(/[/ ]/);
                const day = parseInt(parts[0]);
                const month = parseInt(parts[1]) - 1;
                const year = parseInt(parts[2]);
                const timeParts = parts[3].split(':');
                let hour = parseInt(timeParts[0]);
                const minute = parseInt(timeParts[1]);
                const ampm = parts[4];

                if (ampm.toUpperCase() === "PM" && hour !== 12) {
                    hour += 12;
                } else if (ampm.toUpperCase() === "AM" && hour === 12) {
                    hour = 0; // Midnight case
                }

                return new Date(year, month, day, hour, minute);
            }

            function calculateBookingTo() {
                const fromDate = parseDate(dateFromInput.value);
                const duration = parseFloat(enterDurationInput.value);

                const spaceDurationDisplay = document.getElementById('space-duration-display');
                spaceDurationDisplay.textContent = duration;

                if (!isNaN(duration) && !isNaN(fromDate.getTime())) {
                    let toDate;

                    if (priceType === 'hourly') {
                        toDate = new Date(fromDate.getTime() + duration * 60 * 60 * 1000);
                    } else if (priceType === 'daily') {
                        toDate = new Date(fromDate);
                        toDate.setDate(toDate.getDate() + duration);
                    } else if (priceType === 'weekly') {
                        toDate = new Date(fromDate);
                        toDate.setDate(toDate.getDate() + duration * 7);
                    } else if (priceType === 'monthly') {
                        toDate = new Date(fromDate);
                        toDate.setMonth(toDate.getMonth() + duration);
                    } else if (priceType === 'yearly') {
                        toDate = new Date(fromDate);
                        toDate.setFullYear(toDate.getFullYear() + duration);
                    }

                    // Format the "toDate" to match the "fromDate" style
                    const formattedToDate = formatDate(toDate);
                    toDateDisplay.textContent = formattedToDate;
                    dateToInput.value = formattedToDate;
                } else {
                    toDateDisplay.textContent = '--/--/---- --:--';
                    dateToInput.value = '';
                }
                updateFormValues();
            }

            function formatDate(date) {
                const options = {
                    day: '2-digit',
                    month: '2-digit',
                    year: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: true,
                };
                const localeString = date.toLocaleString('en-US', options);
                const [datePart, timePart] = localeString.split(', ');
                const [month, day, year] = datePart.split('/');
                return `${day}/${month}/${year} ${timePart}`;
            }

            // Attach event listeners
            enterDurationInput.addEventListener('input', calculateBookingTo);

            const durationDisplay = document.getElementById('duration-display');
            const totalCostDisplay = document.getElementById('total-cost-display');
            const facilityCheckboxes = document.querySelectorAll('.facility-checkbox');
            const basePriceDisplay = document.getElementById('base-price-display');
            const facilityCostDisplay = document.getElementById('facilities-cost-display');

            const stockInput = document.getElementById('stock');
            const stockDisplay = document.getElementById('stock-display');
            stockInput.addEventListener('input', updateStockDisplay);
            const stockCalculationDisplay = document.getElementById('stock-calculation-display');

            function updateStockDisplay() {
                const stock = stockInput.value || '1';
                stockDisplay.textContent = stock;
                stockCalculationDisplay.textContent = stock;
                updateFormValues();
            }
            const basePrice = parseFloat(@json($space?->price));
            const displayPriceType = priceType === 'hourly' ? 'Hour' :
                priceType === 'daily' ? 'Day' :
                priceType === 'monthly' ? 'Month' :
                priceType === 'yearly' ? 'Year' : '';

            function updateFormValues() {
                const fromDate = new Date(dateFromInput.value);
                const toDate = new Date(dateToInput.value);

                // Calculate duration based on price type
                const durationInUnits = enterDurationInput.value;
                const stockValue = parseInt(stockInput.value) || 1;


                // Calculate total cost including stock
                let baseCost = durationInUnits * basePrice * stockValue;
                console.log(stockInput.value);
                console.log(baseCost);
                let facilityCost = 0;

                // Add facility prices
                facilityCheckboxes.forEach(checkbox => {
                    if (checkbox.checked) {
                        const facilityPrice = parseFloat(checkbox.getAttribute('data-price')) || 0;
                        facilityCost += facilityPrice * durationInUnits;
                    }
                });

                let totalCost = baseCost + facilityCost;

                // Update visible fields
                fromDateDisplay.textContent = dateFromInput.value || '--/--/----';
                toDateDisplay.textContent = dateToInput.value || '--/--/----';
                durationDisplay.textContent =
                    durationInUnits > 0 ? `${durationInUnits} ${displayPriceType}` + (durationInUnits > 1 ? 's' :
                        '') : '--';
                totalCostDisplay.textContent = totalCost.toFixed(2);
                basePriceDisplay.textContent = baseCost.toFixed(2);
                facilityCostDisplay.textContent = facilityCost.toFixed(2);
            }

            // Attach event listeners
            dateToInput.addEventListener('input', updateFormValues);
            facilityCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', updateFormValues);
            });
        });
    </script>
@endpush
