<?php
use yii\helpers\Url;

/** @var $this yii\web\View */
/** @var $cars array */
/** @var $clients array */
/** @var $auctions array */
/** @var $warehouses array */

$this->title = 'Car Administration';

// Safely encode data for Vue
$jsonCars = json_encode($cars, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
$jsonClients = json_encode($clients);
$jsonAuctions = json_encode($auctions);
$jsonWarehouses = json_encode($warehouses);

$saveUrl = Url::to(['car/save-ajax']);
$deleteUrl = Url::to(['car/delete']);
?>

<div id="carApp" class="container-fluid pt-4" v-cloak>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="fw-bold mb-0 text-dark">
            Vehicle Inventory
            <span class="badge bg-primary-subtle text-primary rounded-pill ms-2" style="font-size: 0.8rem;">
                {{ filteredCars.length }} Units
            </span>
        </h4>
        <button @click="openModal()" class="btn btn-primary rounded-pill px-4 shadow-sm fw-bold border-0">
            <i class="bi bi-plus-circle-fill me-1"></i> Add New Car
        </button>
    </div>

    <div class="card mb-4 border-0 shadow-sm rounded-4 overflow-hidden">
        <div class="card-body p-0 d-flex align-items-center bg-white">
            <div class="ps-4 text-muted">
                <i v-if="!searchQuery" class="bi bi-search fs-5"></i>
                <i v-else @click="searchQuery = ''" class="bi bi-x-circle-fill fs-5 text-danger" style="cursor:pointer"></i>
            </div>
            <input type="text" v-model="searchQuery" @input="currentPage = 1" 
                   placeholder="Search by VIN, Lot, Container, Client, or Info..." 
                   class="form-control form-control-lg border-0 shadow-none py-4">
        </div>
    </div>

    <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.875rem;">
                <thead class="bg-light">
                    <tr class="text-nowrap small fw-bold text-muted">
                        <th class="ps-4">NO.</th>
                        <th>PHOTO</th>
                        <th>YEAR</th>
                        <th>VIN</th>
                        <th>VEHICLE INFO</th>
                        <th>PURCHASE DATE</th>
                        <th>AUCTION / TYPE</th>
                        <th>TITLE/KEY</th>
                        <th>LOT</th>
                        <th>PRICE</th>
                        <th>CLIENT</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">ACTIONS</th>
                    </tr>
                </thead>
                <tbody class="bg-white">
                    <tr v-for="(car, index) in paginatedCars" :key="car.id">
                        <td class="ps-4 text-muted small">{{ ((currentPage - 1) * pageSize) + index + 1 }}</td>
                        <td>
                            <img :src="'<?= Yii::$app->request->baseUrl ?>/images/cars/' + (car.img_auc || 'default.jpg')" 
                                 width="55" height="40" class="rounded-2 border object-fit-cover shadow-sm">
                        </td>
                        <td class="fw-bold">{{ car.year }}</td>
                        <td>
                            <div class="dropdown">
                                <button class="btn btn-sm btn-light border dropdown-toggle fw-bold" type="button" data-bs-toggle="dropdown">
                                    {{ car.vin }}
                                </button>
                                <ul class="dropdown-menu shadow-sm">
                                    <li><a class="dropdown-item" :href="'<?= Url::to(['car/view']) ?>?id=' + car.id"><i class="bi bi-eye me-2"></i> View</a></li>
                                    <li><button class="dropdown-item" @click="openModal(car)"><i class="bi bi-pencil me-2"></i> Edit</button></li>
                                    <li><hr class="dropdown-divider"></li>
                                    <li><button class="dropdown-item text-danger" @click="deleteCar(car.id)"><i class="bi bi-trash me-2"></i> Delete</button></li>
                                </ul>
                            </div>
                        </td>
                        <td class="text-nowrap">{{ car.info }}</td>
                        <td class="text-nowrap">{{ formatDate(car.purchase_date) }}</td>
                        <td>
                            <div class="fw-bold">{{ getAuctionName(car.auction_id) }}</div>
                            <div class="small text-muted">{{ car.auction_type || 'N/A' }}</div>
                        </td>
                        <td><span class="badge bg-light text-dark border">{{ car.title || 'No Title' }}</span></td>
                        <td>{{ car.lot }}</td>
                        <td class="fw-bold text-dark">${{ formatNumber(car.price) }}</td>
                        <td class="text-nowrap">
                            <span class="badge bg-secondary-subtle text-dark me-1">{{ getClientNo(car.client_id) }}</span>
                            {{ getClientName(car.client_id) }}
                        </td>
                        <td>
                            <div class="text-danger small fst-italic" style="max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" :title="car.note">
                                {{ car.note }}
                            </div>
                        </td>
                        <td class="fw-bold">{{ car.container || '---' }}</td>
                        <td class="text-nowrap">{{ formatDate(car.eta_date) }}</td>
                        <td class="text-nowrap">{{ getWarehouseName(car.warehouse_id) }}</td>
                        <td>
                            <span :class="getStatusBadge(car.status)">{{ car.status }}</span>
                        </td>
                        <td>
                            <div>{{ car.liner }}</div>
                            <a v-if="car.shipping_line" :href="car.shipping_line" target="_blank" class="small">Click Here</a>
                        </td>
                        <td class="text-end pe-4">
                            <div class="d-flex justify-content-end">
                                <a :href="'<?= Url::to(['car/view']) ?>?id=' + car.id" class="btn btn-sm btn-outline-info border-0 rounded-pill" title="View">
                                    <i class="bi bi-eye"></i>
                                </a>
                                <button @click="openModal(car)" class="btn btn-sm btn-outline-primary border-0 rounded-pill" title="Edit">
                                    <i class="bi bi-pencil-square"></i>
                                </button>
                                <button @click="deleteCar(car.id)" class="btn btn-sm btn-outline-danger border-0 rounded-pill" title="Delete">
                                    <i class="bi bi-trash3"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <tr v-if="filteredCars.length === 0">
                        <td colspan="18" class="text-center py-5 text-muted">
                            No vehicles found matching "<strong>{{ searchQuery }}</strong>"
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="card-footer bg-white border-top-0 py-3 d-flex justify-content-between align-items-center" v-if="filteredCars.length > pageSize">
            <div class="small text-muted ps-2">
                Showing <strong>{{ startIndex }}</strong> to <strong>{{ endIndex }}</strong> of <strong>{{ filteredCars.length }}</strong>
            </div>
            <nav>
                <ul class="pagination pagination-sm mb-0">
                    <li class="page-item" :class="{ disabled: currentPage === 1 }">
                        <button class="page-link border-0" @click="currentPage--">
                            <i class="bi bi-chevron-left"></i>
                        </button>
                    </li>
                    <li v-for="page in totalPages" :key="page" class="page-item" :class="{ active: currentPage === page }">
                        <button v-if="shouldShowPage(page)" class="page-link rounded-circle mx-1 border-0" @click="currentPage = page">
                            {{ page }}
                        </button>
                    </li>
                    <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                        <button class="page-link border-0" @click="currentPage++">
                            <i class="bi bi-chevron-right"></i>
                        </button>
                    </li>
                </ul>
            </nav>
        </div>
    </div>

    <?= $this->render('_modal', [
        'clients' => $clients,
        'auctions' => $auctions,
        'warehouses' => $warehouses
    ]) ?>
</div>

<style>
    [v-cloak] { display: none; }
    .rounded-4 { border-radius: 1rem; }
    .object-fit-cover { object-fit: cover; }
    .table th { font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
    
    /* Pagination Style Override */
    .page-item.active .page-link { 
        background-color: #0d6efd !important; 
        color: white !important; 
        border-radius: 50% !important; 
    }
    .pagination .page-link { 
        color: #666; 
        padding: 0.5rem 0.75rem; 
        background: transparent;
    }
    .pagination .page-link:hover {
        background-color: #f8f9fa;
        border-radius: 50%;
    }
    .table-hover tbody tr:hover { background-color: #f8f9fa; }
</style>

<?php
$js = <<<JS
const { createApp } = Vue;

createApp({
    data() {
        return {
            cars: $jsonCars,
            clients: $jsonClients,
            auctions: $jsonAuctions,
            warehouses: $jsonWarehouses,
            searchQuery: '',
            currentPage: 1,
            pageSize: 15,
            formData: {},
            isEditing: false,
            loading: false, // For save button spinner
            modalInstance: null,
            
            // New Image System State
            newFiles: { auction: [], warehouse: [], loading: [] },
            newPreviews: { auction: [], warehouse: [], loading: [] },
            existingImages: [], // Images already in DB for the selected car
            deletedImageIds: [] // Track IDs to delete from DB on save
        }
    },
    computed: {
        filteredCars() {
            if (!this.searchQuery) return this.cars;
            const q = this.searchQuery.toLowerCase();
            return this.cars.filter(c => 
                (c.vin || '').toLowerCase().includes(q) || 
                (c.lot || '').toLowerCase().includes(q) ||
                (c.container || '').toLowerCase().includes(q) ||
                (c.info || '').toLowerCase().includes(q) ||
                (this.getClientName(c.client_id).toLowerCase()).includes(q)
            );
        },
        paginatedCars() {
            const start = (this.currentPage - 1) * this.pageSize;
            return this.filteredCars.slice(start, start + this.pageSize);
        },
        totalPages() { return Math.ceil(this.filteredCars.length / this.pageSize) || 1; },
        startIndex() { return this.filteredCars.length === 0 ? 0 : (this.currentPage - 1) * this.pageSize + 1; },
        endIndex() { return Math.min(this.currentPage * this.pageSize, this.filteredCars.length); }
    },
    mounted() {
        this.modalInstance = new bootstrap.Modal(document.getElementById('carModal'));
    },
    methods: {
        // --- Image Handling Methods ---
        handleFileSelect(event, type) {
            const files = Array.from(event.target.files);
            this.processFiles(files, type);
        },
        handleDrop(event, type) {
            const files = Array.from(event.dataTransfer.files);
            this.processFiles(files, type);
        },
        processFiles(files, type) {
            files.forEach(file => {
                this.newFiles[type].push(file);
                const reader = new FileReader();
                reader.onload = (e) => this.newPreviews[type].push(e.target.result);
                reader.readAsDataURL(file);
            });
        },
        removeNewImage(type, index) {
            this.newFiles[type].splice(index, 1);
            this.newPreviews[type].splice(index, 1);
        },
        deleteExistingImage(imgId) {
            if(confirm("Mark this image for deletion?")) {
                this.deletedImageIds.push(imgId);
                this.existingImages = this.existingImages.filter(i => i.id !== imgId);
            }
        },

        // --- Standard Methods ---
        formatDate(dateStr) {
            if (!dateStr) return '';
            const d = new Date(dateStr);
            return d.toLocaleDateString('en-GB');
        },
        formatNumber(val) {
            return parseFloat(val || 0).toLocaleString(undefined, {minimumFractionDigits: 2});
        },
        getStatusBadge(status) {
            const s = (status || '').toLowerCase();
            const map = {
                'paid': 'badge bg-success-subtle text-success border border-success-subtle',
                'unpaid': 'badge bg-danger-subtle text-danger border border-danger-subtle',
                'at_auction': 'badge bg-warning-subtle text-dark border border-warning-subtle'
            };
            return (map[s] || 'badge bg-light text-dark border') + ' rounded-pill px-2';
        },
        getClientName(id) { const c = this.clients.find(x => x.id == id); return c ? c.name : '---'; },
        getClientNo(id) { const c = this.clients.find(x => x.id == id); return c ? c.no : 'N/A'; },
        getAuctionName(id) { const a = this.auctions.find(x => x.id == id); return a ? a.name : '---'; },
        getWarehouseName(id) { const w = this.warehouses.find(x => x.id == id); return w ? w.name : '---'; },
        
        shouldShowPage(p) {
            if (this.totalPages <= 5) return true;
            return Math.abs(p - this.currentPage) <= 1 || p === 1 || p === this.totalPages;
        },

        openModal(car = null) {
            this.isEditing = !!car;
            this.deletedImageIds = [];
            this.newFiles = { auction: [], warehouse: [], loading: [] };
            this.newPreviews = { auction: [], warehouse: [], loading: [] };
            
            if (car) {
                this.formData = JSON.parse(JSON.stringify(car));
                // Fetch existing images from the car_image table via separate call or nested data
                this.existingImages = car.images || []; 
            } else {
                this.formData = { status: 'at_auction', client_id: '', auction_id: '', warehouse_id: '' };
                this.existingImages = [];
            }
            this.modalInstance.show();
        },

        async saveCar() {
            this.loading = true;
            const form = new FormData();
            
            // 1. Add Car Data
            Object.keys(this.formData).forEach(key => {
                if (this.formData[key] !== null) form.append(`Car[\${key}]`, this.formData[key]);
            });

            // 2. Add New Files
            ['auction', 'warehouse', 'loading'].forEach(type => {
                this.newFiles[type].forEach((file) => {
                    form.append(`image_files[\${type}][]`, file);
                });
            });

            // 3. Add IDs to delete
            this.deletedImageIds.forEach(id => form.append('delete_image_ids[]', id));

            try {
                const res = await axios.post('$saveUrl' + (this.isEditing ? '&id=' + this.formData.id : ''), form, {
                    headers: { 
                        'Content-Type': 'multipart/form-data',
                        'X-CSRF-Token': yii.getCsrfToken() 
                    }
                });
                if (res.data.success) {
                    // Update local list or refresh
                    location.reload(); 
                } else {
                    alert('Save failed: ' + JSON.stringify(res.data.errors));
                }
            } catch (e) { 
                console.error(e);
                alert('An error occurred during save.'); 
            } finally {
                this.loading = false;
            }
        },

        async deleteCar(id) {
            if (!confirm("Are you sure you want to delete this car?")) return;
            try {
                const res = await axios.post('$deleteUrl' + '&id=' + id, {}, {
                    headers: { 'X-CSRF-Token': yii.getCsrfToken() }
                });
                if (res.data.success) {
                    this.cars = this.cars.filter(c => c.id !== id);
                }
            } catch (e) { alert('Delete failed.'); }
        }
    }
}).mount('#carApp');
JS;
$this->registerJs($js);
?>