<?php
/* views/car/view.php */
use yii\helpers\Url;
use yii\helpers\Html;

/** @var app\models\Car $car */

$this->title = $car->year . ' ' . $car->info;
$baseUrl     = Yii::$app->request->baseUrl;
$uploadUrl   = $baseUrl . '/uploads/cars/';
$defaultImg  = $baseUrl . '/uploads/cars/default.jpg';

// Group images by type
$auctionImages   = [];
$warehouseImages = [];
$loadingImages   = [];

foreach ($car->images as $img) {
    if ($img->type === 'auction')        $auctionImages[]   = $img;
    elseif ($img->type === 'warehouse')  $warehouseImages[] = $img;
    elseif ($img->type === 'loading')    $loadingImages[]   = $img;
}

// All images flat array for lightbox
$allImages = array_merge($auctionImages, $warehouseImages, $loadingImages);
?>

<div class="container-fluid pt-4 pb-5">

    <!-- Back Button & Title -->
    <div class="d-flex align-items-center mb-4 gap-3">
        <a href="<?= Url::to(['car/index']) ?>"
           class="btn btn-outline-secondary rounded-pill px-3 border-0 shadow-sm">
            <i class="bi bi-arrow-left me-1"></i> Back
        </a>
        <div>
            <h4 class="fw-bold mb-0 text-dark">
                <i class="bi bi-car-front-fill text-primary me-2"></i>
                <?= Html::encode($car->year . ' ' . $car->info) ?>
            </h4>
            <p class="text-muted small mb-0 mt-1">
                VIN: <strong><?= Html::encode($car->vin ?: '—') ?></strong>
                &nbsp;|&nbsp; LOT: <strong><?= Html::encode($car->lot ?: '—') ?></strong>
            </p>
        </div>

        <!-- Status Badge -->
        <span class="ms-auto badge rounded-pill px-3 py-2 fs-6
            <?php
            $badgeMap = [
                'at_auction' => 'bg-warning-subtle text-warning border border-warning-subtle',
                'at_yard'    => 'bg-info-subtle text-info border border-info-subtle',
                'arrived'    => 'bg-success-subtle text-success border border-success-subtle',
                'paid'       => 'bg-primary-subtle text-primary border border-primary-subtle',
                'unpaid'     => 'bg-danger-subtle text-danger border border-danger-subtle',
            ];
            echo $badgeMap[$car->status] ?? 'bg-secondary-subtle text-secondary';
            ?>">
            <?php
            $statusLabels = [
                'at_auction' => 'At Auction',
                'at_yard'    => 'At Yard',
                'arrived'    => 'Arrived',
                'paid'       => 'Paid',
                'unpaid'     => 'Unpaid',
            ];
            echo $statusLabels[$car->status] ?? $car->status;
            ?>
        </span>
    </div>

    <div class="row g-4">

        <!-- LEFT: Car Details Card -->
        <div class="col-lg-4">
            <div class="card border-0 shadow-sm rounded-4 overflow-hidden h-100">
                <!-- Thumbnail Hero -->
                <div class="bg-light text-center p-3" style="min-height:200px;">
                    <?php
                    // ✅ Use getThumbnail() method — not a DB column property
                    $thumbSrc = $defaultImg;
                    $thumb    = $car->getThumbnail();
                    if ($thumb) {
                        $thumbSrc = $uploadUrl . $thumb;
                    }
                    ?>
                    <img src="<?= Html::encode($thumbSrc) ?>"
                        class="img-fluid rounded-3 shadow"
                        style="max-height:200px; object-fit:cover; width:100%;"
                        alt="Thumbnail"
                        onerror="this.src='<?= Html::encode($defaultImg) ?>'">
                </div>
                <div class="card-body p-4">
                    <h6 class="fw-bold text-primary mb-3">
                        <i class="bi bi-info-circle me-2"></i>Vehicle Details
                    </h6>

                    <table class="table table-sm table-borderless mb-0"
                           style="font-size:0.88rem;">
                        <tbody>
                        <?php
                        $client      = $car->client;
                        $auction     = $car->auction;
                        $warehouse   = $car->warehouse;
                        $destination = $car->destination;

                        $rows = [
                            ['Year',          $car->year],
                            ['Make/Model',    $car->info],
                            ['VIN',           $car->vin],
                            ['LOT #',         $car->lot],
                            ['Title',         $car->title],
                            ['Price',         '$' . number_format((float)$car->price, 2)],
                            ['Auction',       $auction ? $auction->name : '—'],
                            ['Client',        $client  ? ('[' . $client->no . '] ' . $client->name) : '—'],
                            ['Warehouse',     $warehouse   ? $warehouse->name   : '—'],
                            ['Destination',   $destination ? $destination->name : '—'],
                            ['Container',     $car->container],
                            ['Liner',         $car->liner],
                            ['Purchase Date', $car->purchase_date
                                                ? date('d-m-Y', strtotime($car->purchase_date))
                                                : '—'],
                            ['Received Date', $car->received_date
                                                ? date('d-m-Y', strtotime($car->received_date))
                                                : '—'],
                            ['ETA Date',      $car->eta_date
                                                ? date('d-m-Y', strtotime($car->eta_date))
                                                : '—'],
                        ];
                        ?>
                        <?php foreach ($rows as [$label, $value]): ?>
                        <tr>
                            <td class="text-muted fw-semibold" style="width:42%;">
                                <?= Html::encode($label) ?>
                            </td>
                            <td class="fw-semibold text-dark">
                                <?= Html::encode($value ?: '—') ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>

                        <?php if ($car->shipping_line): ?>
                        <tr>
                            <td class="text-muted fw-semibold">Tracking</td>
                            <td>
                                <a href="<?= Html::encode($car->shipping_line) ?>"
                                   target="_blank"
                                   class="btn btn-sm btn-outline-primary rounded-pill px-3">
                                    <i class="bi bi-box-arrow-up-right me-1"></i>Track Shipment
                                </a>
                            </td>
                        </tr>
                        <?php endif; ?>

                        <?php if ($car->note): ?>
                        <tr>
                            <td class="text-muted fw-semibold">Note</td>
                            <td class="text-danger fst-italic">
                                <?= Html::encode($car->note) ?>
                            </td>
                        </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- RIGHT: Photos -->
        <div class="col-lg-8">

            <?php
            $photoGroups = [
                ['label' => 'Auction Photos',   'icon' => 'bi-hammer',  'images' => $auctionImages],
                ['label' => 'Warehouse Photos', 'icon' => 'bi-house',   'images' => $warehouseImages],
                ['label' => 'Loading Photos',   'icon' => 'bi-truck',   'images' => $loadingImages],
            ];

            // Build flat lightbox array with global index
            $lightboxImages = [];
            foreach ($allImages as $img) {
                $lightboxImages[] = $uploadUrl . $img->image_path;
            }
            $lightboxJson = json_encode($lightboxImages, JSON_HEX_TAG | JSON_HEX_QUOT);
            ?>

            <!-- Photo Tabs -->
            <div class="card border-0 shadow-sm rounded-4 overflow-hidden">
                <div class="card-header bg-white border-bottom px-4 pt-3 pb-0">
                    <ul class="nav nav-tabs border-0 gap-2" id="photoTabs" role="tablist">
                        <?php foreach ($photoGroups as $gi => $group): ?>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link rounded-pill px-4 border-0
                                           <?= $gi === 0 ? 'active' : '' ?>"
                                    id="tab-<?= $gi ?>-btn"
                                    data-bs-toggle="tab"
                                    data-bs-target="#tab-<?= $gi ?>"
                                    type="button" role="tab">
                                <i class="bi <?= $group['icon'] ?> me-2"></i>
                                <?= $group['label'] ?>
                                <span class="badge bg-primary-subtle text-primary
                                             rounded-pill ms-1">
                                    <?= count($group['images']) ?>
                                </span>
                            </button>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </div>

                <div class="card-body p-4">
                    <div class="tab-content" id="photoTabContent">

                        <?php
                        $globalIdx = 0; // tracks position across all groups
                        foreach ($photoGroups as $gi => $group):
                        ?>
                        <div class="tab-pane fade <?= $gi === 0 ? 'show active' : '' ?>"
                             id="tab-<?= $gi ?>" role="tabpanel">

                            <?php if (empty($group['images'])): ?>
                            <div class="text-center text-muted py-5">
                                <i class="bi bi-image fs-1 d-block mb-2 opacity-25"></i>
                                No <?= strtolower($group['label']) ?> uploaded.
                            </div>
                            <?php else: ?>

                            <div class="row g-3">
                                <?php foreach ($group['images'] as $img): ?>
                                <div class="col-6 col-md-4 col-xl-3">
                                    <!-- ✅ Lightbox trigger -->
                                    <div class="ratio ratio-4x3 rounded-3 overflow-hidden
                                                shadow-sm border lightbox-thumb"
                                         style="cursor:pointer;"
                                         data-index="<?= $globalIdx ?>"
                                         onclick="openLightbox(<?= $globalIdx ?>)">
                                        <img src="<?= Html::encode($uploadUrl . $img->image_path) ?>"
                                             class="w-100 h-100"
                                             style="object-fit:cover;"
                                             alt="Photo"
                                             onerror="this.src='<?= $defaultImg ?>'">
                                        <!-- Hover overlay -->
                                        <div class="lightbox-overlay d-flex align-items-center
                                                    justify-content-center
                                                    position-absolute top-0 start-0
                                                    w-100 h-100"
                                             style="background:rgba(0,0,0,0.35);
                                                    opacity:0;transition:opacity 0.2s;">
                                            <i class="bi bi-zoom-in text-white fs-3"></i>
                                        </div>
                                    </div>
                                </div>
                                <?php $globalIdx++; ?>
                                <?php endforeach; ?>
                            </div>

                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>

                    </div><!-- end tab-content -->
                </div>
            </div><!-- end card -->

        </div><!-- end col -->
    </div><!-- end row -->
