// Masters Management JavaScript

$(document).ready(function() {
    // Check for hash in URL first (from redirects)
    let activeTab = 'units';
    
    if (window.location.hash) {
        const hashTab = window.location.hash.replace('#tab-', '');
        if (hashTab && $(`.tab-btn[data-tab="${hashTab}"]`).length > 0) {
            activeTab = hashTab;
        }
    } else {
        // Fall back to localStorage or default
        activeTab = localStorage.getItem('mastersActiveTab') || 'units';
    }
    
    showTab(activeTab);
    
    // Tab switching functionality
    $('.tab-btn').click(function() {
        const tabName = $(this).data('tab');
        showTab(tabName);
        // Save current tab to localStorage
        localStorage.setItem('mastersActiveTab', tabName);
        // Update URL hash
        window.location.hash = 'tab-' + tabName;
    });
});

function showTab(tabName) {
    // Update active tab button
    $('.tab-btn').removeClass('active');
    $(`.tab-btn[data-tab="${tabName}"]`).addClass('active');
    
    // Update active tab content
    $('.tab-content').removeClass('active');
    $('#' + tabName).addClass('active');
}

// Modal functions
function openModal(masterType) {
    const modalTitle = document.getElementById('modalTitle');
    const modalBody = document.getElementById('modalBody');
    const masterForm = document.getElementById('masterForm');
    
    // Clear form
    masterForm.reset();
    
    // Save current tab to localStorage before opening modal
    const currentTab = $('.tab-btn.active').data('tab');
    localStorage.setItem('mastersActiveTab', currentTab);
    
    // Set form action
    const actionInput = '<input type="hidden" name="action" value="create">';
    const masterTypeInput = '<input type="hidden" name="masterType" value="' + masterType + '">';
    const activeTabInput = '<input type="hidden" name="activeTab" value="' + currentTab + '">';
    
    let formHTML = actionInput + masterTypeInput + activeTabInput;
    let titleText = '';
    
    switch(masterType) {
        case 'unit':
            titleText = 'Add Unit';
            formHTML += `
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="unitName">Unit Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="unitName" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="unitSymbol">Unit Symbol <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="unitSymbol" required>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea class="form-control" name="description" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label for="status">Status</label>
                    <select class="form-control" name="status">
                        <option value="Active">Active</option>
                        <option value="Inactive">Inactive</option>
                    </select>
                </div>
            `;
            break;
            
        case 'category':
            titleText = 'Add Category';
            formHTML += `
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="categoryName">Category Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="categoryName" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="categoryCode">Category Code</label>
                            <input type="text" class="form-control" name="categoryCode">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea class="form-control" name="description" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label for="status">Status</label>
                    <select class="form-control" name="status">
                        <option value="Active">Active</option>
                        <option value="Inactive">Inactive</option>
                    </select>
                </div>
            `;
            break;
            
        case 'brand':
            titleText = 'Add Brand';
            formHTML += `
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="brandName">Brand Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="brandName" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="brandCode">Brand Code</label>
                            <input type="text" class="form-control" name="brandCode">
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="manufacturer">Manufacturer</label>
                            <input type="text" class="form-control" name="manufacturer">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="contactInfo">Contact Info</label>
                            <input type="text" class="form-control" name="contactInfo">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea class="form-control" name="description" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label for="status">Status</label>
                    <select class="form-control" name="status">
                        <option value="Active">Active</option>
                        <option value="Inactive">Inactive</option>
                    </select>
                </div>
            `;
            break;
            
        case 'supplier':
            titleText = 'Add Supplier';
            formHTML += `
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="supplierName">Supplier Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="supplierName" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="supplierCode">Supplier Code</label>
                            <input type="text" class="form-control" name="supplierCode">
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="contactPerson">Contact Person</label>
                            <input type="text" class="form-control" name="contactPerson">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="phoneNumber">Phone Number</label>
                            <input type="text" class="form-control" name="phoneNumber">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="email" class="form-control" name="email">
                </div>
                <div class="form-group">
                    <label for="address">Address</label>
                    <textarea class="form-control" name="address" rows="2"></textarea>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="gstNumber">GST Number</label>
                            <input type="text" class="form-control" name="gstNumber">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="panNumber">PAN Number</label>
                            <input type="text" class="form-control" name="panNumber">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="status">Status</label>
                    <select class="form-control" name="status">
                        <option value="Active">Active</option>
                        <option value="Inactive">Inactive</option>
                    </select>
                </div>
            `;
            break;
            
        case 'tax':
            titleText = 'Add Tax Type';
            formHTML += `
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="taxName">Tax Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="taxName" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="taxType">Tax Type <span class="text-danger">*</span></label>
                            <select class="form-control" name="taxType" required>
                                <option value="">Select Tax Type</option>
                                <option value="CGST">CGST</option>
                                <option value="SGST">SGST</option>
                                <option value="IGST">IGST</option>
                                <option value="CESS">CESS</option>
                                <option value="VAT">VAT</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="taxRate">Tax Rate (%) <span class="text-danger">*</span></label>
                    <input type="number" step="0.01" class="form-control" name="taxRate" required>
                </div>
                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea class="form-control" name="description" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label for="status">Status</label>
                    <select class="form-control" name="status">
                        <option value="Active">Active</option>
                        <option value="Inactive">Inactive</option>
                    </select>
                </div>
            `;
            break;
            
        case 'location':
            titleText = 'Add Location';
            formHTML += `
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="locationName">Location Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="locationName" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="locationCode">Location Code</label>
                            <input type="text" class="form-control" name="locationCode">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="locationType">Location Type</label>
                    <select class="form-control" name="locationType">
                        <option value="Warehouse">Warehouse</option>
                        <option value="Store">Store</option>
                        <option value="Site">Site</option>
                        <option value="Office">Office</option>
                        <option value="Other">Other</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="address">Address</label>
                    <textarea class="form-control" name="address" rows="2"></textarea>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="contactPerson">Contact Person</label>
                            <input type="text" class="form-control" name="contactPerson">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="phoneNumber">Phone Number</label>
                            <input type="text" class="form-control" name="phoneNumber">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="status">Status</label>
                    <select class="form-control" name="status">
                        <option value="Active">Active</option>
                        <option value="Inactive">Inactive</option>
                    </select>
                </div>
            `;
            break;
            
        case 'rack':
            titleText = 'Add Rack';
            // Get locations for dropdown
            formHTML += `
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="rackName">Rack Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="rackName" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="rackCode">Rack Code</label>
                            <input type="text" class="form-control" name="rackCode">
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="locationID">Location</label>
                            <select class="form-control" name="locationID" id="locationSelect">
                                <option value="">Select Location</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="capacity">Capacity</label>
                            <input type="number" step="0.01" class="form-control" name="capacity">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea class="form-control" name="description" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label for="status">Status</label>
                    <select class="form-control" name="status">
                        <option value="Active">Active</option>
                        <option value="Inactive">Inactive</option>
                    </select>
                </div>
            `;
            break;
            
        case 'type':
            titleText = 'Add Type';
            formHTML += `
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="typeName">Type Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="typeName" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="typeCode">Type Code</label>
                            <input type="text" class="form-control" name="typeCode">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="typeCategory">Type Category</label>
                    <select class="form-control" name="typeCategory">
                        <option value="Material">Material</option>
                        <option value="Product">Product</option>
                        <option value="Service">Service</option>
                        <option value="Asset">Asset</option>
                        <option value="Other">Other</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea class="form-control" name="description" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label for="status">Status</label>
                    <select class="form-control" name="status">
                        <option value="Active">Active</option>
                        <option value="Inactive">Inactive</option>
                    </select>
                </div>
            `;
            break;
    }
    
    modalTitle.textContent = titleText;
    modalBody.innerHTML = formHTML;
    
    // Load locations for rack form
    if (masterType === 'rack') {
        loadLocations();
    }
    
    $('#masterModal').modal('show');
}

