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

function quarter_dates(year, quarter) {
	const q = parseInt(quarter, 10);
	const y = parseInt(year, 10);
	const start_month = (q - 1) * 3;
	const end_month = start_month + 2;
	const start = new Date(y, start_month, 1);
	const end = new Date(y, end_month + 1, 0);
	return {
		from_date: frappe.datetime.obj_to_str(start).slice(0, 10),
		to_date: frappe.datetime.obj_to_str(end).slice(0, 10),
	};
}

function sync_quarter_dates(report) {
	const year = report.get_filter_value("year");
	const quarter = report.get_filter_value("quarter");
	if (!year || !quarter) return;
	const { from_date, to_date } = quarter_dates(year, quarter);
	report.set_filter_value("from_date", from_date);
	report.set_filter_value("to_date", to_date);
}

const now = new Date();
const current_quarter = String(Math.ceil((now.getMonth() + 1) / 3));
const default_dates = quarter_dates(now.getFullYear(), current_quarter);

frappe.query_reports["Employee Payroll Register"] = {
	filters: [
		{
			fieldname: "year",
			label: __("Year"),
			fieldtype: "Int",
			default: now.getFullYear(),
			reqd: 1,
			width: "80px",
			on_change: function () {
				sync_quarter_dates(frappe.query_report);
				frappe.query_report.refresh();
			},
		},
		{
			fieldname: "quarter",
			label: __("Quarter"),
			fieldtype: "Select",
			options: [
				{ value: "1", label: __("Q1 (Jan – Mar)") },
				{ value: "2", label: __("Q2 (Apr – Jun)") },
				{ value: "3", label: __("Q3 (Jul – Sep)") },
				{ value: "4", label: __("Q4 (Oct – Dec)") },
			],
			default: current_quarter,
			reqd: 1,
			width: "120px",
			on_change: function () {
				sync_quarter_dates(frappe.query_report);
				frappe.query_report.refresh();
			},
		},
		{
			fieldname: "from_date",
			label: __("From"),
			fieldtype: "Date",
			default: default_dates.from_date,
			hidden: 1,
		},
		{
			fieldname: "to_date",
			label: __("To"),
			fieldtype: "Date",
			default: default_dates.to_date,
			hidden: 1,
		},
		{
			fieldname: "company",
			label: __("Company"),
			fieldtype: "Link",
			options: "Company",
			default: frappe.defaults.get_user_default("Company"),
			width: "100px",
			reqd: 1,
		},
	],
};