</div>

<!-- ============================================================
     LIGHTBOX OVERLAY
     ============================================================ -->
<div id="lightboxOverlay"
     style="display:none; position:fixed; top:0; left:0;
            width:100%; height:100%; z-index:10000;
            background:rgba(0,0,0,0.93);
            align-items:center; justify-content:center;
            flex-direction:column;">

    <!-- Close Button -->
    <button onclick="closeLightbox()"
            style="position:absolute; top:16px; right:20px;
                   background:none; border:none; color:#fff;
                   font-size:2rem; cursor:pointer; z-index:10001;"
            title="Close">
        <i class="bi bi-x-lg"></i>
    </button>

    <!-- Counter -->
    <div id="lightboxCounter"
         style="position:absolute; top:18px; left:50%;
                transform:translateX(-50%); color:#ccc;
                font-size:0.9rem; letter-spacing:1px;">
    </div>

    <!-- Image -->
    <div style="position:relative; display:flex;
                align-items:center; justify-content:center;
                width:100%; height:100%; padding:60px 80px;">

        <!-- Prev Button -->
        <button onclick="lightboxNav(-1)"
                id="btnPrev"
                style="position:absolute; left:16px; top:50%;
                       transform:translateY(-50%);
                       background:rgba(255,255,255,0.12);
                       border:none; border-radius:50%;
                       width:52px; height:52px;
                       color:#fff; font-size:1.4rem;
                       cursor:pointer; transition:background 0.2s;
                       display:flex; align-items:center; justify-content:center;"
                onmouseover="this.style.background='rgba(255,255,255,0.25)'"
                onmouseout="this.style.background='rgba(255,255,255,0.12)'">
            <i class="bi bi-chevron-left"></i>
        </button>

        <!-- Main Image -->
        <img id="lightboxImg"
             src=""
             alt=""
             style="max-width:100%; max-height:100%;
                    object-fit:contain; border-radius:8px;
                    box-shadow:0 8px 40px rgba(0,0,0,0.6);
                    transition:opacity 0.2s ease;"
             onerror="this.src='<?= $defaultImg ?>'">

        <!-- Next Button -->
        <button onclick="lightboxNav(1)"
                id="btnNext"
                style="position:absolute; right:16px; top:50%;
                       transform:translateY(-50%);
                       background:rgba(255,255,255,0.12);
                       border:none; border-radius:50%;
                       width:52px; height:52px;
                       color:#fff; font-size:1.4rem;
                       cursor:pointer; transition:background 0.2s;
                       display:flex; align-items:center; justify-content:center;"
                onmouseover="this.style.background='rgba(255,255,255,0.25)'"
                onmouseout="this.style.background='rgba(255,255,255,0.12)'">
            <i class="bi bi-chevron-right"></i>
        </button>
    </div>

    <!-- Thumbnail Strip -->
    <div id="lightboxThumbs"
         style="position:absolute; bottom:0; left:0; right:0;
                display:flex; gap:6px; padding:10px 16px;
                overflow-x:auto; background:rgba(0,0,0,0.6);
                justify-content:center;">
    </div>
