import puppeteer from 'puppeteer-core';
import { mkdirSync } from 'fs';

const base = 'https://demo77.elbaset.com/controllers';
const out = '/home/moonui/public_html/presentation/albassit/screens';
mkdirSync(out, { recursive: true });

const browser = await puppeteer.launch({
    headless: 'new',
    args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
    executablePath: '/root/.cache/puppeteer/chrome/linux-146.0.7680.153/chrome-linux64/chrome'
});

const page = await browser.newPage();
await page.setViewport({ width: 1366, height: 900 });

// Login
console.log('Logging in...');
await page.goto(`${base}/login.php`, { waitUntil: 'networkidle2', timeout: 30000 });
await new Promise(r => setTimeout(r, 3000));

// Debug: see all selects and inputs
const formInfo = await page.evaluate(() => {
    const selects = Array.from(document.querySelectorAll('select')).map(s => ({
        name: s.name, id: s.id, options: Array.from(s.options).map(o => o.value).slice(0, 5)
    }));
    const inputs = Array.from(document.querySelectorAll('input')).map(i => ({
        name: i.name, id: i.id, type: i.type
    }));
    return { selects, inputs };
});
console.log('Form:', JSON.stringify(formInfo, null, 2));

await page.type('#username', 'admin');
await page.type('#password', 'manager');

// Set database via hidden/text input
await page.evaluate(() => {
    const dbInput = document.querySelector('input[name="db"]');
    if (dbInput) {
        dbInput.value = 'demo77_erp3';
        console.log('DB set to demo77_erp3');
    }
});
console.log('DB input set to demo77_erp3');

await page.evaluate(() => { document.querySelector('form').submit(); });
await page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 30000 }).catch(() => {});
await new Promise(r => setTimeout(r, 4000));
console.log('After login:', page.url());

// Full page screenshot first to understand layout
await page.screenshot({ path: `${out}/demo77-dashboard-full.png`, fullPage: true });
const height = await page.evaluate(() => document.body.scrollHeight);
console.log('Page height:', height);

// Take content-area screenshot
async function takeShot(name, url) {
    try {
        await page.goto(`${base}/${url}`, { waitUntil: 'networkidle2', timeout: 20000 });
        await new Promise(r => setTimeout(r, 3000));

        const h = await page.evaluate(() => document.body.scrollHeight);
        // Try scrolling to content (adaptive)
        const scrollTo = Math.min(500, h - 700);
        if (scrollTo > 0) {
            await page.evaluate((y) => window.scrollTo(0, y), scrollTo);
            await new Promise(r => setTimeout(r, 500));
        }

        await page.screenshot({ path: `${out}/${name}.png`, fullPage: false });
        console.log(`✓ ${name} (h=${h})`);
    } catch(e) {
        console.log(`✗ ${name}: ${e.message.substring(0, 80)}`);
    }
}

// Manufacturing (case-sensitive!)
await takeShot('production-order', 'productionOrderController.php?do=show');
await takeShot('production-execution', 'productionExecutionController.php?do=show');
await takeShot('production-rate', 'productionRateController.php?do=show');
await takeShot('production-equation', 'productionEquationController.php?do=show');
await takeShot('production-out', 'productionOutController.php?do=show');
await takeShot('task-order', 'taskOrderController.php?do=show');

// Employees
await takeShot('employees', 'employeeController.php?do=show');
await takeShot('employee-add', 'employeeController.php');
await takeShot('attendance', 'EmployeeAttendanceController.php?do=show');
await takeShot('salary-report', 'salaryReportController.php?do=show');
await takeShot('absent-report', 'absentReportController.php?do=show');

// Accounts
await takeShot('accounts-tree-demo', 'accountstree.php');
await takeShot('checks-demo', 'checkReportController.php?do=show');

await browser.close();
console.log('Done!');
