// Copyright (c) 2026, Jey Soft and contributors
// For license information, please see license.txt

function get_quarter_dates(year, quarter) {
	const quarters = {
		"1": { from: year + "-01-01", to: year + "-03-31" },
		"2": { from: year + "-04-01", to: year + "-06-30" },
		"3": { from: year + "-07-01", to: year + "-09-30" },
		"4": { from: year + "-10-01", to: year + "-12-31" }
	};
	return quarters[String(quarter)];
}

frappe.query_reports["Monthly Present Report"] = {
	"filters": [
		{
			fieldname: "company",
			label: __("Şirkət"),
			fieldtype: "Link",
			options: "Company",
			reqd: 1,
			default: frappe.defaults.get_user_default("Company")
		},
		{
			fieldname: "year",
			label: __("İl"),
			fieldtype: "Int",
			reqd: 1,
			default: new Date().getFullYear(),
			on_change: function() {
				const year = frappe.query_report.get_filter_value("year");
				const quarter = frappe.query_report.get_filter_value("quarter");
				if (year && quarter) {
					const dates = get_quarter_dates(year, quarter);
					frappe.query_report.set_filter_value("from_date", dates.from);
					frappe.query_report.set_filter_value("to_date", dates.to);
				}
			}
		},
		{
			fieldname: "quarter",
			label: __("Rüb"),
			fieldtype: "Select",
			options: "1\n2\n3\n4",
			reqd: 1,
			default: String(Math.ceil((new Date().getMonth() + 1) / 3)),
			on_change: function() {
				const year = frappe.query_report.get_filter_value("year");
				const quarter = frappe.query_report.get_filter_value("quarter");
				if (year && quarter) {
					const dates = get_quarter_dates(year, quarter);
					frappe.query_report.set_filter_value("from_date", dates.from);
					frappe.query_report.set_filter_value("to_date", dates.to);
				}
			}
		},
		{
			fieldname: "from_date",
			label: __("Tarixdən"),
			fieldtype: "Date",
			hidden: 1
		},
		{
			fieldname: "to_date",
			label: __("Tarixə qədər"),
			fieldtype: "Date",
			hidden: 1
		}
	],

	"onload": function() {
		const year = frappe.query_report.get_filter_value("year");
		const quarter = frappe.query_report.get_filter_value("quarter");
		if (year && quarter) {
			const dates = get_quarter_dates(year, quarter);
			frappe.query_report.set_filter_value("from_date", dates.from);
			frappe.query_report.set_filter_value("to_date", dates.to);
		}
	}
};
