# Copyright (c) 2026, Company and contributors
# For license information, please see license.txt

import frappe
from frappe import _


def execute(filters=None):
	"""Main function for report execution"""
	columns = get_columns(filters)
	data = get_data(filters)

	return columns, data


def get_columns(filters=None):
	"""Get report columns definition (Cədvəl 21 — ƏDV - YGB hesabat)."""
	return [
		{
			"label": _("Purchase Invoice"),
			"fieldname": "purchase_invoice",
			"fieldtype": "Link",
			"options": "Purchase Invoice",
			"width": 160
		},
		{
			# YGB-nin tarixi
			"label": _("Date"),
			"fieldname": "posting_date",
			"fieldtype": "Date",
			"width": 100
		},
		{
			# Sətir kodu
			"label": _("Line Code"),
			"fieldname": "line_code",
			"fieldtype": "Data",
			"width": 100
		},
		{
			"label": _("YGB"),
			"fieldname": "ygb",
			"fieldtype": "Data",
			"width": 140
		},
		{
			# YGB üzrə alınmış malın ƏDV-siz dəyəri, manatla
			"label": _("Amount without VAT"),
			"fieldname": "amount_without_vat",
			"fieldtype": "Currency",
			"width": 180
		},
		{
			# YGB üzrə alınmış malın ƏDV məbləği, manatla
			"label": _("VAT amount"),
			"fieldname": "vat_amount",
			"fieldtype": "Currency",
			"width": 160
		}
	]


def get_data(filters=None):
	"""Get report data — one row per qualifying Purchase Invoice.

	A document qualifies when it is submitted and carries YGB data, i.e. at
	least one of the ygb / line_code fields is filled. Items are not filtered.
	"""
	filters = filters or {}

	# Only documents that actually carry YGB data: at least one of the YGB
	# fields (ygb / line_code) is filled.
	conditions = (
		"pi.docstatus = 1 AND ("
		"(pi.ygb IS NOT NULL AND pi.ygb != 0) "
		"OR (pi.line_code IS NOT NULL AND pi.line_code != '')"
		")"
	)
	params = {}

	if filters.get("company"):
		conditions += " AND pi.company = %(company)s"
		params["company"] = filters["company"]

	if filters.get("from_date"):
		conditions += " AND pi.posting_date >= %(from_date)s"
		params["from_date"] = filters["from_date"]

	if filters.get("to_date"):
		conditions += " AND pi.posting_date <= %(to_date)s"
		params["to_date"] = filters["to_date"]

	rows = frappe.db.sql(f"""
		SELECT
			pi.name AS purchase_invoice,
			pi.posting_date,
			pi.line_code,
			pi.ygb,
			pi.net_total AS amount_without_vat,
			pi.total_taxes_and_charges AS vat_amount
		FROM
			`tabPurchase Invoice` pi
		WHERE
			{conditions}
		ORDER BY
			pi.posting_date, pi.name
	""", params, as_dict=1)

	return rows
