


{{-- <h2>Order Tracking Result</h2>

<p><strong>Order ID:</strong> {{ $order->id }}</p>
<p><strong>Tracking Number:</strong> {{ $order->tracking_number }}</p>
<p><strong>Status:</strong> {{ $order->status }}</p>
<p><strong>Expected Delivery:</strong> {{ $order->delivery_date ?? 'N/A' }}</p> --}}


@extends('layouts.trackpage')

@section('title', 'Orders Deatils '. $order->id)

@section('content')

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/themify-icons/0.1.0/css/themify-icons.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/themify-icons/0.1.0/css/themify-icons.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet">

<style>
    .floating-btn {
    position: fixed;
    bottom: 50px;
    right: 20px;
    background-color: #aa7ece; /* Twitter Blue */
    color: #fff;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    font-size: 24px;
    text-decoration: none;
    border: none;
    cursor: pointer;
    transition: background 0.3s ease, transform 0.2s ease;
}

.floating-btn:hover {
    background-color: #b18cb4; /* Darker shade on hover */
    transform: scale(1.1);
}

.floating-btn i {
    font-size: 24px; /* Adjust icon size */
}
</style>

<style>
    .countdown-container {
        position: relative;
        width: 150px;
        height: 150px;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 18px;
        color: #333;
        font-weight: bold;
        text-align: center;
        background: #e5e5e5; /* Light grey background for the circle */
    }

    .countdown-text {
        position: absolute;
        font-size: 16px;
        z-index: 10;
    }

    .circle {
        width: 100%;
        height: 100%;
        position: absolute;
        background: conic-gradient(#22bd6f 0deg, #e5e5e5 0deg 100%);
        border-radius: 50%;
        transition: background 0.5s ease-in-out;
    }

    .countdown-text-small {
        font-size: 14px;
        line-height: 1.2;
    }
</style>
<main>

    <div class="container-fluid">
<!-- Breadcrumb start -->
<div class="m-1 row">
<div class="col-12 ">
    <h4 class="main-title">Orders Details</h4>
    <ul class="mb-3 app-line-breadcrumbs">
        <li class="">
            <a href="#" class="f-s-14 f-w-500">
          <span>
            <i class="ph-duotone ph-stack f-s-16"></i>
          </span>
            </a>
        </li>

    </ul>
</div>
</div>
<!-- Breadcrumb end -->

<!-- Order Details start -->
<div class="row order-details">
<div class="col-xxl-9">
    <div class="row">
        <!-- Order Details start -->
        <div class="col-lg-4">
            <div class="card order-details-card">
                <div class="card-header">
                    <h5 class="text-nowrap">Order Details (#{{ $order->id }})</h5>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <h6 class="f-w-600 text-dark"><i class="ti ti-calendar f-s-18 me-2 text-secondary"></i>Date</h6>
                        <div class="text-end">
                            <p>{{ $order->created_at->format('d M, Y h:i A') }}</p>
                        </div>
                    </div>
                    <div class="mt-3 d-flex justify-content-between">
                        <h6 class="f-w-600 text-dark"><i class="ti ti-credit-card f-s-18 me-2"></i>Payment</h6>
                        <div class="text-end">
                            <p>Wallet</p>
                        </div>
                    </div>
                    <div class="mt-3 d-flex justify-content-between">
                        <h6 class="f-w-600 text-dark"><i class="ti ti-truck-delivery f-s-18 me-2"></i>Shipping</h6>
                        <div  class="text-end">
                            <p id="countdownDisplay_{{ $order->id }}" class="mt-1 text-success small"></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Order Details end -->
        {{-- <p>Description: {{ $order->description }}</p>
        <p>Status: {{ $order->status }}</p>
        <p>Order Date: {{ $order->created_at }}</p>
        <p>Shipping Cost: {{ $order->shipping_cost }}</p> --}}

        <!-- Customer Details start -->
        {{-- <div class="col-lg-4">
            <div class="card order-details-card">
                <div class="card-header">
                    <h5>Customer Details</h5>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <h6 class="f-w-600 text-dark"><i class="ti ti-file-invoice text-secondary f-s-18 me-2"></i>Customer</h6>
                        <div class="text-end">
                            <p>{{ $order->user->fname ?? 'N/A' }}{{ $order->user->lname ?? 'N/A' }}</p>
                        </div>
                    </div>
                    <div class="mt-3 d-flex justify-content-between">
                        <h6 class="f-w-600 text-dark"><i class="ti ti-mail f-s-18 text-secondary me-2"></i>Email</h6>
                        <div class="text-end">
                            <p>{{ $order->user->email ?? 'N/A' }}</p>
                        </div>
                    </div>
                    <div class="mt-3 d-flex justify-content-between">
                        <h6 class="f-w-600 text-dark"><i class="ti ti-device-mobile f-s-18 text-secondary me-2"></i>contact</h6>
                        <div class="text-end">
                            <p>{{ $order->user->phone ?? 'N/A' }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div> --}}
        <!-- Customer Details end -->

        <!-- Documents start -->
        <div class="col-lg-4">
            <div class="card order-details-card">
                <div class="card-header">
                    <h5>Documents</h5>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <h6 class="f-w-600 text-dark"><i class="ti ti-file-invoice text-secondary f-s-18 me-2"></i>Mark Name:</h6>
                        <div class="text-end">
                            <p> {{ $order->user->mark ?? 'N/A' }}</p>
                        </div>
                    </div>
                    <div class="mt-3 d-flex justify-content-between">
                        <h6 class="f-w-600 text-dark"><i class="ti ti-truck-delivery f-s-18 text-secondary me-2"></i>Tracking</h6>
                        <div class="text-end">
                            <p>#{{ $order->tracking_number }}</p>
                        </div>
                    </div>
                    <div class="mt-3 d-flex justify-content-between">
                        <h6 class="f-w-600 text-dark"><i class="ti ti-award f-s-18 text-secondary me-2"></i>Shipping Cost</h6>
                        <div class="text-end">
                            <p>{{ $order->shipping_cost }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Documents end -->
    </div>
    {{-- <button class="btn btn-sm btn-primary"  data-bs-toggle="modal" data-bs-target="#updateDaysModal{{ $order->id }}">
        Update Days
    </button> --}}



    {{-- <div class="progress">
        <div class="progress-bar progress-bar-striped bg-success" role="progressbar"
            style="width: {{ (1 - $order->days_to_destination / Carbon\Carbon::parse($order->delivery_date)->diffInDays(now())) * 100 }}%"
            aria-valuenow="{{ $order->days_to_destination }}" aria-valuemin="0" aria-valuemax="100">
            {{ $order->days_to_destination }} Days Remaining
        </div>
    </div> --}}

    <!-- Update Days Modal -->
 <!-- Update Days Modal -->
 <div class="modal fade" id="updateDaysModal{{ $order->id }}" tabindex="-1" aria-labelledby="updateDaysModalLabel{{ $order->id }}" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <form action="{{ route('orders.updateDays', $order->id) }}" method="POST">
          @csrf
          @method('PUT')

          <div class="modal-header">
            <h5 class="modal-title" id="updateDaysModalLabel{{ $order->id }}">Update Delivery Days</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>

          <div class="modal-body">
            <div class="mb-3">
              <label for="days_to_destination" class="form-label">Days to Destination</label>
              <input type="number" class="form-control" name="days_to_destination" id="daysInput{{ $order->id }}" min="0" value="{{ $order->days_to_destination }}" required oninput="updateCountdown({{ $order->id }})">
            </div>
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-primary">Update</button>
          </div>
        </form>
      </div>
    </div>
  </div>




    <!-- Order start -->
    <div class="card">
        <p id="countdownDisplay_{{ $order->id }}" class="mt-1 text-success small"></p>

        <div id="countdownDisplay_{{ $order->id }}" class="countdown-container">
            <div class="circle" id="progressCircle_{{ $order->id }}"></div>
            <div class="countdown-text" id="countdownText_{{ $order->id }}">
                ⏳ <br />
                <span class="countdown-text-small">Loading...</span>
            </div>
        </div>
        <div class="card-header">

        </div>
        <div class="p-0 card-body">
            <div class="orders-details-datatable app-datatable-default app-scroll table-responsive">
                <table class="table mb-0 text-center align-middle table-bottom-border">
                    <thead>
                    <tr>
                        <th scope="col" class="text-start">Product Details</th>
                        <th>Status</th>
                        <th scope="col">number of Sacks/Box</th>
                        <th scope="col">Expected Date</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                        <td class="f-w-600">{{ $order->description }}</td>
                        <td><span class="badge text-light-danger">{{ $order->status }}</span></td>
                        <td class="f-w-600">{{ $order->qty }}</td>
                        <td class="text-success f-w-500">{{ $order->delivery_date  }}</td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="card-footer">
            <div class="flex-wrap d-flex justify-content-between align-items-center">
                <p class="text-secondary"> </p>
            </div>
        </div>
    </div>
    <!-- Order end -->

</div>


<!-- Order Status start -->
<div class="col-xxl-3">
    <div class="card equal-card">
        <div class="card-header">
            <h5>Order Status</h5>
        </div>
        <div class="card-body">
            <ul class="app-timeline-box">
                @php
                    // Updated status map with new statuses
                    $statusMap = [
                        'Received in China' => ['color' => 'primary', 'icon' => 'ph-duotone ph-map-pin'],
                        'In Transit' => ['color' => 'secondary', 'icon' => 'ph-duotone ph-truck'],
                        'Received in Ghana' => ['color' => 'info', 'icon' => 'ph-duotone ph-map-trifold'],
                        'Available for Pickup' => ['color' => 'warning', 'icon' => 'ph-duotone ph-checks'],
                        'Completed' => ['color' => 'dark', 'icon' => 'ph-duotone ph-check-circle'],
                        'pending'    => ['icon' => 'ti-clock', 'color' => 'secondary'],
                        'loading'    => ['color' => 'info', 'icon' => 'ph-duotone ph-map-trifold'],
                        'departed'   => ['icon' => 'ti-rocket', 'color' => 'info'],
                        'Transit' => ['icon' => 'ti-road', 'color' => 'primary'],
                        'at port'    => ['icon' => 'ti-anchor', 'color' => 'dark'],
                        'discharged' => ['icon' => 'ti-box', 'color' => 'success'],
                        'delivered'  => ['icon' => 'ti-check', 'color' => 'success'],
                    ];
                @endphp

                @forelse($order->history as $history)
                    @php
                        // Get the status info from the statusMap or default to a fallback
                        $statusInfo = $statusMap[$history->status] ?? ['color' => 'dark', 'icon' => 'ti-alert'];
                        $formattedDate = \Carbon\Carbon::parse($history->date_updated)->format('D, d M Y - h:i A');
                    @endphp
                    <li class="timeline-section">
                        <div class="timeline-icon">
                            <!-- Apply the status color dynamically -->
                            <span class="text-light-{{ $statusInfo['color'] }} h-35 w-35 d-flex-center b-r-50">
                                <i class="{{ $statusInfo['icon'] }} f-s-20"></i>
                            </span>
                        </div>
                        <div class="timeline-content bg-light-{{ $statusInfo['color'] }} b-1-{{ $statusInfo['color'] }}">
                            <h6 class="text-{{ $statusInfo['color'] }}">{{ $history->status }}</h6>
                            <p class="text-secondary">{{ $formattedDate }}</p>
                            <p>{{ $history->description ?? 'No details provided.' }}</p>
                        </div>
                    </li>
                @empty
                    <!-- If no statuses exist, show "No status" message -->
                    <li class="timeline-section">
                        <div class="timeline-icon">
                            <span class="text-light-dark h-35 w-35 d-flex-center b-r-50">
                                <i class="ti-alert f-s-20"></i>
                            </span>
                        </div>
                        <div class="p-4 rounded-lg timeline-content bg-light-dark b-1-dark"
                        style="background-image: url('{{ asset('assets/i.jpg') }}'); background-size: cover; background-position: center; min-height: 300px;">
                       <div class="text-center text-white">
                           <h6 class="mb-3 text-uppercase font-weight-bold">No Status</h6>
                           <!-- Optional message can go here -->
                       </div>
                   </div>
                    </li>
                @endforelse
            </ul>
        </div>
    </div>
</div>



<!-- Order Status end -->
</div>
<!-- Order Details end -->
</div>
</main>
<!-- Main Section end -->
</div>
<!-- Update Order Modal -->


<!-- Floating Button -->
{{-- <button class="floating-btn" data-bs-toggle="modal" data-bs-target="#updateOrderModal">
    <i class="ti ti-plus"></i>
</button> --}}
<!-- tap on top -->
<div class="go-top">
<span class="progress-value">
<i class="ti ti-chevron-up"></i>
</span>
</div>

<script>
    function startLiveCountdown(id, deliveryDateStr) {
        const el = document.getElementById(`countdownText_${id}`);
        const progressCircle = document.getElementById(`progressCircle_${id}`);
        if (!el || !progressCircle || !deliveryDateStr) return;

        const deliveryDate = new Date(deliveryDateStr);

        const update = () => {
            const now = new Date();
            const distance = deliveryDate - now;

            if (distance <= 0) {
                // Time is up: show complete circle and message
                el.innerText = "✅ Delivered or overdue";
                progressCircle.style.background = "conic-gradient(#22bd6f 0deg, #4d5bf9 360deg)"; // Full blue circle
                return;
            }

            const days = Math.floor(distance / (1000 * 60 * 60 * 24));
            const hours = Math.floor((distance / (1000 * 60 * 60)) % 24);
            const minutes = Math.floor((distance / (1000 * 60)) % 60);
            const seconds = Math.floor((distance / 1000) % 60);

            // Calculate total time in seconds
            const totalTime = (deliveryDate - new Date()) / 1000;

            // Calculate the progress percentage (how much time has passed)
            const elapsedTime = (totalTime - (distance / 1000)); // Time passed since the start
            const progress = (elapsedTime / totalTime) * 360; // Converting to degrees (0-360)

            // Update the progress circle with conic-gradient
            progressCircle.style.background = `conic-gradient(#22bd6f ${progress}deg, #e5e5e5 ${progress}deg 100%)`;

            // Format time
            const format = (num) => String(num).padStart(2, '0');

            // Display countdown text
            el.innerHTML = `⏳ ${format(days)}d ${format(hours)}h <br />
            ${format(minutes)}m ${format(seconds)}s left`;
        };

        // Initial update
        update();

        // Update every second (1000 milliseconds)
        setInterval(update, 1000);
    }

    @if($order->delivery_date)
        startLiveCountdown("{{ $order->id }}", "{{ $order->delivery_date }}");
    @endif
</script>
<script>
    function updateCountdown(orderId) {
        const input = document.getElementById(`daysInput${orderId}`);
        const display = document.getElementById(`countdownDisplay${orderId}`);
        if (!input || !display) return;

        const days = parseInt(input.value || 0);
        const totalSeconds = days * 24 * 60 * 60;

        let countdown = totalSeconds;

        // Clear previous interval if any
        if (window[`interval_${orderId}`]) {
            clearInterval(window[`interval_${orderId}`]);
        }

        function render() {
            if (countdown <= 0) {
                display.textContent = 'Expired';
                clearInterval(window[`interval_${orderId}`]);
                return;
            }

            const d = Math.floor(countdown / (3600 * 24));
            const h = Math.floor((countdown % (3600 * 24)) / 3600);
            const m = Math.floor((countdown % 3600) / 60);
            const s = countdown % 60;

            display.textContent = `${d}d ${h}h ${m}m ${s}s`;
            countdown--;
        }

        render(); // Initial render
        window[`interval_${orderId}`] = setInterval(render, 1000);
    }

    // Auto-init when modal is shown
    document.addEventListener('DOMContentLoaded', () => {
        const modals = document.querySelectorAll('[id^="updateDaysModal"]');
        modals.forEach(modal => {
            modal.addEventListener('shown.bs.modal', () => {
                const orderId = modal.id.replace('updateDaysModal', '');
                updateCountdown(orderId);
            });
        });
    });
</script>

<script>
    function startLiveCountdown(id, deliveryDateStr) {
        const el = document.getElementById(`countdownDisplay_${id}`);
        if (!el || !deliveryDateStr) return;

        // Convert the provided string into a Date object
        const deliveryDate = new Date(deliveryDateStr);

        const update = () => {
            const now = new Date(); // Get the current date/time
            const distance = deliveryDate - now; // Calculate the remaining time

            if (distance <= 0) {
                el.innerText = "✅ Delivered or overdue"; // If time is up
                return;
            }

            // Calculate days, hours, minutes, and seconds left
            const days = Math.floor(distance / (1000 * 60 * 60 * 24));
            const hours = Math.floor((distance / (1000 * 60 * 60)) % 24);
            const minutes = Math.floor((distance / (1000 * 60)) % 60);
            const seconds = Math.floor((distance / 1000) % 60);

            // Format time to always display two digits (e.g., 03, 05, etc.)
            const format = (num) => String(num).padStart(2, '0');

            // Display the countdown
            el.innerText = `⏳ ${format(days)}d ${format(hours)}h ${format(minutes)}m ${format(seconds)}s left`;
        };

        // Initial update
        update();

        // Update every second (1000 milliseconds)
        setInterval(update, 1000);
    }

    // Ensure the countdown only starts if the delivery_date exists
    @if($order->delivery_date)
        startLiveCountdown("{{ $order->id }}", "{{ $order->delivery_date }}");
    @endif
</script>
<script>
    function adjustDays(value) {
        let remainingDays = parseInt(document.getElementById('remainingDays').innerText);
        let newDays = remainingDays + value;

        if (newDays < 0) {
            alert("Cannot reduce days below 0!");
            return;
        }

        document.getElementById('remainingDays').innerText = newDays;

        // Update Progress Bar
        let progressBar = document.getElementById('progressBar');
        let progress = Math.max(0, (100 - (newDays / 30) * 100));
        progressBar.style.width = progress + "%";
        progressBar.innerText = Math.round(progress) + "%";
    }
    </script>
@endsection
