File size: 12,420 Bytes
ba33f5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
document.addEventListener('DOMContentLoaded', function() {
    // Variables de estado
    let parkingSlots = [];
    let totalSlots = 20;
    let availableSlots = 20;
    
    // Elementos del DOM
    const parkingSlotsInput = document.getElementById('parking-slots');
    const updateLayoutBtn = document.getElementById('update-layout');
    const monthlyFixedBtn = document.getElementById('monthly-fixed-btn');
    const monthlyRotatingBtn = document.getElementById('monthly-rotating-btn');
    const hourlyBtn = document.getElementById('hourly-btn');
    const exitPlateInput = document.getElementById('exit-plate');
    const processExitBtn = document.getElementById('process-exit');
    const modal = document.getElementById('modal');
    const modalTitle = document.getElementById('modal-title');
    const modalContent = document.getElementById('modal-content');
    const modalCancel = document.getElementById('modal-cancel');
    const modalConfirm = document.getElementById('modal-confirm');
    const availableSlotsSpan = document.getElementById('available-slots');
    const totalSlotsSpan = document.getElementById('total-slots');
    const parkingGrid = document.querySelector('parking-grid');
    
    // Inicializar la cuadrícula de estacionamiento
    function initializeParking() {
        totalSlots = parseInt(parkingSlotsInput.value);
        availableSlots = totalSlots;
        parkingSlots = Array(totalSlots).fill(null);
        
        updateCounters();
        parkingGrid.setAttribute('slots', totalSlots);
    }
    
    // Actualizar contadores
    function updateCounters() {
        availableSlotsSpan.textContent = availableSlots;
        totalSlotsSpan.textContent = totalSlots;
    }
    
    // Mostrar modal
    function showModal(title, content, confirmCallback) {
        modalTitle.textContent = title;
        modalContent.innerHTML = content;
        
        modal.classList.remove('hidden');
        modal.classList.add('flex');
        
        // Configurar el botón de confirmación
        modalConfirm.onclick = function() {
            if (confirmCallback) confirmCallback();
            hideModal();
        };
    }
    
    // Ocultar modal
    function hideModal() {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
    }
    
    // Procesar ingreso de vehículo
    function processVehicleEntry(type) {
        if (availableSlots <= 0) {
            showModal('Estacionamiento lleno', '<p class="text-red-600">No hay plazas disponibles en este momento.</p>');
            return;
        }
        
        let title, content;
        
        switch(type) {
            case 'monthly-fixed':
                title = 'Ingreso mensual fijo';
                content = `
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Número de placa</label>
                            <input type="text" id="plate-number" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Ej: ABC123">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Número de plaza asignada</label>
                            <input type="number" id="assigned-slot" min="1" max="${totalSlots}" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                    </div>
                `;
                break;
                
            case 'monthly-rotating':
                title = 'Ingreso mensual rotativo';
                content = `
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Número de placa</label>
                            <input type="text" id="plate-number" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Ej: ABC123">
                        </div>
                        <div class="flex items-center">
                            <input type="checkbox" id="key-deposit" class="mr-2">
                            <label class="text-sm font-medium text-gray-700">El cliente dejó las llaves</label>
                        </div>
                    </div>
                `;
                break;
                
            case 'hourly':
                title = 'Ingreso por hora';
                content = `
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Número de placa</label>
                            <input type="text" id="plate-number" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Ej: ABC123">
                        </div>
                        <div class="flex items-center">
                            <input type="checkbox" id="key-deposit" class="mr-2" checked>
                            <label class="text-sm font-medium text-gray-700">El cliente dejó las llaves</label>
                        </div>
                    </div>
                `;
                break;
        }
        
        showModal(title, content, function() {
            const plateNumber = document.getElementById('plate-number').value.trim();
            
            if (!plateNumber) {
                alert('Por favor ingrese el número de placa');
                return;
            }
            
            let assignedSlot;
            
            if (type === 'monthly-fixed') {
                assignedSlot = parseInt(document.getElementById('assigned-slot').value) - 1;
                
                if (isNaN(assignedSlot) || assignedSlot < 0 || assignedSlot >= totalSlots) {
                    alert('Por favor ingrese un número de plaza válido');
                    return;
                }
                
                if (parkingSlots[assignedSlot] !== null) {
                    alert('Esta plaza ya está ocupada');
                    return;
                }
            } else {
                // Encontrar la primera plaza disponible
                assignedSlot = parkingSlots.findIndex(slot => slot === null);
                
                if (assignedSlot === -1) {
                    alert('No hay plazas disponibles');
                    return;
                }
            }
            
            const keyDeposit = type !== 'monthly-fixed' ? document.getElementById('key-deposit').checked : false;
            
            parkingSlots[assignedSlot] = {
                type: type,
                plateNumber: plateNumber,
                entryTime: new Date(),
                keyDeposit: keyDeposit,
                assignedSlot: type === 'monthly-fixed' ? assignedSlot : null
            };
            
            availableSlots--;
            updateCounters();
            parkingGrid.setAttribute('slots-data', JSON.stringify(parkingSlots));
            
            let message = `Vehículo registrado exitosamente en plaza ${assignedSlot + 1}`;
            if (type === 'hourly') {
                message += '<br><br><strong class="text-blue-600">Ticket generado:</strong> ' + generateTicketNumber();
            }
            
            showModal('Registro exitoso', `<p>${message}</p>`);
        });
    }
    
    // Generar número de ticket
    function generateTicketNumber() {
        return 'T-' + Date.now().toString().slice(-6);
    }
    
    // Procesar salida de vehículo
    function processExit() {
        const plateNumber = exitPlateInput.value.trim();
        
        if (!plateNumber) {
            alert('Por favor ingrese el número de placa');
            return;
        }
        
        const slotIndex = parkingSlots.findIndex(slot => slot && slot.plateNumber === plateNumber);
        
        if (slotIndex === -1) {
            showModal('Vehículo no encontrado', '<p class="text-red-600">No se encontró un vehículo con esa placa en el estacionamiento.</p>');
            return;
        }
        
        const vehicle = parkingSlots[slotIndex];
        let content = `
            <div class="space-y-3">
                <p><strong>Tipo:</strong> ${getVehicleTypeName(vehicle.type)}</p>
                <p><strong>Placa:</strong> ${vehicle.plateNumber}</p>
                <p><strong>Plaza:</strong> ${slotIndex + 1}</p>
                <p><strong>Hora de entrada:</strong> ${vehicle.entryTime.toLocaleTimeString()}</p>
        `;
        
        if (vehicle.type === 'hourly') {
            const exitTime = new Date();
            const duration = Math.ceil((exitTime - vehicle.entryTime) / (1000 * 60 * 60)); // Horas
            const rate = 5; // $5 por hora
            const total = duration * rate;
            
            content += `
                <p><strong>Tiempo estacionado:</strong> ~${duration} hora(s)</p>
                <p><strong>Tarifa:</strong> $${rate} por hora</p>
                <p class="font-bold text-lg">Total a pagar: $${total}</p>
                <div class="mt-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Método de pago</label>
                    <select id="payment-method" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="cash">Efectivo</option>
                        <option value="card">Tarjeta</option>
                        <option value="transfer">Transferencia</option>
                    </select>
                </div>
            `;
        }
        
        if (vehicle.keyDeposit) {
            content += `
                <div class="mt-3 flex items-center">
                    <input type="checkbox" id="return-key" class="mr-2" checked>
                    <label class="text-sm font-medium text-gray-700">Llaves devueltas al cliente</label>
                </div>
            `;
        }
        
        content += `</div>`;
        
        showModal('Procesar salida', content, function() {
            if (vehicle.type === 'hourly') {
                const paymentMethod = document.getElementById('payment-method').value;
                // Aquí podrías registrar el pago en tu sistema
            }
            
            if (vehicle.keyDeposit) {
                const keyReturned = document.getElementById('return-key').checked;
                if (!keyReturned) {
                    alert('¡Atención! Las llaves no fueron devueltas al cliente');
                    // Podrías registrar esto como una alerta
                }
            }
            
            // Liberar la plaza
            parkingSlots[slotIndex] = null;
            availableSlots++;
            updateCounters();
            parkingGrid.setAttribute('slots-data', JSON.stringify(parkingSlots));
            
            exitPlateInput.value = '';
            showModal('Salida registrada', '<p class="text-green-600">La salida del vehículo ha sido registrada exitosamente.</p>');
        });
    }
    
    // Obtener nombre del tipo de vehículo
    function getVehicleTypeName(type) {
        switch(type) {
            case 'monthly-fixed': return 'Mensual con plaza fija';
            case 'monthly-rotating': return 'Mensual rotativo';
            case 'hourly': return 'Por hora';
            default: return type;
        }
    }
    
    // Event listeners
    updateLayoutBtn.addEventListener('click', initializeParking);
    monthlyFixedBtn.addEventListener('click', () => processVehicleEntry('monthly-fixed'));
    monthlyRotatingBtn.addEventListener('click', () => processVehicleEntry('monthly-rotating'));
    hourlyBtn.addEventListener('click', () => processVehicleEntry('hourly'));
    processExitBtn.addEventListener('click', processExit);
    modalCancel.addEventListener('click', hideModal);
    
    // Permitir procesar salida con Enter
    exitPlateInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            processExit();
        }
    });
    
    // Inicializar la aplicación
    initializeParking();
});