<?php
use yii\helpers\Url;
/** @var array $rows */

$this->title = 'Warehouses';
$jsonWarehouses = json_encode($rows);
$saveUrl = Url::to(['warehouse/save-ajax']);
$deleteUrl = Url::to(['warehouse/delete']);
?>

<div id="app" class="warehouse-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">
            Warehouse Management
            <span class="badge bg-primary-subtle text-primary rounded-pill ms-2" style="font-size: 0.8rem;">
                {{ filteredList.length }} Total
            </span>
        </h4>
        <button @click="openModal()" class="btn btn-primary rounded-pill px-4 shadow-sm fw-bold border-0">
            <i class="bi bi-plus-lg me-1"></i> New Warehouse
        </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" placeholder="Search warehouses..." 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">
                <thead class="bg-light">
                    <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 class="fw-bold text-dark">{{ item.name }}</td>
                        <td><span class="badge bg-light text-dark border fw-normal">{{ item.created }}</span></td>
                        <td class="text-end pe-4">
                            <button @click="openModal(item)" class="btn btn-sm btn-outline-info border-0 rounded-pill mx-1">
                                <i class="bi bi-pencil-square"></i>
                            </button>
                            <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">No records found.</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="small text-muted ps-2">
                Showing <strong>{{ startIndex }}</strong> to <strong>{{ endIndex }}</strong>
            </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 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>

    <div class="modal fade" id="warehouseModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow-lg rounded-4">
                <div class="modal-header border-0 pb-0 pt-4 px-4">
                    <h5 class="fw-bold">{{ isEditing ? 'Edit Warehouse' : 'New Warehouse' }}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4">
                    <div v-if="serverErrors.name" class="alert alert-danger border-0 small rounded-3 mb-3">
                        <i class="bi bi-exclamation-triangle-fill me-2"></i>
                        {{ serverErrors.name[0] }}
                    </div>
                    <form @submit.prevent="submitForm">
                        <div class="mb-4">
                            <label class="form-label small text-muted fw-bold">WAREHOUSE NAME</label>
                            <input type="text" v-model="formData.name" class="form-control form-control-lg bg-light border-0" placeholder="e.g. Main Hub" required>
                        </div>
                        <div class="d-flex justify-content-end gap-2">
                            <button type="button" class="btn btn-light rounded-pill px-4" data-bs-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary rounded-pill px-4 shadow-sm" :disabled="loading">
                                <span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
                                {{ isEditing ? 'Update' : 'Save' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    [v-cloak] { display: none !important; }
    .rounded-4 { border-radius: 1rem; }
    .page-item.active .page-link { background-color: #0d6efd; color: white !important; border-radius: 50% !important; }
</style>

<?php
$js = <<<JS
const { createApp } = Vue;
createApp({
    data() {
        return {
            searchQuery: '',
            warehouses: $jsonWarehouses,
            currentPage: 1,
            pageSize: 10,
            formData: { id: null, name: '' },
            serverErrors: {},
            isEditing: false,
            loading: false,
            modalInstance: null
        }
    },
    mounted() {
        this.modalInstance = new bootstrap.Modal(document.getElementById('warehouseModal'));
    },
    computed: {
        filteredList() {
            if (!this.searchQuery) return this.warehouses;
            return this.warehouses.filter(i => i.name.toLowerCase().includes(this.searchQuery.toLowerCase()));
        },
        paginatedList() {
            const start = (this.currentPage - 1) * this.pageSize;
            return this.filteredList.slice(start, start + this.pageSize);
        },
        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) {
            if (this.totalPages <= 5) return true;
            return Math.abs(page - this.currentPage) <= 1 || page === 1 || page === this.totalPages;
        },
        openModal(item = null) {
            this.serverErrors = {};
            if (item) {
                this.isEditing = true;
                this.formData = { ...item };
            } else {
                this.isEditing = false;
                this.formData = { id: null, name: '' };
            }
            this.modalInstance.show();
        },
        async submitForm() {
            this.loading = true;
            this.serverErrors = {};
            try {
                const res = await axios.post('$saveUrl', this.formData, {
                    headers: { 
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-Token': yii.getCsrfToken() 
                    }
                });
                if (res.data.success) {
                    if (this.isEditing) {
                        const idx = this.warehouses.findIndex(w => w.id === this.formData.id);
                        this.warehouses[idx] = res.data.model;
                    } else {
                        this.warehouses.unshift(res.data.model);
                    }
                    this.modalInstance.hide();
                } else {
                    this.serverErrors = res.data.errors;
                }
            } catch (error) {
                alert("System error. Record could not be saved.");
            } finally {
                this.loading = false;
            }
        },
        confirmDelete(id) {
            if (confirm("Permanently delete this warehouse?")) {
                axios.post('$deleteUrl' + '&id=' + id, {}, {
                    headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': yii.getCsrfToken() }
                }).then(res => {
                    if (res.data.success) {
                        this.warehouses = this.warehouses.filter(w => w.id !== id);
                    } else {
                        alert(res.data.message || 'Could not delete this warehouse.');
                    }
                }).catch(() => {
                    alert('Network error. Please try again.');
                });
            }
        }
    }
}).mount('#app');
JS;
$this->registerJs($js);
?>