var webPage = require('webpage');
var page = webPage.create();
var system = require('system');

page.settings.encoding = "utf8";
phantom.outputEncoding = "utf8";

var currentYear = new Date().getFullYear();

// Metoda za dohvaćanje početnog datuma
function getStartDate(month) {
    return '01-' + (month < 10 ? '0' + month : month) + '-' + currentYear;
}

// Metoda za dohvaćanje krajnjeg datuma
function getEndDate(month) {
    var lastDay = new Date(currentYear, month, 0).getDate();
    return lastDay + '-' + (month < 10 ? '0' + month : month) + '-' + currentYear;
}

// Get month, base URL, project name, and recipient argument from command line
var month = parseInt(system.args[1], 10) || 1; // Default to January
var baseUrl = system.args[2] || 'http://desktop-t3pjdpe/ugo';
var projectName = system.args[3] || 'nepoznato';
var recipient = system.args[4] || 'both'; // Accepts "knjigovodstvo", "vlasnik", or "both"

// Set start and end dates based on the month
var startDate, endDate;

switch (month) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    case 7:
    case 8:
    case 9:
    case 10:
    case 11:
    case 12:
        startDate = getStartDate(month);
        endDate = getEndDate(month);
        break;
    default:
        console.log("Invalid month, defaulting to January.");
        startDate = getStartDate(1);
        endDate = getEndDate(1);
        break;
}

console.log("Set start date: " + startDate + ", end date: " + endDate);
/*
// Get month, base URL, project name, and recipient argument from command line
var month = parseInt(system.args[1], 10) || 1; // Default to January
var baseUrl = system.args[2] || 'http://desktop-t3pjdpe/ugo';
var projectName = system.args[3] || 'nepoznato';
var recipient = system.args[4] || 'both'; // Accepts "knjigovodstvo", "vlasnik", or "both"

// Set start and end dates based on the month
var startDate, endDate;

switch (month) {
    case 1: startDate = '01-01-2024'; endDate = '31-01-2024'; break;
    case 2: startDate = '01-02-2024'; endDate = '29-02-2024'; break;
    case 3: startDate = '01-03-2024'; endDate = '31-03-2024'; break;
    case 4: startDate = '01-04-2024'; endDate = '30-04-2024'; break;
    case 5: startDate = '01-05-2024'; endDate = '31-05-2024'; break;
    case 6: startDate = '01-06-2024'; endDate = '30-06-2024'; break;
    case 7: startDate = '01-07-2024'; endDate = '31-07-2024'; break;
    case 8: startDate = '01-08-2024'; endDate = '31-08-2024'; break;
    case 9: startDate = '01-09-2024'; endDate = '30-09-2024'; break;
    case 10: startDate = '01-10-2024'; endDate = '31-10-2024'; break;
    case 11: startDate = '01-11-2024'; endDate = '30-11-2024'; break;
    case 12: startDate = '01-12-2024'; endDate = '31-12-2024'; break;
    default:
        console.log("Invalid month, defaulting to January.");
        startDate = '01-01-2024'; endDate = '31-01-2024'; break;
}

console.log("Set start date: " + startDate + ", end date: " + endDate);

*/

var loginUrl = baseUrl + '/users/login';
var internetCheckUrl = baseUrl + '/kontrola_interneta';
var reportUrls = projectName === 'ugo' ? [
    { url: baseUrl + '/reports/pregled_prodaje_po_normativu', type: 2 },
    { url: baseUrl + '/reports/pregled_prodaje_po_nacinu_placanja', type: 23 },
    { url: baseUrl + '/reports/rekapitulacija_prometa', type: 4 },
    { url: baseUrl + '/reports/porez_na_potrosnju', type: 6 },
    { url: baseUrl + '/reports/rekapitulacija_po_danima', type: 19 },
    { url: baseUrl + '/reports/pregled_napojnice', type: 26 }
] : [
    { url: baseUrl + '/reports/prodani_artikli', type: 9 },
    { url: baseUrl + '/reports/rekapitulacija_prometa', type: 11 },
    { url: baseUrl + '/reports/rekapitulacija_po_danima', type: 20 },
    { url: baseUrl + '/reports/pregled_napojnice', type: 26 }
];

