<?php
use yii\helpers\Url;

$this->title = 'Clients';
// Safely encode the initial data from the controller
$jsonClients = json_encode($rows, JSON_HEX_APOS | JSON_HEX_QUOT);
$saveUrl = Url::to(['client/save-ajax']);
$deleteUrl = Url::to(['client/delete']);
$getNextNoUrl = Url::to(['client/get-next-no']);
?>

<div id="app" 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">
            Client Directory
            <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-person-plus-fill me-1"></i> New Client
        </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 name, client no, phone, or town..." 
                   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">NO.</th>
                        <th class="py-3 text-muted small fw-bold">CLIENT NAME / CONTACT</th>
                        <th class="py-3 text-muted small fw-bold">ADDRESS & LOCATION</th>
                        <th class="py-3 text-muted small fw-bold text-end">BALANCE</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 in paginatedList" :key="item.id">
                        <td class="ps-4 fw-bold text-primary">#{{ item.no }}</td>
                        <td>
                            <div class="fw-bold text-dark">{{ item.name }}</div>
                            <div class="text-muted small">{{ item.phone }} | {{ item.email }}</div>
                        </td>
                        <td>
                            <div class="small text-dark">{{ item.address }}</div>
                            <div class="text-muted small">{{ item.town }}, {{ item.country }}</div>
                        </td>
                        <td class="text-end fw-bold text-dark">
                            ${{ parseFloat(item.balance).toLocaleString(undefined, {minimumFractionDigits: 2}) }}
                        </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="5" class="text-center py-5 text-muted">
                            No clients 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 > pageSize">
            <div class="small text-muted ps-2">
                Showing <strong>{{ startIndex }}</strong> to <strong>{{ endIndex }}</strong> of <strong>{{ filteredList.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>

    <div class="modal fade" id="clientModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <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 Client Details' : 'Register New Client' }}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4">
                    <form @submit.prevent="submitForm">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <label class="small fw-bold text-muted">CLIENT NO</label>
                                <input type="text" v-model="formData.no" class="form-control bg-secondary-subtle border-0 fw-bold" readonly tabindex="-1">
                            </div>
                            <div class="col-md-8">
                                <label class="small fw-bold">FULL NAME</label>
                                <input type="text" v-model="formData.name" class="form-control bg-light border-0" required>
                            </div>
                            <div class="col-md-6">
                                <label class="small fw-bold">PHONE</label>
                                <input type="text" v-model="formData.phone" class="form-control bg-light border-0" required>
                            </div>
                            <div class="col-md-6">
                                <label class="small fw-bold">EMAIL</label>
                                <input type="email" v-model="formData.email" class="form-control bg-light border-0" required>
                            </div>
                            <div class="col-12">
                                <label class="small fw-bold">ADDRESS</label>
                                <input type="text" v-model="formData.address" class="form-control bg-light border-0">
                            </div>
                            <div class="col-md-4">
                                <label class="small fw-bold">TOWN</label>
                                <input type="text" v-model="formData.town" class="form-control bg-light border-0">
                            </div>
                            <div class="col-md-4">
                                <label class="small fw-bold">COUNTRY</label>
                                <input type="text" v-model="formData.country" class="form-control bg-light border-0">
                            </div>
                            <div class="col-md-4">
                                <label class="small fw-bold">OPENING BALANCE</label>
                                <input type="number" step="0.01" v-model="formData.balance" class="form-control bg-light border-0" :disabled="isEditing">
                            </div>

                            <hr class="my-4 text-muted">
                            <h6 class="fw-bold mb-3 text-primary"><i class="bi bi-shield-lock me-2"></i>LOGIN CREDENTIALS</h6>

                            <div class="col-md-12 mb-2">
                                <label class="small fw-bold">USERNAME</label>
                                <input type="text" v-model="formData.username" class="form-control bg-light border-0" 
                                       required placeholder="Unique username for login">
                            </div>

                            <div class="col-md-6">
                                <label class="small fw-bold">
                                    PASSWORD 
                                    <span v-if="isEditing" class="text-muted small fw-normal">(Leave blank to keep current)</span>
                                </label>
                                <input type="password" v-model="formData.password" class="form-control bg-light border-0" :required="!isEditing">
                            </div>
                            <div class="col-md-6">
                                <label class="small fw-bold">CONFIRM PASSWORD</label>
                                <input type="password" v-model="formData.password_confirm" 
                                       class="form-control bg-light border-0" 
                                       :class="{'is-invalid': passwordMismatch}" 
                                       :required="!isEditing && formData.password !== ''">
                                <div v-if="passwordMismatch" class="invalid-feedback">Passwords do not match.</div>
                            </div>
                        </div>

                        <div class="d-flex justify-content-end gap-2 mt-4">
                            <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" :disabled="loading || passwordMismatch">
                                <span v-if="loading" class="spinner-border spinner-border-sm me-1"></span> 
                                {{ isEditing ? 'Update Client' : 'Save Client' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    [v-cloak] { display: none; }
    .rounded-4 { border-radius: 1rem; }
    .page-item.active .page-link { background-color: #0d6efd; color: white !important; border-radius: 50% !important; }
    .pagination .page-link { color: #666; padding: 0.5rem 0.75rem; }
    .is-invalid { border: 1px solid #dc3545 !important; }
    .table-hover tbody tr:hover { background-color: #f8f9fa; }
</style>

<?php
$js = <<<JS
const { createApp } = Vue;
createApp({
    data() {
        return {
            searchQuery: '',
            clients: $jsonClients,
            currentPage: 1,
            pageSize: 10,
            formData: { 
                id: null, no: '', name: '', phone: '', email: '', 
                address: '', town: '', country: '', balance: 0,
                username: '', password: '', password_confirm: '' 
            },
            isEditing: false,
            loading: false,
            modalInstance: null
        }
    },
    computed: {
        passwordMismatch() {
            if (!this.formData.password && !this.formData.password_confirm) return false;
            return this.formData.password !== this.formData.password_confirm;
        },
        filteredList() {
            if (!this.searchQuery) return this.clients;
            const q = this.searchQuery.toLowerCase();
            return this.clients.filter(i => {
                return (i.name || '').toLowerCase().includes(q) || 
                       (i.no || '').toLowerCase().includes(q) || 
                       (i.phone || '').toLowerCase().includes(q) || 
                       (i.town || '').toLowerCase().includes(q);
            });
        },
        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) || 1;
        },
        startIndex() {
            return this.filteredList.length === 0 ? 0 : (this.currentPage - 1) * this.pageSize + 1;
        },
        endIndex() {
            return Math.min(this.currentPage * this.pageSize, this.filteredList.length);
        }
    },
    mounted() {
        this.modalInstance = new bootstrap.Modal(document.getElementById('clientModal'));
    },
    methods: {
        shouldShowPage(page) {
            if (this.totalPages <= 5) return true;
            return Math.abs(page - this.currentPage) <= 1 || page === 1 || page === this.totalPages;
        },
        async openModal(item = null) {
            if (item) {
                this.isEditing = true;
                // Important: Reset password fields on open
                this.formData = { 
                    ...item, 
                    password: '', 
                    password_confirm: '',
                    // Assume username is available in the 'item' array from controller
                    username: item.username || '' 
                };
            } else {
                this.isEditing = false;
                this.formData = { 
                    id: null, no: 'Loading...', name: '', phone: '', email: '', 
                    address: '', town: '', country: '', balance: 0,
                    username: '', password: '', password_confirm: ''
                };
                
                try {
                    const res = await axios.get('$getNextNoUrl');
                    this.formData.no = res.data.next_no;
                } catch (e) {
                    this.formData.no = 'ERR';
                }
            }
            this.modalInstance.show();
        },
        async submitForm() {
            this.loading = true;
            try {
                const res = await axios.post('$saveUrl', this.formData, {
                    headers: { 
                        'X-CSRF-Token': yii.getCsrfToken(),
                        'Content-Type': 'application/json'
                    }
                });
                
                if (res.data.success) {
                    const saved = res.data.client;
                    // Add the username back to the client object for display/edit
                    saved.username = this.formData.username; 
                    
                    if (this.isEditing) {
                        const idx = this.clients.findIndex(c => c.id === saved.id);
                        this.clients.splice(idx, 1, saved);
                    } else {
                        this.clients.unshift(saved);
                    }
                    this.modalInstance.hide();
                } else {
                    alert(res.data.message || "Failed to save record.");
                }
            } catch (e) {
                const msg = e.response?.data?.message || "Server error. Please check your connection.";
                alert(msg);
            } finally { this.loading = false; }
        },
        confirmDelete(id) {
            if (!confirm("Are you sure? This will delete the client and their user account. It will be blocked if car records exist.")) return;
            
            axios.post('$deleteUrl' + '&id=' + id, {}, {
                headers: { 'X-CSRF-Token': yii.getCsrfToken() }
            }).then(res => {
                if (res.data.success) {
                    this.clients = this.clients.filter(c => c.id !== id);
                } else {
                    // This will display your custom message about car records
                    alert(res.data.message || "Could not delete record.");
                }
            }).catch(err => {
                alert("Server error during deletion.");
            });
        }
    }
}).mount('#app');
JS;
$this->registerJs($js);
?>