<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Administración de Sucursal - Sufarma</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: { sans: ['Inter', 'sans-serif'] }
                }
            }
        }
    </script>
</head>
<body class="bg-slate-50 min-h-screen font-sans">
    <div class="container mx-auto px-4 py-12 max-w-2xl">
        <div class="bg-white rounded-2xl shadow-xl border border-slate-200 overflow-hidden">
            <div class="bg-gradient-to-r from-blue-600 to-indigo-600 px-8 py-6">
                <h1 class="text-2xl font-bold text-white">Configuración de Sucursal</h1>
                <p class="text-blue-100 mt-1">Selecciona la sucursal activa para este dispositivo</p>
            </div>
            
            <div class="p-8">
                <div id="currentBranchInfo" class="mb-8 p-4 bg-blue-50 border border-blue-100 rounded-xl flex items-center gap-4">
                    <div class="p-3 bg-blue-100 rounded-lg text-blue-600">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"></path>
                        </svg>
                    </div>
                    <div>
                        <p class="text-xs font-bold text-blue-500 uppercase tracking-wide">Sucursal Activa</p>
                        <h2 id="activeBranchName" class="text-xl font-bold text-slate-800">Cargando...</h2>
                    </div>
                </div>

                <div class="space-y-4">
                    <label class="block text-sm font-medium text-slate-700">Cambiar Sucursal</label>
                    <div id="branchesList" class="grid gap-3">
                        <!-- Branches will be loaded here -->
                        <div class="animate-pulse flex space-x-4">
                            <div class="flex-1 space-y-4 py-1">
                                <div class="h-12 bg-slate-200 rounded"></div>
                                <div class="h-12 bg-slate-200 rounded"></div>
                                <div class="h-12 bg-slate-200 rounded"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="mt-8 pt-6 border-t border-slate-100 flex justify-end">
                    <a href="index.html" class="px-6 py-2.5 bg-slate-100 text-slate-700 font-medium rounded-xl hover:bg-slate-200 transition-colors">
                        Ir al Sistema
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Toast -->
    <div id="toast" class="fixed bottom-8 right-8 transform translate-y-32 transition-transform duration-300 z-50">
        <div class="bg-white rounded-xl shadow-2xl border-2 border-slate-200 p-4 min-w-[300px] flex items-center gap-3">
            <div id="toastIcon"></div>
            <div>
                <p id="toastTitle" class="font-bold text-slate-800"></p>
                <p id="toastMessage" class="text-sm text-slate-600"></p>
            </div>
        </div>
    </div>

    <script>
        const API_BASE = 'api/';
        let currentBranchId = null;

        document.addEventListener('DOMContentLoaded', () => {
            loadCurrentBranch();
            loadAllBranches();
        });

        async function loadCurrentBranch() {
            try {
                const response = await fetch(API_BASE + 'get_current_branch.php');
                const data = await response.json();
                if (data.success) {
                    currentBranchId = data.data.id;
                    document.getElementById('activeBranchName').textContent = data.data.nombre;
                    updateSelectionUI();
                }
            } catch (error) {
                console.error('Error loading current branch:', error);
            }
        }

        async function loadAllBranches() {
            try {
                const response = await fetch(API_BASE + 'get_branches.php');
                const data = await response.json();
                
                if (data.success) {
                    renderBranches(data.data);
                }
            } catch (error) {
                console.error('Error loading branches:', error);
                showToast('Error', 'No se pudieron cargar las sucursales', 'error');
            }
        }

        function renderBranches(branches) {
            const container = document.getElementById('branchesList');
            container.innerHTML = branches.map(branch => `
                <button 
                    onclick="setBranch(${branch.id}, '${branch.nombre}')"
                    class="branch-item w-full text-left px-4 py-3 rounded-xl border-2 transition-all duration-200 flex items-center justify-between group
                    ${branch.id == currentBranchId ? 'border-blue-500 bg-blue-50 ring-2 ring-blue-200' : 'border-slate-200 hover:border-blue-300 hover:bg-slate-50'}"
                    data-id="${branch.id}"
                >
                    <span class="font-medium ${branch.id == currentBranchId ? 'text-blue-700' : 'text-slate-700'}">${branch.nombre}</span>
                    ${branch.id == currentBranchId ? 
                        '<span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs font-bold rounded">ACTIVA</span>' : 
                        '<span class="opacity-0 group-hover:opacity-100 text-slate-400 text-sm">Seleccionar</span>'}
                </button>
            `).join('');
        }

        function updateSelectionUI() {
            // Re-render list to update styles if list exists
            const buttons = document.querySelectorAll('.branch-item');
            if (buttons.length > 0) {
                loadAllBranches(); // Reload to refresh styles simply
            }
        }

        async function setBranch(id, name) {
            if (id == currentBranchId) return;

            try {
                const response = await fetch(API_BASE + 'set_current_branch.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ sucursal_id: id })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    currentBranchId = id;
                    document.getElementById('activeBranchName').textContent = name;
                    updateSelectionUI();
                    showToast('Éxito', `Sucursal cambiada a ${name}`, 'success');
                } else {
                    showToast('Error', data.error || 'Error al cambiar sucursal', 'error');
                }
            } catch (error) {
                console.error('Error setting branch:', error);
                showToast('Error', 'Error de conexión', 'error');
            }
        }

        function showToast(title, message, type = 'info') {
            const toast = document.getElementById('toast');
            const toastTitle = document.getElementById('toastTitle');
            const toastMessage = document.getElementById('toastMessage');
            const toastIcon = document.getElementById('toastIcon');

            const icons = {
                success: '<svg class="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>',
                error: '<svg class="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>'
            };

            toastIcon.innerHTML = icons[type] || icons.success;
            toastTitle.textContent = title;
            toastMessage.textContent = message;

            toast.classList.remove('translate-y-32');
            setTimeout(() => toast.classList.add('translate-y-32'), 3000);
        }
    </script>
</body>
</html>
