const mix = require('laravel-mix');
const glob = require('glob');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

// Configure Mix options
mix.options({
    processCssUrls: false,
    terser: {
        terserOptions: {
            compress: {
                drop_console: true,
                drop_debugger: true
            }
        }
    }
});

// Helper function to get files matching pattern
function getFiles(pattern) {
    try {
        return glob.sync(pattern, { cwd: __dirname });
    } catch (e) {
        console.warn(`Pattern not found: ${pattern}`);
        return [];
    }
}

// Vendor JavaScript - CRITICAL FIX: Exclude jQuery to prevent conflicts
const vendorFiles = [
    // EXCLUDE jQuery and jQuery UI (loaded from CDN)
    // 'resources/assets/vendor/libs/jquery.min.js',
    // 'resources/assets/vendor/jqueryui/jqueryui.min.js',

    // Include jQuery plugins that depend on jQuery UI
    'resources/assets/vendor/bootstrap-switch/static/js/bootstrapSwitch.js',
    'resources/assets/vendor/daterangepicker/daterangepicker.js',
    'resources/assets/vendor/libs/jquery.nanoscroller.min.js',
    'resources/assets/vendor/select2/select2.js',
    'resources/assets/vendor/typeahead.js/typeahead.bundle.js',

    // Other jQuery plugins
    'resources/assets/vendor/tabdrop/js/bootstrap-tabdrop.js',
    'resources/assets/vendor/fullcalendar/fullcalendar.min.js',

    // Core libraries
    'resources/assets/vendor/libs/underscore.min.js',
    'resources/assets/vendor/bootstrap-sass/assets/javascripts/bootstrap.min.js',

    // Angular and UI
    'resources/assets/vendor/angular/angular.min.js',
    'resources/assets/vendor/angular-resource/angular-resource.min.js',
    'resources/assets/vendor/angular-route/angular-route.min.js',
    'resources/assets/vendor/angular-sanitize/angular-sanitize.min.js',
    'resources/assets/vendor/angular-bootstrap/ui-bootstrap.min.js',
    'resources/assets/vendor/angular-bootstrap/ui-bootstrap-tpls.min.js',
    'resources/assets/vendor/messenger/js/messenger.min.js',
    'resources/assets/vendor/messenger/js/messenger-theme-future.js',

    // Other Angular plugins
    'resources/assets/vendor/daterangepicker/ng-daterangepicker.js',
    'resources/assets/vendor/angular-ui-grid/ui-grid.min.js',
    'resources/assets/vendor/chartjs/chart.min.js',
    'resources/assets/vendor/chartjs/angular-chart.js',
    'resources/assets/vendor/sweetalert/sweetalert.min.js',
    'resources/assets/vendor/sweetalert/ng-sweetalert.js',
    'resources/assets/vendor/angular-ui-select/dist/select.min.js',

    // CRITICAL: Missing Angular modules that broke dashboard
    'resources/assets/vendor/angular-xeditable/js/xeditable.min.js',
    'resources/assets/vendor/gantt/angular-gantt.min.js',
    'resources/assets/vendor/textcomplete/ng-textcomplete.js',
    'resources/assets/vendor/select2/ui-select2.js',
    'resources/assets/vendor/mentio/mentio.min.js',
    'resources/assets/vendor/elastic/elastic.js'
];

// Add additional vendor files that exist
const additionalVendorPatterns = [
    'resources/assets/vendor/libs/*.js',
    'resources/assets/vendor/summernote/*.js',
    'resources/assets/vendor/blueimp/*.js',
    'resources/assets/vendor/ui-utils/*.js',
    'resources/assets/vendor/desktop-notifications/*.js'
];

// Collect additional vendor files
additionalVendorPatterns.forEach(pattern => {
    const files = getFiles(pattern);
    vendorFiles.push(...files);
});

// Application JavaScript - Dynamic collection with PROPER MODULE LOADING ORDER
const appFiles = [
    'resources/assets/js/archDB.js',
    'resources/assets/js/directives.js',
    'resources/assets/js/services.js'
];