</div>

<style>
/* Tab active style */
.nav-tabs .nav-link.active {
    background: #0d6efd !important;
    color: #fff !important;
    font-weight: 600;
}
.nav-tabs .nav-link {
    color: #555;
    font-size: 0.875rem;
}

/* Hover effect on thumbnails */
.lightbox-thumb:hover .lightbox-overlay {
    opacity: 1 !important;
}

/* Scrollbar for thumb strip */
#lightboxThumbs::-webkit-scrollbar { height: 4px; }
#lightboxThumbs::-webkit-scrollbar-thumb {
    background: rgba(255,255,255,0.3);
    border-radius: 4px;
}

/* Active thumb in strip */
.lb-strip-thumb.active {
    outline: 3px solid #0d6efd !important;
    opacity: 1 !important;
}
</style>

<script>
// ============================================================
// LIGHTBOX JAVASCRIPT
// ============================================================
const _lbImages  = <?= $lightboxJson ?>;
let   _lbCurrent = 0;

function openLightbox(index) {
    _lbCurrent = index;
    const overlay = document.getElementById('lightboxOverlay');
    overlay.style.display = 'flex';
    document.body.style.overflow = 'hidden';
    renderLightbox();
    buildThumbStrip();
}

function closeLightbox() {
    document.getElementById('lightboxOverlay').style.display = 'none';
    document.body.style.overflow = '';
}

