@extends('web.home.layout.master')

@section('content')
    @php
        $orderData = App\Models\Order::where('id', $id)->first();
        $subTotal = $orderData->total ?? 0;
        $taxAmount = $orderData->tax_amount ?? 0;
        $serviceFee = $orderData->service_fee ?? 0;
        $discountAmount = $orderData->discount_amount ?? 0;
        $grandTotal = $subTotal + $taxAmount + $serviceFee - $discountAmount;

        // Progress Calculation
        $activeCount = 1;
        if ($orderData->processing == 1) {
            if ($orderData->ready == 1) {
                $activeCount = 2;
                if ($orderData->picked == 1) {
                    $activeCount = 3;
                    if ($orderData->on_the_way == 1) {
                        $activeCount = 4;
                        if ($orderData->delivered == 1) {
                            $activeCount = 5;
                        }
                    }
                }
            }
        } else {
            $activeCount = 0;
        }
        $progressWidth = $activeCount > 0 ? (($activeCount - 1) * 25) : 0;
    @endphp

    <section class="order-detail-section">
        <div class="order-detail-container">
            <div class="detail-main-card">
                
                <!-- Card Header -->
                <div class="detail-card-header">
                    <div class="header-left">
                        <span class="back-link-breadcrumb"><a href="{{ route('american.plastic.web.myprofile') }}?tab=order">My Profile</a> / Order Tracking</span>
                        <h2 class="header-title">Order Status Details</h2>
                    </div>
                    <div class="header-right">
                        <span class="order-id-label">Order ID</span>
                        <code class="order-id-val">#{{ $orderData->order_id }}</code>
                    </div>
                </div>

                <div class="detail-card-body">
                    
                    @if ($orderData->processing == 0 && $orderData->cancellation == 1)
                        <div class="custom-alert-banner alert-danger mb-4">
                            <i class="fas fa-times-circle me-2"></i>
                            <span>This order has been cancelled.</span>
                        </div>
                    @elseif ($orderData->processing == 0 && $orderData->cancellation == 0)
                        <div class="custom-alert-banner alert-warning mb-4">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <span>Cancellation has been requested for this order.</span>
                        </div>
                    @endif

                    <!-- Section 1: Order Metadata Cards -->
                    <div class="order-meta-grid mb-4">
                        <div class="meta-item-card">
                            <div class="meta-icon date-icon">
                                <i class="far fa-calendar-alt"></i>
                            </div>
                            <div class="meta-info">
                                <span class="meta-label">Ordered At</span>
                                <h4 class="meta-value">{{ \Carbon\Carbon::parse($orderData->created_at)->format('M j, Y') }}</h4>
                            </div>
                        </div>

                        <div class="meta-item-card">
                            <div class="meta-icon courier-icon">
                                <i class="fas fa-truck"></i>
                            </div>
                            <div class="meta-info">
                                <span class="meta-label">Shipping By</span>
                                <h4 class="meta-value">American Plastics</h4>
                            </div>
                        </div>

                        <div class="meta-item-card">
                            <div class="meta-icon status-icon">
                                <i class="fas fa-info-circle"></i>
                            </div>
                            <div class="meta-info">
                                <span class="meta-label">Order Status</span>
                                <h4 class="meta-value text-green-accent">
                                    @if ($orderData->processing == 1 && $orderData->ready == 0 && $orderData->picked == 0 && $orderData->on_the_way == 0 && $orderData->delivered == 0)
                                        Processing
                                    @elseif ($orderData->processing == 1 && $orderData->ready == 1 && $orderData->picked == 0 && $orderData->on_the_way == 0 && $orderData->delivered == 0)
                                        Ready for pickup
                                    @elseif ($orderData->processing == 1 && $orderData->ready == 1 && $orderData->picked == 1 && $orderData->on_the_way == 0 && $orderData->delivered == 0)
                                        Shipped
                                    @elseif ($orderData->processing == 1 && $orderData->ready == 1 && $orderData->picked == 1 && $orderData->on_the_way == 1 && $orderData->delivered == 0)
                                        On the way
                                    @elseif ($orderData->processing == 1 && $orderData->ready == 1 && $orderData->picked == 1 && $orderData->on_the_way == 1 && $orderData->delivered == 1)
                                        Delivered
                                    @elseif ($orderData->processing == 0 && $orderData->cancellation == 1)
                                        Cancelled
                                    @elseif ($orderData->processing == 0 && $orderData->ready == 0 && $orderData->picked == 0 && $orderData->on_the_way == 0 && $orderData->delivered == 0)
                                        Cancellation in progress
                                    @endif
                                </h4>
                            </div>
                        </div>

                        <div class="meta-item-card">
                            <div class="meta-icon tracking-icon">
                                <i class="fas fa-hashtag"></i>
                            </div>
                            <div class="meta-info">
                                <span class="meta-label">Tracking Number</span>
                                <h4 class="meta-value">{{ $orderData->tracking ?? 'No tracking updated!' }}</h4>
                            </div>
                        </div>
                    </div>

                    <!-- Section 2: Interactive Tracker Progress -->
                    <div class="tracker-wrapper my-5">
                        <div class="track-bar-container">
                            <div class="track-line-base"></div>
                            <div class="track-line-progress" style="width: {{ $progressWidth }}%"></div>
                        </div>
                        <div class="track-steps-list">
                            <div class="step-node {{ $activeCount >= 1 ? 'active' : '' }}">
                                <div class="step-icon"><i class="fas fa-check"></i></div>
                                <span class="step-text">Order Confirmed</span>
                            </div>
                            <div class="step-node {{ $activeCount >= 2 ? 'active' : '' }}">
                                <div class="step-icon"><i class="fas fa-box"></i></div>
                                <span class="step-text">Ready for Pickup</span>
                            </div>
                            <div class="step-node {{ $activeCount >= 3 ? 'active' : '' }}">
                                <div class="step-icon"><i class="fas fa-people-carry"></i></div>
                                <span class="step-text">Picked by Courier</span>
                            </div>
                            <div class="step-node {{ $activeCount >= 4 ? 'active' : '' }}">
                                <div class="step-icon"><i class="fas fa-shipping-fast"></i></div>
                                <span class="step-text">On the Way</span>
                            </div>
                            <div class="step-node {{ $activeCount >= 5 ? 'active' : '' }}">
                                <div class="step-icon"><i class="fas fa-clipboard-check"></i></div>
                                <span class="step-text">Delivered</span>
                            </div>
                        </div>
                    </div>

                    <!-- Section 3: Product Info & Details Grid -->
                    @php
                        $productData = DB::table('product')
                            ->join('product_color', 'product.id', '=', 'product_color.product_id')
                            ->select(
                                'product.id',
                                'product.product_name',
                                'product_color.color_image'
                            )
                            ->where('product.id', $orderData->product_id)
                            ->where('product_color.product_color', $orderData->color)
                            ->first();

                        $color_code = $orderData->color;
                        // Map code to color name
                        $colorMapping = [
                            '#A78B8D' => 'Marblepink', '#61A8F8' => 'Babyblue', '#C55C82' => 'Pink', '#FF0000' => 'Red',
                            '#CAD3D0' => 'Clear', '#BA9978' => 'Beige', '#88DB86' => 'Applegreen', '#DEE4EE' => 'Marblewhite',
                            '#BDB8EE' => 'Marbleviolet', '#E9CBB9' => 'Marbleorange', '#FEF250' => 'Lemonyellow',
                            '#f4c2c2' => 'Babypink', '#D2C77D' => 'Metallicgold', '#DAD9C6' => 'Buttermilk',
                            '#E9C500' => 'Yellow', '#D3CBC4' => 'Graybeige', '#0F2D8D' => 'Blue', '#005E3A' => 'Green',
                            '#D6F2E6' => 'Marblegreen', '#BF8BFF' => 'Violet', '#6B4B36' => 'Brown', '#C0C0C0' => 'Silver',
                            '#808080' => 'Grey', '#6CD2FA' => 'Skyblue', '#D09305' => 'Orange', '#13598B' => 'Metallicblue',
                            '#9582BB' => 'Metallicviolet', '#A286F4' => 'Purple', '#62ADE6' => 'Marbleblue',
                            '#80355C' => 'Marblered', '#2FCBD4' => 'Avocadogreen', '#FFA07A' => 'Lightorange',
                            '#DDD3D1' => 'Marblebeige', '#F4C430' => 'Saffron', '#000000' => 'Black', '#D4AF37' => 'Marblegold',
                            '#FFFFFF' => 'Purewhite', '#B4B4B8' => 'Metallicsilver', '#58C3C2' => 'Marblegreen',
                            '#006A4E' => 'Bottlegreen', '#6F4E37' => 'Coffee', '#FFFDD0' => 'Cream', '#A9A9A9' => 'Darkgrey',
                            '#C40233' => 'Metalicred', '#3D7764' => 'Metalicgreen', '#F8B700' => 'Metalicyellow'
                        ];
                        $colorName = $colorMapping[strtoupper($color_code)] ?? $colorMapping[$color_code] ?? 'Default Color';
                    @endphp

                    <div class="row g-4" style="display: flex; flex-wrap: wrap; margin: -12px;">
                        <!-- Product Preview Card -->
                        <div class="col-md-7" style="flex: 0 0 58.333%; max-width: 58.333%; padding: 12px; box-sizing: border-box;">
                            <h3 class="section-subtitle-title mb-3">Items in Order</h3>
                            <div class="product-info-detail-card">
                                <div class="product-detail-thumb">
                                    @if($productData && $productData->color_image)
                                        <img src="{{ asset('admin/assets/img/product/' . $productData->color_image) }}" alt="{{ $productData->product_name ?? 'Product' }}">
                                    @else
                                        <img src="https://images.macrumors.com/article-new/2019/04/guest-user-250x250.jpg" alt="Default Product">
                                    @endif
                                </div>
                                <div class="product-detail-meta">
                                    <h4 class="product-title">{{ $productData->product_name ?? 'Product Name' }}</h4>
                                    <div class="product-attributes mt-2" style="display: flex; gap: 10px; align-items: center;">
                                        <span class="attribute-tag">Qty: <strong>{{ $orderData->quantity }}</strong></span>
                                        <span class="attribute-tag" style="display: inline-flex; align-items: center; gap: 6px;">
                                            Color: <strong>{{ $colorName }}</strong>
                                            <span class="color-circle-badge" style="background-color: {{ $color_code }}; display: inline-block; width: 12px; height: 12px; border-radius: 50%; border: 1px solid rgba(0,0,0,0.1);"></span>
                                        </span>
                                    </div>
                                    <div class="shipping-address-block mt-3">
                                        <h5>Shipping Address</h5>
                                        <p>{{ $orderData->address_1 }}, {{ $orderData->address_2 }}, {{ $orderData->city }}</p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Price Receipt Card -->
                        <div class="col-md-5" style="flex: 0 0 41.666%; max-width: 41.666%; padding: 12px; box-sizing: border-box;">
                            <h3 class="section-subtitle-title mb-3">Payment Summary</h3>
                            <div class="payment-receipt-card">
                                <div class="receipt-row">
                                    <span>Subtotal</span>
                                    <span>LKR {{ number_format($subTotal, 2) }}</span>
                                </div>
                                @if($taxAmount > 0)
                                    <div class="receipt-row">
                                        <span>Tax ({{ $orderData->tax_percentage }}%)</span>
                                        <span>LKR {{ number_format($taxAmount, 2) }}</span>
                                    </div>
                                @endif
                                <div class="receipt-row">
                                    <span>Shipping Fee</span>
                                    <span>LKR {{ number_format($serviceFee, 2) }}</span>
                                </div>
                                @if($discountAmount > 0)
                                    <div class="receipt-row text-danger">
                                        <span>Discount</span>
                                        <span>- LKR {{ number_format($discountAmount, 2) }}</span>
                                    </div>
                                @endif
                                <div class="receipt-divider"></div>
                                <div class="receipt-row total-row">
                                    <span>Total Paid</span>
                                    <span class="total-price-val">LKR {{ number_format($grandTotal, 2) }}</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Actions Footer -->
                    <div class="detail-actions-footer mt-5">
                        <button type="button" class="action-btn btn-secondary" id="backToOrders">
                            <i class="fas fa-arrow-left me-2"></i> Back to Orders
                        </button>
                        
                        @if ($orderData->processing == 1 && $orderData->ready == 0 && $orderData->picked == 0 && $orderData->on_the_way == 0 && $orderData->delivered == 0)
                            <button type="button" class="action-btn btn-danger" id="cancelOrder" data-order="{{ $orderData->id }}">
                                <i class="fas fa-times-circle me-2"></i> Request Cancellation
                            </button>
                        @elseif ($orderData->processing == 0 && $orderData->cancellation == 1)
                            <button type="button" class="action-btn btn-danger" disabled style="opacity: 0.65; cursor: not-allowed;">
                                <i class="fas fa-ban me-2"></i> Order Cancelled
                            </button>
                        @elseif ($orderData->processing == 0 && $orderData->picked == 0 && $orderData->on_the_way == 0 && $orderData->delivered == 0)
                            <button type="button" class="action-btn btn-warning" disabled style="opacity: 0.65; cursor: not-allowed; background-color: #fef3c7; color: #d97706;">
                                <i class="fas fa-hourglass-half me-2"></i> Cancellation Requested
                            </button>
                        @endif
                    </div>

                </div>
            </div>
        </div>
    </section>

    <style>
        @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap');

        /* Design Aesthetics Variables */
        :root {
            --dashboard-font: 'Plus Jakarta Sans', sans-serif;
            --bg-body-color: #f8fafc;
            --card-bg-color: #ffffff;
            --primary-accent: #85c226;
            --primary-accent-dark: #6fa81d;
            --success-accent: #10b981;
            --text-heading: #0f172a;
            --text-body: #475569;
            --text-light: #94a3b8;
            --border-tint: #f1f5f9;
            --border-hard: #e2e8f0;
            --shadow-subtle: 0 4px 20px rgba(0, 0, 0, 0.03);
            --shadow-strong: 0 10px 30px rgba(0, 0, 0, 0.05);
        }

        .order-detail-section {
            font-family: var(--dashboard-font);
            background-color: var(--bg-body-color);
            background-image: radial-gradient(var(--border-hard) 1px, transparent 1px);
            background-size: 24px 24px;
            padding: 3rem 0;
            min-height: 80vh;
        }

        .order-detail-container {
            max-width: auto;
            margin: 0 auto;
            padding: 0 5.5rem;
        }

        .detail-main-card {
            background-color: var(--card-bg-color);
            border-radius: 24px;
            box-shadow: var(--shadow-subtle);
            border: 1px solid var(--border-tint);
            overflow: hidden;
        }

        .detail-card-header {
            background-color: #fafbfc;
            padding: 1.75rem 2rem;
            border-bottom: 1px solid var(--border-tint);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }

        .back-link-breadcrumb {
            font-size: 0.8rem;
            font-weight: 700;
            color: var(--text-light);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            display: block;
            margin-bottom: 4px;
        }

        .back-link-breadcrumb a {
            color: var(--text-light);
            text-decoration: none;
            transition: color 0.2s ease;
        }

        .back-link-breadcrumb a:hover {
            color: var(--primary-accent);
        }

        .header-title {
            font-size: 1.4rem;
            font-weight: 800;
            color: var(--text-heading);
            margin-bottom: 0;
            letter-spacing: -0.4px;
        }

        .order-id-label {
            font-size: 0.75rem;
            font-weight: 700;
            color: var(--text-light);
            text-transform: uppercase;
            display: block;
            text-align: right;
            margin-bottom: 2px;
        }

        .order-id-val {
            font-family: monospace;
            font-size: 1.1rem;
            font-weight: 800;
            color: var(--text-heading);
            background-color: #e2e8f0;
            padding: 4px 12px;
            border-radius: 6px;
        }

        .detail-card-body {
            padding: 2.5rem;
        }

        /* Alerts styling */
        .custom-alert-banner {
            border-radius: 12px;
            padding: 1rem 1.25rem;
            font-size: 0.9rem;
            font-weight: 600;
            border: 1px solid transparent;
            display: flex;
            align-items: center;
        }

        .custom-alert-banner.alert-danger {
            background-color: #fef2f2;
            border-color: #fca5a5;
            color: #991b1b;
        }

        .custom-alert-banner.alert-warning {
            background-color: #fffbeb;
            border-color: #fcd34d;
            color: #92400e;
        }

        /* Order Metadata Grid */
        .order-meta-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1.25rem;
        }

        .meta-item-card {
            background-color: #fafbfc;
            border: 1px solid var(--border-hard);
            border-radius: 16px;
            padding: 1.25rem 1.5rem;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .meta-icon {
            width: 42px;
            height: 42px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.15rem;
            flex-shrink: 0;
        }

        .meta-icon.date-icon {
            background-color: #eff6ff;
            color: #3b82f6;
        }

        .meta-icon.courier-icon {
            background-color: #f5f3ff;
            color: #8b5cf6;
        }

        .meta-icon.status-icon {
            background-color: #fffbeb;
            color: #f59e0b;
        }

        .meta-icon.tracking-icon {
            background-color: #f0fdf4;
            color: #10b981;
        }

        .meta-label {
            font-size: 0.75rem;
            text-transform: uppercase;
            font-weight: 700;
            color: var(--text-light);
            letter-spacing: 0.5px;
            display: block;
            margin-bottom: 2px;
        }

        .meta-value {
            font-size: 0.95rem;
            font-weight: 700;
            color: var(--text-heading);
            margin-bottom: 0;
            word-break: break-all;
        }

        .text-green-accent {
            color: var(--primary-accent) !important;
        }

        /* Interactive Tracker Progress */
        .tracker-wrapper {
            position: relative;
            padding: 10px 0;
        }

        .track-bar-container {
            position: relative;
            height: 6px;
            margin-bottom: -25px;
            top: 22px;
            width: 100%;
        }

        .track-line-base {
            position: absolute;
            width: 100%;
            height: 100%;
            background-color: var(--border-hard);
            border-radius: 3px;
        }

        .track-line-progress {
            position: absolute;
            height: 100%;
            background-color: var(--primary-accent);
            border-radius: 3px;
            transition: width 0.4s ease;
        }

        .track-steps-list {
            display: flex;
            justify-content: space-between;
            position: relative;
            z-index: 2;
        }

        .step-node {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100px;
        }

        .step-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--card-bg-color);
            border: 3px solid var(--border-hard);
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--text-light);
            font-size: 0.95rem;
            transition: all 0.3s ease;
        }

        .step-node.active .step-icon {
            background-color: var(--primary-accent);
            border-color: var(--primary-accent);
            color: #ffffff;
            box-shadow: 0 4px 10px rgba(133, 194, 38, 0.3);
        }

        .step-text {
            margin-top: 10px;
            font-size: 0.775rem;
            font-weight: 700;
            color: var(--text-body);
            text-align: center;
            transition: color 0.3s ease;
            white-space: nowrap;
        }

        .step-node.active .step-text {
            color: var(--text-heading);
        }

        /* Product Info Block */
        .section-subtitle-title {
            font-size: 1.15rem;
            font-weight: 800;
            color: var(--text-heading);
            letter-spacing: -0.2px;
        }

        .product-info-detail-card {
            background: var(--card-bg-color);
            border: 1px solid var(--border-hard);
            border-radius: 18px;
            padding: 1.5rem;
            display: flex;
            gap: 1.5rem;
        }

        .product-detail-thumb {
            width: 90px;
            height: 90px;
            border-radius: 12px;
            overflow: hidden;
            border: 1px solid var(--border-tint);
            flex-shrink: 0;
        }

        .product-detail-thumb img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .product-detail-meta {
            flex-grow: 1;
        }

        .product-title {
            font-size: 1.1rem;
            font-weight: 700;
            color: var(--text-heading);
            margin-bottom: 0.5rem;
        }

        .product-attributes {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .attribute-tag {
            font-size: 0.8rem;
            color: var(--text-body);
            background-color: var(--border-tint);
            padding: 4px 10px;
            border-radius: 6px;
            font-weight: 500;
        }

        .shipping-address-block {
            border-top: 1px dashed var(--border-hard);
            padding-top: 12px;
        }

        .shipping-address-block h5 {
            font-size: 0.8rem;
            text-transform: uppercase;
            font-weight: 700;
            color: var(--text-light);
            margin-bottom: 4px;
        }

        .shipping-address-block p {
            font-size: 0.85rem;
            color: var(--text-body);
            margin-bottom: 0;
            line-height: 1.4;
        }

        /* Payment Summary Card */
        .payment-receipt-card {
            background-color: #fafbfc;
            border: 1px solid var(--border-hard);
            border-radius: 18px;
            padding: 1.5rem;
        }

        .receipt-row {
            display: flex;
            justify-content: space-between;
            font-size: 0.9rem;
            color: var(--text-body);
            margin-bottom: 10px;
            font-weight: 500;
        }

        .receipt-divider {
            border-top: 1px solid var(--border-hard);
            margin: 12px 0;
        }

        .receipt-row.total-row {
            font-size: 1.05rem;
            font-weight: 800;
            color: var(--text-heading);
            margin-bottom: 0;
        }

        .total-price-val {
            color: var(--primary-accent);
        }

        /* Actions Footer */
        .detail-actions-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-top: 1px solid var(--border-tint);
            padding-top: 1.5rem;
        }

        .action-btn {
            display: inline-flex;
            align-items: center;
            font-size: 0.9rem;
            font-weight: 700;
            padding: 10px 20px;
            border-radius: 10px;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .action-btn.btn-secondary {
            background-color: #e2e8f0;
            color: var(--text-heading);
        }

        .action-btn.btn-secondary:hover {
            background-color: #cbd5e1;
        }

        .action-btn.btn-danger {
            background-color: #fee2e2;
            color: #ef4444;
        }

        .action-btn.btn-danger:hover {
            background-color: #fecaca;
        }

        /* Responsive styling */
        @media (max-width: 991px) {
            .order-meta-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 767px) {
            .order-meta-grid {
                grid-template-columns: 1fr;
            }
            .track-steps-list {
                flex-direction: column;
                gap: 20px;
                align-items: flex-start;
                padding-left: 20px;
            }
            .track-bar-container {
                display: none;
            }
            .step-node {
                flex-direction: row;
                gap: 15px;
                width: 100%;
                text-align: left;
                align-items: center;
            }
            .step-text {
                margin-top: 0;
            }
            .col-md-7, .col-md-5 {
                flex: 0 0 100% !important;
                max-width: 100% !important;
            }
            .product-info-detail-card {
                flex-direction: column;
            }
        }
    </style>

    <script>
        document.getElementById('backToOrders').addEventListener('click', function() {
            window.history.back();
        });
        $(document).ready(function() {
            $('#cancelOrder').click(function() {
                var orderId = $(this).data('order');
                let csrfToken = $('meta[name="csrf-token"]').attr('content');
                $.ajax({
                    url: "{{ route('american.plastic.web.cancel.order') }}",
                    type: 'POST',
                    data: {
                        order_id: orderId
                    },
                    headers: {
                        'X-CSRF-TOKEN': csrfToken
                    },
                    success: function(response) {
                        window.location.reload();
                        console.log('Order cancelled successfully:', response);
                    },
                    error: function(xhr, status, error) {
                        console.error('Error cancelling order:', error);
                    }
                });
            });
        });
    </script>
@endsection