// Helper function to check if an element exists
function elementExists(selector) {
    return page.evaluate(function (selector) {
        return document.querySelector(selector) !== null;
    }, selector);
}

function loginAndGenerateReports() {
    page.open(loginUrl, function (status) {
        if (status !== 'success') {
            console.log('Error opening login page.');
            phantom.exit();
        } else {
            console.log('Login page opened, logging in...');
            page.evaluate(function () {
                document.querySelector('input[name="data[User][username]"]').value = 'Kasapro';
                document.querySelector('input[name="data[User][password]"]').value = '6664999';
                document.querySelector('input[type="submit"]').click();
            });
            window.setTimeout(checkInternetConnection, 5000);
        }
    });
}

function checkInternetConnection() {
    page.open(internetCheckUrl, function (status) {
        if (status !== 'success') {
            console.log('Error checking internet connection.');
            phantom.exit();
        } else {
            var isInternetOk = page.evaluate(function () {
                var element = document.querySelector("h3[style='color:blue']");
                return element && element.innerText === "Internet veza je ispravna!";
            });
            if (isInternetOk) {
                console.log("Internet connection is OK. Starting report generation.");
                generateReport(0);
            } else {
                console.log("Internet connection is not OK.");
                phantom.exit();
            }
        }
    });
}

function generateReport(reportIndex) {
    if (reportIndex >= reportUrls.length) {
        console.log("Svi izveštaji su generirani i poslani.");
        phantom.exit();
        return;
    }

    var reportUrl = reportUrls[reportIndex].url;
    console.log("Opening report: " + reportUrl);

    page.open(reportUrl, function (status) {
        if (status !== 'success') {
            console.log('Error opening report: ' + reportUrl);
            phantom.exit();
        } else {
            if (elementExists('#FilterDateStart') && elementExists('#FilterDateEnd')) {
                page.evaluate(function (startDate, endDate) {
                    document.querySelector('#FilterDateStart').value = startDate;
                    document.querySelector('#FilterDateEnd').value = endDate;
                }, startDate, endDate);

                window.setTimeout(function () {
                    if (elementExists('div.submit input[type="submit"][value="Izradi"]')) {
                        page.evaluate(function () {
                            document.querySelector('div.submit input[type="submit"][value="Izradi"]').click();
                        });
                        window.setTimeout(function () {
                            if (recipient === "vlasnik" || recipient === "both") {
                                sendEmailForRecipient("Vlasnik", "mailer-primatelj-1", reportIndex);
                            } else if (recipient === "knjigovodstvo") {
                                sendEmailForRecipient("Knjigovodstvo", "mailer-primatelj-2", reportIndex);
                            }
                        }, 5000);
                    } else {
                        console.log("Report generation button not found.");
                        phantom.exit();
                    }
                }, 5000);
            } else {
                console.log("Date input fields not found.");
                phantom.exit();
            }
        }
    });
}

function sendEmailForRecipient(recipientName, recipientId, reportIndex) {
    console.log("Preparing email for " + recipientName + "...");

    var checkEmailLink = setInterval(function () {
        if (elementExists('a[onclick="email_box_open(1); return false;"]')) {
            clearInterval(checkEmailLink);
            page.evaluate(function () {
                document.querySelector('a[onclick="email_box_open(1); return false;"]').click();
            });

            var checkEmailFields = setInterval(function () {
                if (elementExists('#' + recipientId) && elementExists("input[type='submit'][value='Pošalji e-mail']")) {
                    clearInterval(checkEmailFields);
                    page.evaluate(function (recipientId) {
                        document.querySelector('#' + recipientId).click();
                        document.querySelector("input[type='submit'][value='Pošalji e-mail']").click();
                    }, recipientId);

                    var checkConfirmation = setInterval(function () {
                        if (elementExists('#send-email-box-2')) {
                            clearInterval(checkConfirmation);
                            page.evaluate(function () {
                                document.querySelector('a[onclick="mailer_close_layer(); return false;"]').click();
                            });

                            if (recipientName === "Vlasnik" && recipient === "both") {
                                sendEmailForRecipient("Knjigovodstvo", "mailer-primatelj-2", reportIndex);
                            } else {
                                generateReport(reportIndex + 1);
                            }
                        }
                    }, 100);
                }
            }, 100);
        }
    }, 100);
}

loginAndGenerateReports();
