<script>
// Tab switching function with URL parameter
function switchTab(tabName) {
    // Update URL without reloading
    const url = new URL(window.location.href);
    url.searchParams.set('tab', tabName);
    window.history.pushState({}, '', url);
    
    // Hide all tab panes
    document.querySelectorAll('.tab-pane').forEach(pane => {
        pane.classList.remove('active');
    });
    
    // Show selected tab pane
    const selectedPane = document.getElementById('tab-' + tabName);
    if (!selectedPane) {
        const fallback = document.getElementById('tab-account');
        if (fallback) {
            url.searchParams.set('tab', 'account');
            window.history.replaceState({}, '', url);
            fallback.classList.add('active');
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.classList.toggle('active', btn.dataset.tab === 'tab-account');
            });
        }
        return;
    }
    selectedPane.classList.add('active');
    
    // Update tab buttons
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
        if (btn.dataset.tab === 'tab-' + tabName) {
            btn.classList.add('active');
        }
    });
}

// Initialize tabs on page load
document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const tab = urlParams.get('tab');
    if (tab) {
        switchTab(tab);
    }
});



// Test WhatsApp
function testWhatsApp() {
    const whatsappNumber = document.getElementById('whatsapp_number').value;
    if (!whatsappNumber) {
        showToast('Please set a WhatsApp number first', 'warning');
        return;
    }
    const message = encodeURIComponent('Hello! This is a test message from SHARK CRM.');
    window.open(`https://wa.me/${whatsappNumber.replace(/[^0-9+]/g, '')}?text=${message}`, '_blank');
}

async function testEmail() {
    const emailFrom = document.getElementById('email_from').value;
    if (!emailFrom) {
        showToast('Please set an email address first', 'warning');
        return;
    }
    
    const res = await apiCall('handlers/settings.php', { 
        action: 'test_email',
        email: emailFrom
    });
    
    if (res.success) {
        showToast('Test email sent successfully!', 'success');
    } else {
        showToast(res.message || 'Failed to send test email', 'error');
    }
}

function editUser(id, name, email, phone, roleId) {
    document.getElementById('edit_user_id').value = id;
    document.getElementById('edit_user_name').value = name;
    document.getElementById('edit_user_email').value = email;
    document.getElementById('edit_user_phone').value = phone || '';
    document.getElementById('edit_user_role').value = roleId || '';
    openModal('editUserModal');
}

