<script>
// Tab switching function with URL parameter
function switchTab(tabName) {
    console.log(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
    document.getElementById('tab-' + tabName).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';
    document.getElementById('stage_type_span_' + id).style.display = 'none';
    document.getElementById('stage_type_' + id).style.display = 'block';
    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 === '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_type_' + id).style.display = 'none';
        document.getElementById('stage_edit_btn_' + id).style.display = 'inline-block';
        document.getElementById('stage_save_btn_' + id).style.display = 'none';
    } 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('Account updated!', 'success');
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

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'); 
        closeModal('addUserModal'); 
        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');
    } else {
        showToast(res.message || 'Error', 'error');
    }
}




async function addAccountEmail() {

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

    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');

        }

    });
}


</script>
