<?php
/** @var $cars         array */
/** @var $totalCount   int */
/** @var $statusCounts array */
/** @var $uploadUrl    string */

$this->title  = 'My Vehicles';
$baseUrl      = Yii::$app->request->baseUrl;
$defaultThumb = $baseUrl . '/uploads/cars/default.jpg';
$myCarsUrl    = \yii\helpers\Url::to(['/client/my-cars']);
$viewCarUrl   = \yii\helpers\Url::to(['/client/view-car']);
?>

<script>
window.MyCarsData = {
    cars:          <?= json_encode($cars,         JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP|JSON_UNESCAPED_UNICODE) ?>,
    totalCount:    <?= $totalCount ?>,
    statusCounts:  <?= json_encode($statusCounts, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>,
    uploadBaseUrl: '<?= $uploadUrl ?>',
    defaultThumb:  '<?= $defaultThumb ?>',
    myCarsUrl:     '<?= $myCarsUrl ?>',
    viewCarUrl:    '<?= $viewCarUrl ?>',
};
</script>

<div id="myCarsApp" class="container-fluid py-3" v-cloak>

    <!-- Stats -->
    <div class="row g-3 mb-4">
        <div class="col-6 col-md-2" v-for="stat in statusStats" :key="stat.status">
            <div class="card border-0 shadow-sm rounded-4 h-100">
                <div class="card-body py-3 text-center">
                    <div class="fw-bold fs-4">{{ stat.count }}</div>
                    <div class="small text-muted">{{ stat.label }}</div>
                    <span :class="stat.badge" class="badge rounded-pill mt-1" style="font-size:0.65rem;">
                        {{ stat.status }}
                    </span>
                </div>
            </div>
        </div>
    </div>

    <!-- Search -->
    <div class="card mb-4 border-0 shadow-sm rounded-4 overflow-hidden">
        <div class="card-body p-0 d-flex align-items-center">
            <div class="ps-4 text-muted">
                <i v-if="!searchQuery" class="bi bi-search fs-5"></i>
                <i v-else @click="searchQuery=''; fetchPage(1);"
                   class="bi bi-x-circle-fill fs-5 text-danger" style="cursor:pointer"></i>
            </div>
            <input type="text"
                   v-model="searchQuery"
                   @input="onSearchInput"
                   placeholder="Search by VIN, Lot, Container, Info, Status..."
                   class="form-control form-control-lg border-0 shadow-none py-3 ps-3">
            <div class="pe-4 text-muted small text-nowrap">
                <strong>{{ totalCount }}</strong> vehicle(s)
            </div>
        </div>
    </div>

    <!-- Table -->
    <div class="card border-0 shadow-sm rounded-4 overflow-hidden">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0" style="font-size:0.855rem;">
                <thead class="bg-light">
                    <tr class="text-nowrap small text-muted">
                        <th class="ps-4">#</th>
                        <th>PHOTO</th>
                        <th>YEAR</th>
                        <th>VIN</th>
                        <th>VEHICLE INFO</th>
                        <th>PURCHASE DATE</th>
                        <th>AUCTION</th>
                        <th>TITLE/KEY</th>
                        <th>LOT</th>
                        <th>PRICE</th>
                        <th>NOTE</th>
                        <th>CONTAINER</th>
                        <th>ETA</th>
                        <th>WAREHOUSE</th>
                        <th>STATUS</th>
                        <th>LINER</th>
                        <th class="text-end pe-4">ACTION</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-if="loading">
                        <td colspan="17" class="text-center py-5">
                            <div class="spinner-border text-primary" role="status"></div>
                        </td>
                    </tr>
                    <tr v-else-if="cars.length === 0">
                        <td colspan="17" class="text-center py-5 text-muted">
                            <i class="bi bi-inbox fs-2 d-block mb-2"></i>
                            <span v-if="searchQuery">No results for <strong>"{{ searchQuery }}"</strong></span>
                            <span v-else>No vehicles found.</span>
                        </td>
                    </tr>
                    <tr v-for="(car, idx) in cars" :key="car.id" v-else>

                        <td class="ps-4 text-muted small">
                            {{ ((currentPage - 1) * pageSize) + idx + 1 }}
                        </td>

                        <td>
                            <img :src="car.thumbnail ? uploadBaseUrl + car.thumbnail : defaultThumb"
                                 width="60" height="44"
                                 class="rounded-2 border shadow-sm"
                                 style="object-fit:cover;"
                                 @error="e => e.target.src = defaultThumb">
                        </td>

                        <td class="fw-bold">{{ car.year || '—' }}</td>

                        <td class="fw-semibold text-nowrap">{{ car.vin || '—' }}</td>

                        <td style="max-width:160px;">
                            <div class="text-truncate" :title="car.info">{{ car.info || '—' }}</div>
                        </td>

                        <td class="text-nowrap">{{ formatDate(car.purchase_date) }}</td>

                        <td class="fw-semibold text-nowrap">{{ car.auction_name || '—' }}</td>

                        <td>
                            <span class="badge bg-light text-dark border rounded-pill">
                                {{ car.title || 'No Title' }}
                            </span>
                        </td>

                        <td class="fw-semibold">{{ car.lot }}</td>

                        <td class="fw-bold text-nowrap">${{ formatNumber(car.price) }}</td>

                        <td style="max-width:130px;">
                            <div class="text-danger small fst-italic text-truncate" :title="car.note">
                                {{ car.note || '' }}
                            </div>
                        </td>

                        <td class="fw-semibold text-nowrap">{{ car.container || '—' }}</td>

                        <td class="text-nowrap">{{ formatDate(car.eta_date) }}</td>

                        <td class="text-nowrap">{{ car.warehouse_name || '—' }}</td>

                        <td>
                            <span :class="getStatusBadge(car.status)"
                                  class="badge rounded-pill px-3 py-2">
                                {{ formatStatus(car.status) }}
                            </span>
                        </td>

                        <td class="text-nowrap">
                            <div class="fw-semibold small">{{ car.liner || '—' }}</div>
                            <a v-if="car.shipping_line"
                               :href="car.shipping_line" target="_blank"
                               class="small text-primary text-decoration-none">
                                <i class="bi bi-box-arrow-up-right me-1"></i>Track
                            </a>
                        </td>

                        <td class="text-end pe-4">
                            <a :href="viewCarUrl + '&id=' + car.id"
                               class="btn btn-sm btn-outline-primary border-0 rounded-pill">
                                <i class="bi bi-eye me-1"></i>View
                            </a>
                        </td>

                    </tr>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <div class="card-footer bg-white border-top py-3
                    d-flex justify-content-between align-items-center flex-wrap gap-2"
             v-if="totalCount > 0">
            <div class="d-flex align-items-center gap-3 ps-2">
                <div class="small text-muted">
                    Showing <strong>{{ startIndex }}</strong>–<strong>{{ endIndex }}</strong>
                    of <strong>{{ totalCount }}</strong>
                </div>
                <div class="d-flex align-items-center gap-2">
                    <label class="small text-muted mb-0">Show:</label>
                    <select v-model.number="pageSize"
                            class="form-select form-select-sm w-auto border-0 shadow-sm rounded-pill"
                            style="min-width:70px;">
                        <option :value="10">10</option>
                        <option :value="15">15</option>
                        <option :value="25">25</option>
                        <option :value="50">50</option>
                    </select>
                </div>
            </div>
            <nav v-if="totalPages > 1">
                <ul class="pagination pagination-sm mb-0 gap-1">
                    <li class="page-item" :class="{disabled: currentPage===1}">
                        <button class="page-link rounded-pill border-0 px-3"
                                @click="goToPage(currentPage - 1)">
                            <i class="bi bi-chevron-left"></i>
                        </button>
                    </li>
                    <template v-for="page in visiblePages" :key="page">
                        <li v-if="page !== '...'"
                            class="page-item" :class="{active: currentPage === page}">
                            <button class="page-link rounded-pill border-0 px-3"
                                    @click="goToPage(page)">{{ page }}</button>
                        </li>
                        <li v-else class="page-item disabled">
                            <span class="page-link border-0 bg-transparent">…</span>
                        </li>
                    </template>
                    <li class="page-item" :class="{disabled: currentPage === totalPages}">
                        <button class="page-link rounded-pill border-0 px-3"
                                @click="goToPage(currentPage + 1)">
                            <i class="bi bi-chevron-right"></i>
                        </button>
                    </li>
                </ul>
            </nav>
        </div>
    </div>

</div>

<style>
[v-cloak] { display: none !important; }
.rounded-4 { border-radius: 1rem !important; }
.table th {
    font-size: 0.75rem; font-weight: 600;
    text-transform: uppercase; letter-spacing: 0.5px;
    padding-top: 1rem; padding-bottom: 1rem;
}
.table-hover tbody tr:hover { background-color: #f8f9fa !important; }
.page-item.active .page-link { background-color: #0d6efd !important; color: #fff !important; font-weight: 600; }
.page-link { color: #555; transition: all .2s; }
.page-link:hover { background-color: #e9ecef; color: #0d6efd; }
</style>

<?php $this->registerJs(<<<'JS'
(function () {
    var _d = window.MyCarsData;

    Vue.createApp({
        data() {
            return {
                cars:          _d.cars          || [],
                totalCount:    _d.totalCount    || 0,
                statusCounts:  _d.statusCounts  || {},
                uploadBaseUrl: _d.uploadBaseUrl || '',
                defaultThumb:  _d.defaultThumb  || '',
                myCarsUrl:     _d.myCarsUrl     || '',
                viewCarUrl:    _d.viewCarUrl    || '',
                searchQuery:   '',
                currentPage:   1,
                pageSize:      15,
                loading:       false,
                searchTimer:   null,
            };
        },

        computed: {
            totalPages() { return Math.ceil(this.totalCount / this.pageSize) || 1; },
            startIndex() { return this.totalCount === 0 ? 0 : (this.currentPage - 1) * this.pageSize + 1; },
            endIndex()   { return Math.min(this.currentPage * this.pageSize, this.totalCount); },

            statusStats() {
                var s = this;
                return [
                    { status: 'at_auction', label: 'At Auction', badge: 'bg-warning-subtle text-warning'  },
                    { status: 'at_yard',    label: 'At Yard',    badge: 'bg-info-subtle text-info'        },
                    { status: 'arrived',    label: 'Arrived',    badge: 'bg-success-subtle text-success'  },
                    { status: 'paid',       label: 'Paid',       badge: 'bg-primary-subtle text-primary'  },
                    { status: 'unpaid',     label: 'Unpaid',     badge: 'bg-danger-subtle text-danger'    },
                ].map(x => Object.assign({}, x, { count: s.statusCounts[x.status] || 0 }));
            },

            visiblePages() {
                var t = this.totalPages, c = this.currentPage, p = [];
                if (t <= 7) { for (var i = 1; i <= t; i++) p.push(i); return p; }
                p.push(1);
                if (c > 4) p.push('...');
                for (var j = Math.max(2, c - 2); j <= Math.min(t - 1, c + 2); j++) p.push(j);
                if (c < t - 3) p.push('...');
                p.push(t);
                return p;
            },
        },

        watch: {
            pageSize() { this.currentPage = 1; this.fetchPage(1); },
        },

        methods: {
            onSearchInput() {
                var s = this;
                s.currentPage = 1;
                clearTimeout(s.searchTimer);
                s.searchTimer = setTimeout(() => s.fetchPage(1), 400);
            },

            fetchPage(page) {
                var s = this;
                s.loading = true;
                var url = s.myCarsUrl + '&ajax=1&page=' + page + '&pageSize=' + s.pageSize
                    + (s.searchQuery ? '&search=' + encodeURIComponent(s.searchQuery) : '');

                fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                    .then(r => r.json())
                    .then(d => {
                        if (d.success) {
                            s.cars       = d.cars;
                            s.totalCount = d.total;
                            s.currentPage = page;
                        }
                    })
                    .catch(e => console.error('[MyCars] fetchPage error:', e))
                    .finally(() => s.loading = false);
            },

            goToPage(page) {
                if (page < 1 || page > this.totalPages || page === '...') return;
                this.fetchPage(page);
            },

            formatDate(d) {
                if (!d) return '—';
                var dt = new Date(d + 'T00:00:00');
                return isNaN(dt) ? d : dt.toLocaleDateString('en-GB');
            },

            formatNumber(v) {
                return parseFloat(v || 0).toLocaleString('en-US', {
                    minimumFractionDigits: 2, maximumFractionDigits: 2,
                });
            },

            formatStatus(s) {
                return { at_auction: 'At Auction', at_yard: 'At Yard', arrived: 'Arrived',
                         paid: 'Paid', unpaid: 'Unpaid' }[s] || s;
            },

            getStatusBadge(s) {
                return {
                    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',
                }[s] || 'bg-secondary-subtle text-secondary';
            },
        },
    }).mount('#myCarsApp');
})();
JS, \yii\web\View::POS_END); ?>