async function editItem(masterType, id) {
    console.log('Editing item:', masterType, id); // Debug log
    
    try {
        const response = await fetch(`api/get-${masterType}.php?id=${id}`);
        console.log('Response status:', response.status); // Debug log
        const data = await response.json();
        console.log('API Response:', data); // Debug log
        
        if (data.success) {
            openEditModal(masterType, data.data);
        } else {
            await MsgBox.alert('Error loading data: ' + (data.message || 'Unknown error'));
        }
    } catch (error) {
        console.error('Error:', error);
        await MsgBox.alert('Error loading data: ' + error.message);
    }
}

function openEditModal(masterType, data) {
    openModal(masterType);
    
    // Update modal title
    document.getElementById('modalTitle').textContent = `Edit ${masterType.charAt(0).toUpperCase() + masterType.slice(1)}`;
    
    // Update form action
    const actionInput = document.querySelector('input[name="action"]');
    actionInput.value = 'update';
    
    // Add ID field
    const masterTypeInput = document.querySelector('input[name="masterType"]');
    masterTypeInput.insertAdjacentHTML('afterend', `<input type="hidden" name="id" value="${data.ID}">`);
    
    // Ensure activeTab is set correctly for edit
    const activeTabInput = document.querySelector('input[name="activeTab"]');
    if (activeTabInput) {
        const currentTab = $('.tab-btn.active').data('tab');
        activeTabInput.value = currentTab;
    }
    
    // Populate form fields based on master type
    populateFormFields(masterType, data);
}

