import frappe

@frappe.whitelist()
def get_pallets(page=1, page_size=100, sort_field="pallet_number", sort_dir="desc", status_filter="", search=""):
    page = int(page)
    page_size = int(page_size)
    offset = (page - 1) * page_size
    
    conditions = [
        "pallet_number IS NOT NULL", 
        "pallet_number != ''", 
        "date_reserved IS NOT NULL",
        "customer_number IS NOT NULL",
        "customer_number != ''"
    ]
    
    junk = ["", "0", "0000", "N/A", "TBD", "null", "999990", "999995"]
    junk_list = "', '".join(junk)
    conditions.append("pallet_number NOT IN ('" + junk_list + "')")
    conditions.append("pallet_number NOT LIKE '999%'")
    conditions.append("pallet_number REGEXP '^[0-9]'")
    
    if status_filter:
        conditions.append("status = '" + frappe.db.escape(status_filter) + "'")
    if search:
        conditions.append("pallet_number LIKE '%" + frappe.db.escape(search) + "%'")
    
    where_clause = " AND ".join(conditions)
    
    total = frappe.db.sql("SELECT COUNT(*) FROM tabPallet WHERE " + where_clause)[0][0]
    
    pallets = frappe.db.sql("SELECT name, pallet_number, date_reserved, received_date, customer_number, company_name, inbound_weight, tester, description, qty_to_sales, weight_to_sales, finish_date, notes, status FROM tabPallet WHERE " + where_clause + " ORDER BY CAST(pallet_number AS UNSIGNED) " + sort_dir + " LIMIT " + str(page_size) + " OFFSET " + str(offset), as_dict=True)
    
    empty_pallet = frappe.db.sql("SELECT name, pallet_number, date_reserved, received_date, customer_number, company_name, inbound_weight, tester, description, qty_to_sales, weight_to_sales, finish_date, notes, status FROM tabPallet WHERE date_reserved IS NULL AND (customer_number IS NULL OR customer_number = '') AND pallet_number NOT IN ('" + junk_list + "') AND pallet_number NOT LIKE '999%' AND pallet_number REGEXP '^[0-9]' ORDER BY CAST(pallet_number AS UNSIGNED) DESC LIMIT 1", as_dict=True)
    
    result = []
    if empty_pallet:
        empty_pallet[0]["_is_new"] = True
        result.append(empty_pallet[0])
    result.extend(pallets)
    
    return {"pallets": result, "total": total, "page": page, "page_size": page_size}

@frappe.whitelist()
def update_pallet(docname, field, value):
    pallet = frappe.get_doc("Pallet", docname)
    pallet.set(field, value)
    pallet.save(ignore_permissions=True)
    frappe.db.commit()
    return {"status": "ok", "message": "Updated " + field}

@frappe.whitelist()
def create_pallet(data):
    data = frappe.parse_json(data)
    pallet = frappe.new_doc("Pallet")
    pallet.pallet_number = data.get("pallet_number")
    pallet.status = data.get("status", "Received")
    pallet.date_reserved = data.get("date_reserved")
    for field, value in data.items():
        if field not in ["pallet_number", "status", "date_reserved"] and value:
            pallet.set(field, value)
    pallet.insert(ignore_permissions=True)
    frappe.db.commit()
    return {"status": "ok", "name": pallet.name}