async function updateUser() {
    const fd = new FormData(document.getElementById('editUserForm'));
    fd.append('action', 'update_user');
    
    const res = await apiCall('handlers/settings.php', fd);
    if (res.success) { 
        showToast('User updated!', 'success'); 
        closeModal('editUserModal'); 
        setTimeout(() => location.reload(), 600); 
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

async function changeUserRole(userId, roleId) {
    const res = await apiCall('handlers/settings.php', {
        action: 'update_user_role',
        user_id: userId,
        role_id: roleId
    });
    
    if (res.success) {
        showToast('Role updated!', 'success');
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

function editLostReason(id) {
    document.getElementById('lr_name_span_' + id).style.display = 'none';
    document.getElementById('lr_name_' + id).style.display = 'block';
    document.getElementById('lr_status_span_' + id).style.display = 'none';
    document.getElementById('lr_status_' + id).style.display = 'block';
    document.getElementById('lr_edit_btn_' + id).style.display = 'none';
    document.getElementById('lr_save_btn_' + id).style.display = 'inline-block';
}

async function saveLostReason(id) {
    const name = document.getElementById('lr_name_' + id).value.trim();
    const status = document.getElementById('lr_status_' + id).value;
    
    if (!name) {
        showToast('Please enter a reason', 'warning');
        return;
    }
    
    const res = await apiCall('handlers/settings.php', {
        action: 'update_lost_reason',
        id: id,
        name: name,
        status: status
    });
    
    if (res.success) {
        showToast('Lost reason updated!', 'success');
        document.getElementById('lr_name_span_' + id).textContent = name;
        document.getElementById('lr_status_span_' + id).textContent = status.charAt(0).toUpperCase() + status.slice(1);
        document.getElementById('lr_status_span_' + id).className = 'badge badge-' + (status === 'active' ? 'green' : 'gray');
        
        // Reset display
        document.getElementById('lr_name_span_' + id).style.display = 'inline';
        document.getElementById('lr_name_' + id).style.display = 'none';
        document.getElementById('lr_status_span_' + id).style.display = 'inline';
        document.getElementById('lr_status_' + id).style.display = 'none';
        document.getElementById('lr_edit_btn_' + id).style.display = 'inline-block';
        document.getElementById('lr_save_btn_' + id).style.display = 'none';
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

function editStage(id) {
    document.getElementById('stage_name_span_' + id).style.display = 'none';
    document.getElementById('stage_name_' + id).style.display = 'block';
    document.getElementById('stage_position_span_' + id).style.display = 'none';
    document.getElementById('stage_position_' + id).style.display = 'block';
    document.getElementById('stage_color_span_' + id).style.display = 'none';
    document.getElementById('stage_color_' + id).style.display = 'block';
    // Stage type is locked after creation to protect linked leads.
    document.getElementById('stage_edit_btn_' + id).style.display = 'none';
    document.getElementById('stage_save_btn_' + id).style.display = 'inline-block';
}

async function saveStage(id) {
    const name = document.getElementById('stage_name_' + id).value.trim();
    const position = document.getElementById('stage_position_' + id).value;
    const color = document.getElementById('stage_color_' + id).value;
    const type = document.getElementById('stage_type_' + id).value;
    
    if (!name) {
        showToast('Enter stage name', 'warning');
        return;
    }
    
    const res = await apiCall('handlers/settings.php', {
        action: 'update_stage',
        id: id,
        name: name,
        position: position,
        color: color,
        type: type
    });
    
    if (res.success) {
        showToast('Stage updated!', 'success');
        
        // Update displayed values
        document.getElementById('stage_name_span_' + id).textContent = name;
        document.getElementById('stage_position_span_' + id).textContent = position;
        document.getElementById('stage_color_span_' + id).style.backgroundColor = color;
        
        // Update type badge
        let typeHtml = '';
        if (type === 'start') typeHtml = '<span class="badge badge-green">Start</span>';
        else if (type === 'won') typeHtml = '<span class="badge badge-green">End - Won</span>';
        else if (type === 'lost') typeHtml = '<span class="badge badge-red">End - Lost</span>';
        else if (type === 'end') typeHtml = '<span class="badge badge-red">End</span>';
        else typeHtml = '<span class="badge badge-blue">Normal</span>';
        document.getElementById('stage_type_span_' + id).innerHTML = typeHtml;
        
        // Reset display
        document.getElementById('stage_name_span_' + id).style.display = 'inline';
        document.getElementById('stage_name_' + id).style.display = 'none';
        document.getElementById('stage_position_span_' + id).style.display = 'inline';
        document.getElementById('stage_position_' + id).style.display = 'none';
        document.getElementById('stage_color_span_' + id).style.display = 'inline-block';
        document.getElementById('stage_color_' + id).style.display = 'none';
        document.getElementById('stage_type_span_' + id).style.display = 'inline';
        document.getElementById('stage_edit_btn_' + id).style.display = 'inline-block';
        document.getElementById('stage_save_btn_' + id).style.display = 'none';
        if (['start','won','lost'].includes(type)) setTimeout(() => location.reload(), 500);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

async function addStage() {
    const name = document.getElementById('stageName').value.trim();
    const position = document.getElementById('stagePosition').value;
    const color = document.getElementById('stageColor').value;
    const type = document.getElementById('stageType').value;

    if (!name) {
        showToast('Enter stage name', 'warning');
        return;
    }

    const res = await apiCall('handlers/settings.php', {
        action: 'add_stage',
        name: name,
        position: position,
        color: color,
        type: type
    });

    if (res.success) {
        showToast('Stage added!', 'success');
        closeModal('addStageModal');
        setTimeout(() => location.reload(), 600);
    }
}

async function deleteStage(id) {
    confirmAction('Delete this stage?', async () => {
        const res = await apiCall('handlers/settings.php', {
            action: 'delete_stage',
            id: id
        });

        if (res.success) {
            showToast('Stage deleted', 'success');
            document.getElementById('stage_' + id).remove();
        }
    });
}

async function saveAccount() {
    const fd = new FormData(document.getElementById('accountForm'));
    fd.append('action', 'update');
    const res = await apiCall('handlers/settings.php', fd);
    if (res.success) {
        showToast(res.message || 'Account updated!', 'success');
        if (res.reload === true || res.reload === 1 || res.reload === '1') {
            setTimeout(function () {
                window.location.reload();
            }, 500);
            return;
        }
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

function toggleAllAddUserPermissions(checked) {
    document.querySelectorAll('.add-user-perm-check, .add-user-page-all').forEach(ch => ch.checked = checked);
}
function toggleAddUserPagePermissions(page, checked) {
    document.querySelectorAll('.add-user-perm-' + page).forEach(ch => ch.checked = checked);
}
document.addEventListener('change', function(e){
    if (e.target && e.target.classList && e.target.classList.contains('add-user-perm-check')) {
        const page = e.target.dataset.page;
        const pageChecks = document.querySelectorAll('.add-user-perm-' + page);
        const pageAll = document.querySelector('.add-user-page-all[data-page="' + page + '"]');
        if (pageAll) pageAll.checked = Array.from(pageChecks).every(ch => ch.checked);
        const all = document.getElementById('addUserAllPermissions');
        if (all) all.checked = Array.from(document.querySelectorAll('.add-user-perm-check')).every(ch => ch.checked);
    }
});
async function addUser() {
    const fd = new FormData(document.getElementById('addUserForm'));
    fd.append('action', 'add_user');
    const res = await apiCall('handlers/settings.php', fd);
    if (res.success) { 
        showToast('User added!', 'success'); 
        setTimeout(() => location.reload(), 600); 
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

async function deleteUser(id, name) {
    confirmAction(`Remove user "${name}"?`, async () => {
        const res = await apiCall('handlers/settings.php', { action: 'delete_user', id: id });
        if (res.success) { 
            showToast('User removed', 'success'); 
            setTimeout(() => location.reload(), 600); 
        } else {
            showToast(res.message || 'Error', 'error');
        }
    });
}

async function addLostReason() {
    const name = document.getElementById('lostReasonInput').value.trim();
    if (!name) { 
        showToast('Please enter a reason', 'warning'); 
        return; 
    }
    const res = await apiCall('handlers/settings.php', { action: 'add_lost_reason', name: name });
    if (res.success) { 
        showToast('Added!', 'success'); 
        closeModal('addLostModal'); 
        setTimeout(() => location.reload(), 600); 
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

async function deleteLostReason(id) {
    confirmAction('Delete this lost reason?', async () => {
        const res = await apiCall('handlers/settings.php', { action: 'delete_lost_reason', id: id });
        if (res.success) { 
            showToast('Deleted', 'success'); 
            const el = document.getElementById('lr_' + id); 
            if (el) el.remove(); 
        } else {
            showToast(res.message || 'Error', 'error');
        }
    });
}

async function changePassword() {
    const f = document.getElementById('pwForm');
    const np = f.querySelector('[name=new_password]').value;
    const cp = f.querySelector('[name=confirm_password]').value;
    if (np !== cp) { 
        showToast('Passwords do not match', 'error'); 
        return; 
    }
    const fd = new FormData(f);
    fd.append('action', 'change_password');
    const res = await apiCall('handlers/settings.php', fd);
    if (res.success) { 
        showToast('Password updated!', 'success'); 
        f.reset(); 
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

function filterCountriesGrid() {
    const input = document.getElementById('countrySearch').value.toLowerCase();
    const items = document.querySelectorAll('.country-item');

    items.forEach(item => {
        const name = item.getAttribute('data-name');
        item.style.display = name.includes(input) ? 'flex' : 'none';
    });
}

async function saveCountries() {

    const countries = [];

    document.querySelectorAll('.country-checkbox:checked').forEach(el => {
        countries.push(el.value);
    });

    const defaultCountry = document.querySelector('input[name="default_country"]:checked')?.value || '';

    const res = await apiCall('handlers/settings.php', {
        action: 'save_countries',
        countries: countries,
        default_country: defaultCountry
    });

    if (res.success) {
        showToast('Countries updated!', 'success');
        setTimeout(() => location.href='index.php?page=settings&tab=countries', 500);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}


async function addAccountEmail() {

    const emailInput = document.getElementById('accountEmailInput');
    const defaultInput = document.getElementById('accountEmailDefault');

    if (!emailInput || !defaultInput) {
        showToast('Email form not found', 'error');
        return;
    }

    const email = emailInput.value.trim();
    const isDefault = defaultInput.checked ? 1 : 0;

    if (!email) {
        showToast('Enter email', 'warning');
        return;
    }

    const res = await apiCall('handlers/settings.php', {
        action: 'add_account_email',
        email: email,
        is_default: isDefault
    });

    if (res.success) {
        showToast('Email added!', 'success');
        closeModal('addEmailModal');
        emailInput.value = '';
        defaultInput.checked = false;
        setTimeout(() => location.reload(), 500);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

async function setDefaultEmail(id) {

    const res = await apiCall('handlers/settings.php', {
        action: 'set_default_account_email',
        id: id
    });

    if (res.success) {
        showToast('Default email updated!', 'success');
        setTimeout(() => location.reload(), 500);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

async function deleteEmail(id) {

    confirmAction('Delete this email?', async () => {

        const res = await apiCall('handlers/settings.php', {
            action: 'delete_account_email',
            id: id
        });

        if (res.success) {
            showToast('Deleted!', 'success');
            const row = document.getElementById('email_' + id);
            if (row) row.remove();
        } else {
            showToast(res.message || 'Error', 'error');
        }
    });
}




function toggleAllExistingPermissions(checked) {
    document.querySelectorAll('.perm-check, .perm-page-all').forEach(ch => ch.checked = checked);
}
function toggleExistingPagePermissions(page, checked) {
    document.querySelectorAll('.perm-page-' + page).forEach(ch => ch.checked = checked);
}

function openUserPermissionsPane(userId, userName) {
    const tabBtn = document.getElementById('usersPermMiniTab');
    if (tabBtn) tabBtn.style.display = 'inline-block';
    document.getElementById('permUserId').value = userId;
    const title = document.getElementById('permUserTitle');
    if (title) title.textContent = 'Manage page access for ' + userName;
    document.querySelectorAll('.perm-check').forEach(ch => ch.checked = false);
    const map = (window.userPermissionMap && window.userPermissionMap[userId]) ? window.userPermissionMap[userId] : {};
    document.querySelectorAll('.perm-check').forEach(ch => {
        if (map[ch.dataset.page]) ch.checked = true;
    });
    const all = document.getElementById('existingAllPermissions');
    if (all) all.checked = Array.from(document.querySelectorAll('.perm-check')).every(ch => ch.checked);
    openUsersSubtab('usersPermissionsPane', tabBtn);
}

async function saveUserPermissions() {
    const userId = document.getElementById('permUserId')?.value;
    if (!userId) { showToast('Select user first', 'warning'); return; }
    const permissions = [];
    document.querySelectorAll('.perm-check:checked').forEach(ch => {
        permissions.push({ page: ch.dataset.page, action: ch.dataset.action });
    });
    const res = await apiCall('handlers/settings.php', {
        action: 'save_user_permissions',
        user_id: userId,
        permissions: permissions
    });
    if (res.success) {
        const newMap = {};
        permissions.forEach(p => { newMap[p.page] = true; });
        window.userPermissionMap = window.userPermissionMap || {};
        window.userPermissionMap[userId] = newMap;
        showToast('Page access saved!', 'success');
    } else showToast(res.message || 'Error', 'error');
}

</script>