async function deleteItem(masterType, id, name) {
    const confirmation = await MsgBox.confirm(`Are you sure you want to delete this ${masterType}: "${name}"?`);
    if (confirmation) {
        const currentTab = $('.tab-btn.active').data('tab');
        window.location.href = `masters-management.php?delete=${id}&type=${masterType}&tab=${currentTab}`;
    }
}

function loadLocations() {
    fetch('api/get-locations.php')
        .then(response => response.json())
        .then(data => {
            console.log('Locations loaded:', data); // Debug log
            if (data.success) {
                const select = document.getElementById('locationSelect');
                if (select) {
                    // Clear existing options (except the first one)
                    select.innerHTML = '<option value="">Select Location</option>';
                    
                    data.locations.forEach(location => {
                        const option = document.createElement('option');
                        option.value = location.ID;
                        option.textContent = location.LocationName;
                        select.appendChild(option);
                    });
                }
            } else {
                console.error('Failed to load locations:', data.message);
            }
        })
        .catch(error => {
            console.error('Error loading locations:', error);
        });
}

function populateFormFields(masterType, data) {
    switch(masterType) {
        case 'unit':
            setFieldValue('unitName', data.UnitName);
            setFieldValue('unitSymbol', data.UnitSymbol);
            setFieldValue('description', data.Description);
            setFieldValue('status', data.Status);
            break;
            
        case 'category':
            setFieldValue('categoryName', data.CategoryName);
            setFieldValue('categoryCode', data.CategoryCode);
            setFieldValue('description', data.Description);
            setFieldValue('status', data.Status);
            break;
            
        case 'brand':
            setFieldValue('brandName', data.BrandName);
            setFieldValue('brandCode', data.BrandCode);
            setFieldValue('manufacturer', data.Manufacturer);
            setFieldValue('contactInfo', data.ContactInfo);
            setFieldValue('description', data.Description);
            setFieldValue('status', data.Status);
            break;
            
        case 'supplier':
            setFieldValue('supplierName', data.SupplierName);
            setFieldValue('supplierCode', data.SupplierCode);
            setFieldValue('contactPerson', data.ContactPerson);
            setFieldValue('phoneNumber', data.PhoneNumber);
            setFieldValue('email', data.Email);
            setFieldValue('address', data.Address);
            setFieldValue('gstNumber', data.GSTNumber);
            setFieldValue('panNumber', data.PanNumber);
            setFieldValue('status', data.Status);
            break;
            
        case 'tax':
            setFieldValue('taxName', data.TaxName);
            setFieldValue('taxType', data.TaxType);
            setFieldValue('taxRate', data.TaxRate);
            setFieldValue('description', data.Description);
            setFieldValue('status', data.Status);
            break;
            
        case 'location':
            setFieldValue('locationName', data.LocationName);
            setFieldValue('locationCode', data.LocationCode);
            setFieldValue('locationType', data.LocationType);
            setFieldValue('address', data.Address);
            setFieldValue('contactPerson', data.ContactPerson);
            setFieldValue('phoneNumber', data.PhoneNumber);
            setFieldValue('status', data.Status);
            break;
            
        case 'rack':
            setFieldValue('rackName', data.RackName);
            setFieldValue('rackCode', data.RackCode);
            setFieldValue('locationID', data.LocationID);
            setFieldValue('capacity', data.Capacity);
            setFieldValue('description', data.Description);
            setFieldValue('status', data.Status);
            break;
            
        case 'type':
            setFieldValue('typeName', data.TypeName);
            setFieldValue('typeCode', data.TypeCode);
            setFieldValue('typeCategory', data.TypeCategory);
            setFieldValue('description', data.Description);
            setFieldValue('status', data.Status);
            break;
    }
}

function setFieldValue(fieldName, value) {
    const field = document.querySelector(`[name="${fieldName}"]`);
    if (field) {
        field.value = value || '';
    }
}