function lightboxNav(dir) {
    _lbCurrent = (_lbCurrent + dir + _lbImages.length) % _lbImages.length;
    renderLightbox();
    syncThumbStrip();
}

function renderLightbox() {
    const img     = document.getElementById('lightboxImg');
    const counter = document.getElementById('lightboxCounter');
    const btnPrev = document.getElementById('btnPrev');
    const btnNext = document.getElementById('btnNext');

    // Fade transition
    img.style.opacity = '0';
    setTimeout(function() {
        img.src           = _lbImages[_lbCurrent];
        img.style.opacity = '1';
    }, 150);

    counter.textContent = (_lbCurrent + 1) + ' / ' + _lbImages.length;

    // Hide nav arrows if only 1 image
    btnPrev.style.display = _lbImages.length <= 1 ? 'none' : 'flex';
    btnNext.style.display = _lbImages.length <= 1 ? 'none' : 'flex';
}

function buildThumbStrip() {
    const strip = document.getElementById('lightboxThumbs');
    strip.innerHTML = '';

    if (_lbImages.length <= 1) {
        strip.style.display = 'none';
        return;
    }

    strip.style.display = 'flex';

    _lbImages.forEach(function(src, i) {
        const thumb = document.createElement('img');
        thumb.src    = src;
        thumb.className = 'lb-strip-thumb rounded-2';
        thumb.style.cssText =
            'width:60px; height:45px; object-fit:cover;' +
            'cursor:pointer; border-radius:6px;' +
            'opacity:0.55; transition:opacity 0.2s, outline 0.2s;' +
            'flex-shrink:0;';

        if (i === _lbCurrent) {
            thumb.classList.add('active');
            thumb.style.opacity = '1';
        }

        thumb.addEventListener('click', function() {
            _lbCurrent = i;
            renderLightbox();
            syncThumbStrip();
        });

        strip.appendChild(thumb);
    });
}

function syncThumbStrip() {
    const thumbs = document.querySelectorAll('.lb-strip-thumb');
    thumbs.forEach(function(t, i) {
        t.style.opacity = i === _lbCurrent ? '1' : '0.55';
        t.classList.toggle('active', i === _lbCurrent);
    });

    // Scroll active thumb into view
    if (thumbs[_lbCurrent]) {
        thumbs[_lbCurrent].scrollIntoView({
            behavior: 'smooth', inline: 'center', block: 'nearest'
        });
    }
}

// Keyboard navigation
document.addEventListener('keydown', function(e) {
    const overlay = document.getElementById('lightboxOverlay');
    if (overlay.style.display === 'none') return;

    if (e.key === 'ArrowRight') lightboxNav(1);
    if (e.key === 'ArrowLeft')  lightboxNav(-1);
    if (e.key === 'Escape')     closeLightbox();
});

// Click background to close
document.getElementById('lightboxOverlay').addEventListener('click', function(e) {
    if (e.target === this) closeLightbox();
});
</script>