// Add all module files dynamically with FIXED LOADING ORDER
const modulePatterns = [
    'resources/assets/js/menu/**/*.js',
    'resources/assets/js/bookings/**/*.js',
    'resources/assets/js/clients/**/*.js',
    'resources/assets/js/dashboard/**/*.js',
    'resources/assets/js/dashboard_v2/**/*.js',
    'resources/assets/js/sales/**/*.js',
    'resources/assets/js/invoices/**/*.js',
    'resources/assets/js/notifications/**/*.js',
    'resources/assets/js/stats/**/*.js',
    'resources/assets/js/stock/**/*.js',
    'resources/assets/js/accounts/**/*.js',
    'resources/assets/js/admin/**/*.js',
    'resources/assets/js/asterisk/**/*.js',
    'resources/assets/js/workflow/**/*.js',
    'resources/assets/js/hr/**/*.js',
    'resources/assets/js/chat/**/*.js',
    'resources/assets/js/reminders/**/*.js'
];

// Collect app files with CRITICAL LOADING ORDER FIX
modulePatterns.forEach(pattern => {
    const files = getFiles(pattern);

    // CRITICAL FIX: Proper sorting for Angular module dependencies
    files.sort((a, b) => {
        // 1. module.js files MUST come first
        if (a.includes('module.js') && !b.includes('module.js')) return -1;
        if (!a.includes('module.js') && b.includes('module.js')) return 1;

        // 2. If both are module.js files, sort alphabetically  
        if (a.includes('module.js') && b.includes('module.js')) {
            return a.localeCompare(b);
        }

        // 3. For non-module files, controllers come before directives
        if (a.includes('/controllers/') && b.includes('/directives/')) return -1;
        if (a.includes('/directives/') && b.includes('/controllers/')) return 1;

        // 4. Default alphabetical sorting
        return a.localeCompare(b);
    });

    appFiles.push(...files);
});

console.log(`📦 Found ${vendorFiles.length} vendor files`);
console.log(`📦 Found ${appFiles.length} app files`);

// Build vendor JavaScript
mix.scripts(vendorFiles, 'public/js/vendor.js');

// Build application JavaScript 
mix.scripts(appFiles, 'public/js/app.js');

// Vendor CSS - Third-party stylesheets
const vendorCssFiles = [
    'resources/assets/vendor/jqueryui/jqueryui.min.css',
    'resources/assets/vendor/messenger/css/messenger.css',
    'resources/assets/vendor/messenger/css/messenger-theme-future.css',
    'resources/assets/vendor/bootstrap-switch/static/stylesheets/bootstrapSwitch.css',
    'resources/assets/vendor/tabdrop/css/tabdrop.css',
    'resources/assets/vendor/fullcalendar/fullcalendar.css',
    'resources/assets/vendor/daterangepicker/daterangepicker-bs3.css',
    'resources/assets/vendor/angular-ui-grid/ui-grid.css',
    'resources/assets/vendor/chartjs/angular-chart.css',
    'resources/assets/vendor/sweetalert/sweetalert.css',
    'resources/assets/vendor/angular-ui-select/dist/select.min.css',
    'resources/assets/vendor/font-awesome/css/font-awesome.css'
];

// Add additional CSS files
const additionalCssPatterns = [
    'resources/assets/vendor/summernote/*.css',
    'resources/assets/vendor/angular-xeditable/css/*.css',
    'resources/assets/vendor/gantt/*.css',
    'resources/assets/vendor/select2/select2.css',
    'resources/assets/vendor/select2/select2-bootstrap.css'
];

additionalCssPatterns.forEach(pattern => {
    const files = getFiles(pattern);
    vendorCssFiles.push(...files);
});

mix.styles(vendorCssFiles, 'public/css/all.css');

// SCSS Compilation - RE-ENABLED with compass-mixins support
console.log('🎨 SCSS compilation enabled with compass-mixins support');
mix.sass('resources/assets/scss/main.scss', 'public/css')
    .sass('resources/assets/scss/print_sheets.scss', 'public/css')
    .sass('resources/assets/scss/custom_style.scss', 'public/css');

// Individual JavaScript files
mix.copy('resources/assets/vendor/typeahead.js/typeahead.min.js', 'public/js/typeahead.min.js');

// Enable versioning in production
if (mix.inProduction()) {
    mix.version();
    console.log('🚀 Production build with versioning enabled');
} else {
    mix.sourceMaps();
    console.log('🔧 Development build with source maps');
} 