<?php
use yii\helpers\Url;
use yii\helpers\Html;

/** @var yii\web\View $this */
/** @var yii\data\ActiveDataProvider $dataProvider */

$this->title = 'Auctions';

// 1. Prepare the data safely for JavaScript
$models = $dataProvider->getModels();
$rows = [];
foreach ($models as $model) {
    $rows[] = [
        'id' => $model->id,
        'name' => $model->name,
        'created' => Yii::$app->formatter->asDate($model->created, 'php:M d, Y'),
    ];
}
$jsonAuctions = json_encode($rows);

// 2. Register Vue and Axios
$this->registerJsFile('https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.js', ['position' => \yii\web\View::POS_HEAD]);
$this->registerJsFile('https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js', ['position' => \yii\web\View::POS_HEAD]);
?>

<div id="app" class="auction-index 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">
            Auction Management
            <span class="badge bg-primary-subtle text-primary rounded-pill ms-2" style="font-size: 0.8rem;">
                {{ filteredList.length }} Total
            </span>
        </h4>
        <a href="<?= Url::to(['create']) ?>" class="btn btn-primary rounded-pill px-4 shadow-sm fw-bold border-0">
            <i class="bi bi-plus-lg me-1"></i> New Auction
        </a>
    </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" 
                placeholder="Search by name..." 
                class="form-control form-control-lg border-0 shadow-none py-4"
                style="font-size: 1.1rem;"
            >
        </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">
                <thead style="background-color: #f8f9fa;">
                    <tr>
                        <th class="ps-4 py-3 text-muted small fw-bold" style="width: 80px">SERIAL</th>
                        <th class="py-3 text-muted small fw-bold">NAME</th>
                        <th class="py-3 text-muted small fw-bold">CREATED</th>
                        <th class="py-3 text-muted small fw-bold text-end pe-4">ACTIONS</th>
                    </tr>
                </thead>
                <tbody class="bg-white">
                    <tr v-for="(item, index) in paginatedList" :key="item.id">
                        <td class="ps-4 text-muted">#{{ ((currentPage - 1) * pageSize) + index + 1 }}</td>
                        <td><span class="fw-bold text-dark">{{ item.name }}</span></td>
                        <td><span class="badge bg-light text-dark border fw-normal">{{ item.created }}</span></td>
                        <td class="text-end pe-4">
                            <a :href="'<?= Url::to(['update']) ?>?id=' + item.id" class="btn btn-sm btn-outline-info border-0 rounded-pill mx-1">
                                <i class="bi bi-pencil-square"></i>
                            </a>
                            <button @click="confirmDelete(item.id)" class="btn btn-sm btn-outline-danger border-0 rounded-pill mx-1">
                                <i class="bi bi-trash3"></i>
                            </button>
                        </td>
                    </tr>
                    <tr v-if="filteredList.length === 0">
                        <td colspan="4" class="text-center py-5 text-muted">
                            <i class="bi bi-search fs-1 mb-3 d-block opacity-25"></i>
                            No auctions 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="filteredList.length > 0">
            <div class="d-flex align-items-center">
                <div class="small text-muted ps-2 me-3">
                    Showing <strong>{{ startIndex }}</strong> to <strong>{{ endIndex }}</strong> of {{ filteredList.length }} entries
                </div>
                <select v-model="pageSize" class="form-select form-select-sm border-0 bg-light rounded-pill px-3" style="width: auto; cursor: pointer;">
                    <option :value="10">10 Rows</option>
                    <option :value="25">25 Rows</option>
                    <option :value="50">50 Rows</option>
                    <option :value="100">100 Rows</option>
                </select>
            </div>
            <nav v-if="totalPages > 1">
                <ul class="pagination pagination-sm mb-0">
                    <li class="page-item" :class="{ disabled: currentPage === 1 }">
                        <button class="page-link shadow-none border-0" @click="currentPage = 1"><i class="bi bi-chevron-double-left"></i></button>
                    </li>
                    <li class="page-item" :class="{ disabled: currentPage === 1 }">
                        <button class="page-link shadow-none 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 shadow-none border-0" @click="currentPage = page">
                            {{ page }}
                        </button>
                    </li>

                    <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                        <button class="page-link shadow-none border-0" @click="currentPage++"><i class="bi bi-chevron-right"></i></button>
                    </li>
                    <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                        <button class="page-link shadow-none border-0" @click="currentPage = totalPages"><i class="bi bi-chevron-double-right"></i></button>
                    </li>
                </ul>
            </nav>
        </div>
    </div>
</div>

<style>
    [v-cloak] { display: none !important; }
    body { background-color: #f0f2f5; font-family: 'Inter', sans-serif; }
    .rounded-4 { border-radius: 1rem; }
    
    /* Table Styling */
    .table thead th { border-bottom: 1px solid #eee; font-size: 0.75rem; letter-spacing: 0.05em; }
    .table-hover tbody tr:hover { background-color: #fcfdfe !important; }
    
    /* Pagination Polish */
    .page-link { color: #6c757d; font-size: 0.85rem; padding: 0.5rem 0.75rem; }
    .page-item.active .page-link { background-color: #0d6efd; color: white !important; border-radius: 50% !important; }
    .page-item.disabled .page-link { background-color: transparent; color: #dee2e6; }
</style>

<?php
$deleteUrl = Url::to(['delete']);
$js = <<<JS
    const { createApp } = Vue;

    createApp({
        data() {
            return {
                searchQuery: '',
                auctions: $jsonAuctions,
                currentPage: 1,
                pageSize: 10 // Change this to set how many rows to show
            }
        },
        watch: {
            searchQuery() {
                this.currentPage = 1;
            },
            pageSize() {
                this.currentPage = 1;
            }
        },
        computed: {
            // Filter list based on search query
            filteredList() {
                if (!this.searchQuery) return this.auctions;
                return this.auctions.filter(item => 
                    item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
                );
            },
            // Slice the filtered list for the current page
            paginatedList() {
                const start = (this.currentPage - 1) * this.pageSize;
                const end = start + this.pageSize;
                return this.filteredList.slice(start, end);
            },
            totalPages() {
                return Math.ceil(this.filteredList.length / this.pageSize);
            },
            startIndex() {
                return (this.currentPage - 1) * this.pageSize + 1;
            },
            endIndex() {
                return Math.min(this.currentPage * this.pageSize, this.filteredList.length);
            }
        },
        methods: {
            shouldShowPage(page) {
                // Logic to show only a few page numbers if there are many
                if (this.totalPages <= 7) return true;
                return Math.abs(page - this.currentPage) <= 2 || page === 1 || page === this.totalPages;
            },
            confirmDelete(id) {
                if (confirm("Move this auction to trash?")) {
                    axios.post('$deleteUrl?id=' + id, {}, {
                        headers: { 'X-Requested-With': 'XMLHttpRequest' }
                    }).then(response => {
                        this.auctions = this.auctions.filter(a => a.id !== id);
                        // If current page becomes empty, go back one page
                        if (this.paginatedList.length === 0 && this.currentPage > 1) {
                            this.currentPage--;
                        }
                    }).catch(error => {
                        alert("Error deleting record.");
                        console.error(error);
                    });
                }
            }
        }
    }).mount('#app');
JS;
$this->registerJs($js);
?>