-- ============================================================================
-- Phase 4: Invoices Module Definition (Declarative)
-- ============================================================================
-- This module uses the ActionRegistry, ModalBuilder, and DataLoader
-- enhancements to provide a fully declarative invoices management interface.
--
-- Features:
-- - Status-based row actions (Submit to TaxCore, Refund, etc.)
-- - Conditional action visibility
-- - ShoppingCartComponent for line items
-- - ActionRegistry integration for all actions
-- - TaxCore integration support
-- - No custom JavaScript required!
-- ============================================================================

-- Insert Invoices Module
INSERT INTO modules (
    name,
    config,
    icon,
    aria_label,
    description
) VALUES (
    'Invoices',
    '{
        "title": "Invoices Management",
        "modulePath": "invoices",
        "header": [
            {
                "type": "button",
                "label": "New Invoice",
                "icon": "fa-plus",
                "class": "btn btn-primary",
                "action": {
                    "handler": "openInvoiceForm"
                },
                "ariaLabel": "Create new invoice"
            },
            {
                "type": "filter-select",
                "options": {
                    "data_column": "status",
                    "label": "Status",
                    "options": [
                        {"label": "All", "value": ""},
                        {"label": "Draft", "value": "draft"},
                        {"label": "Pending", "value": "pending"},
                        {"label": "Submitted", "value": "submitted"},
                        {"label": "Paid", "value": "paid"},
                        {"label": "Overdue", "value": "overdue"},
                        {"label": "Cancelled", "value": "cancelled"}
                    ]
                }
            },
            {
                "type": "filter-select",
                "options": {
                    "data_column": "is_proforma",
                    "label": "Type",
                    "options": [
                        {"label": "All", "value": ""},
                        {"label": "Standard", "value": "false"},
                        {"label": "Proforma", "value": "true"},
                        {"label": "Advance Payment", "value": "advance"},
                        {"label": "Refund", "value": "refund"}
                    ]
                }
            },
            {
                "type": "filter-date-range",
                "options": {
                    "data_column": "invoice_date",
                    "label": "Date Range"
                }
            },
            {
                "type": "button",
                "label": "Refresh",
                "icon": "fa-sync",
                "class": "btn btn-ghost",
                "action": "refresh",
                "ariaLabel": "Refresh invoices list"
            }
        ],
        "body": [
            {
                "type": "table",
                "id": "invoicesTable",
                "options": {
                    "tableName": "invoices",
                    "primaryKeyField": "invoice_id",
                    "showGlobalSearch": true,
                    "columnsToShow": [
                        "invoice_number",
                        "invoice_date",
                        "name",
                        "amount",
                        "amount_paid",
                        "status",
                        "is_proforma",
                        "taxcore_submission_id",
                        "sent_at"
                    ],
                    "columnLabels": {
                        "invoice_number": "Invoice #",
                        "invoice_date": "Date",
                        "name": "Customer",
                        "amount": "Amount",
                        "amount_paid": "Paid",
                        "status": "Status",
                        "is_proforma": "Proforma",
                        "taxcore_submission_id": "TaxCore ID",
                        "sent_at": "Sent"
                    },
                    "rowClick": "selectRecord",
                    "rowActions": [
                        {
                            "label": "View",
                            "icon": "fa-eye",
                            "class": "btn btn-info btn-xs",
                            "action": "openSelectedDetail",
                            "ariaLabel": "View invoice details"
                        },
                        {
                            "label": "Submit to TaxCore",
                            "icon": "fa-upload",
                            "class": "btn btn-primary btn-xs",
                            "action": "invoices:submit-taxcore",
                            "condition": "status == \"draft\" && taxcore_submission_id == null",
                            "confirm": "Submit this invoice to the tax authority?",
                            "ariaLabel": "Submit invoice to tax authority"
                        },
                        {
                            "label": "TaxCore Receipt",
                            "icon": "fa-receipt",
                            "class": "btn btn-success btn-xs",
                            "action": "invoices:taxcore-receipt",
                            "condition": "taxcore_submission_id != null",
                            "ariaLabel": "View TaxCore receipt"
                        },
                        {
                            "label": "Create Advance Payment",
                            "icon": "fa-money-bill",
                            "class": "btn btn-success btn-xs",
                            "action": "invoices:advance-payment",
                            "condition": "status == \"draft\" && is_advance_payment == false",
                            "confirm": "Create an advance payment invoice?",
                            "ariaLabel": "Create advance payment invoice"
                        },
                        {
                            "label": "Create Refund",
                            "icon": "fa-undo",
                            "class": "btn btn-warning btn-xs",
                            "action": "invoices:refund",
                            "condition": "status == \"paid\" && is_refund == false",
                            "confirm": "Create a refund invoice?",
                            "ariaLabel": "Create refund invoice"
                        },
                        {
                            "label": "Record Payment",
                            "icon": "fa-credit-card",
                            "class": "btn btn-success btn-xs",
                            "action": "payments:initiate",
                            "condition": "status != \"paid\" && status != \"cancelled\"",
                            "ariaLabel": "Record payment for invoice"
                        },
                        {
                            "label": "Payment Status",
                            "icon": "fa-info-circle",
                            "class": "btn btn-info btn-xs",
                            "action": "payments:status",
                            "condition": "amount_paid > 0",
                            "ariaLabel": "View payment status"
                        },
                        {
                            "label": "PDF",
                            "icon": "fa-file-pdf",
                            "class": "btn btn-secondary btn-xs",
                            "action": "invoices:pdf",
                            "ariaLabel": "Download invoice PDF"
                        },
                        {
                            "label": "Cancel",
                            "icon": "fa-ban",
                            "class": "btn btn-error btn-xs btn-outline",
                            "action": "records:cancel",
                            "condition": "status != \"paid\" && status != \"cancelled\"",
                            "confirm": "Are you sure you want to cancel this invoice?",
                            "ariaLabel": "Cancel invoice"
                        }
                    ]
                }
            }
        ],
        "footer": [
            {
                "type": "button",
                "label": "Close",
                "class": "btn btn-ghost",
                "action": "close",
                "ariaLabel": "Close invoices module"
            }
        ],
        "dataSources": {
            "invoices": {
                "table": "invoices",
                "syncPolicy": "default",
                "autoRefresh": true,
                "refreshInterval": 30000
            }
        }
    }'::jsonb,
    'fa-file-invoice',
    'Invoices Management',
    'Create, submit, and manage invoices. Integrate with TaxCore for tax submissions.'
) ON CONFLICT (name) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description,
    updatedAt = now();

-- ============================================================================
-- Invoice Detail Modal Definition
-- ============================================================================
-- This modal shows full invoice details with action buttons
-- Uses ModalBuilder with ActionRegistry integration
-- Includes TaxCore integration information
-- ============================================================================

INSERT INTO modules (
    name,
    config,
    icon,
    aria_label,
    description
) VALUES (
    'Invoice Detail',
    '{
        "title": "Invoice {invoice_number}",
        "size": "large",
        "header": [
            {
                "type": "badge",
                "class": "badge badge-lg",
                "classExpression": "status == \"draft\" ? \"badge-warning\" : status == \"pending\" ? \"badge-info\" : status == \"paid\" ? \"badge-success\" : status == \"overdue\" ? \"badge-error\" : \"badge-ghost\"",
                "text": "{status}"
            },
            {
                "type": "badge",
                "class": "badge badge-lg badge-secondary",
                "text": "Proforma",
                "condition": "is_proforma == true"
            },
            {
                "type": "badge",
                "class": "badge badge-lg badge-success",
                "text": "TaxCore Submitted",
                "condition": "taxcore_submission_id != null"
            }
        ],
        "body": [
            {
                "type": "tabs",
                "tabs": [
                    {
                        "label": "Details",
                        "icon": "fa-info-circle",
                        "elements": [
                            {
                                "type": "grid",
                                "columns": 2,
                                "elements": [
                                    {
                                        "type": "field-display",
                                        "label": "Invoice Number",
                                        "field": "invoice_number"
                                    },
                                    {
                                        "type": "field-display",
                                        "label": "Date",
                                        "field": "invoice_date",
                                        "format": "date"
                                    },
                                    {
                                        "type": "field-display",
                                        "label": "Customer",
                                        "field": "name"
                                    },
                                    {
                                        "type": "field-display",
                                        "label": "Status",
                                        "field": "status"
                                    },
                                    {
                                        "type": "field-display",
                                        "label": "Total Amount",
                                        "field": "amount",
                                        "format": "currency"
                                    },
                                    {
                                        "type": "field-display",
                                        "label": "Amount Paid",
                                        "field": "amount_paid",
                                        "format": "currency"
                                    },
                                    {
                                        "type": "field-display",
                                        "label": "Sent At",
                                        "field": "sent_at",
                                        "format": "datetime"
                                    },
                                    {
                                        "type": "field-display",
                                        "label": "Tax",
                                        "field": "tax"
                                    }
                                ]
                            },
                            {
                                "type": "divider"
                            },
                            {
                                "type": "field-display",
                                "label": "Details",
                                "field": "details"
                            }
                        ]
                    },
                    {
                        "label": "Line Items",
                        "icon": "fa-list",
                        "elements": [
                            {
                                "type": "shopping-cart",
                                "id": "invoiceLineItems",
                                "options": {
                                    "dataField": "line_items",
                                    "readonly": true,
                                    "columns": [
                                        {
                                            "field": "item_type",
                                            "label": "Type",
                                            "type": "select",
                                            "options": [
                                                {"value": "product", "label": "Product"},
                                                {"value": "service", "label": "Service"}
                                            ]
                                        },
                                        {
                                            "field": "item_id",
                                            "label": "Item",
                                            "type": "select",
                                            "options_source_field": "item_type",
                                            "options_tables": {
                                                "product": "products",
                                                "service": "services"
                                            }
                                        },
                                        {
                                            "field": "description",
                                            "label": "Description",
                                            "type": "text"
                                        },
                                        {
                                            "field": "quantity",
                                            "label": "Qty",
                                            "type": "number"
                                        },
                                        {
                                            "field": "unit_price",
                                            "label": "Price",
                                            "type": "number"
                                        },
                                        {
                                            "field": "tax_rate",
                                            "label": "Tax %",
                                            "type": "number"
                                        },
                                        {
                                            "field": "total",
                                            "label": "Total",
                                            "type": "computed",
                                            "formula": "(quantity * unit_price) * (1 + tax_rate/100)"
                                        }
                                    ]
                                }
                            }
                        ]
                    },
                    {
                        "label": "TaxCore",
                        "icon": "fa-file-invoice-dollar",
                        "condition": "taxcore_submission_id != null",
                        "elements": [
                            {
                                "type": "alert",
                                "class": "alert alert-success",
                                "icon": "fa-check-circle",
                                "text": "This invoice has been successfully submitted to the tax authority."
                            },
                            {
                                "type": "grid",
                                "columns": 2,
                                "elements": [
                                    {
                                        "type": "field-display",
                                        "label": "TaxCore Submission ID",
                                        "field": "taxcore_submission_id"
                                    },
                                    {
                                        "type": "field-display",
                                        "label": "Submitted At",
                                        "field": "taxcore_submitted_at",
                                        "format": "datetime"
                                    },
                                    {
                                        "type": "field-display",
                                        "label": "Verification URL",
                                        "field": "taxcore_verification_url",
                                        "link": true
                                    },
                                    {
                                        "type": "field-display",
                                        "label": "QR Code",
                                        "field": "taxcore_qr_code",
                                        "render": "qrcode"
                                    }
                                ]
                            },
                            {
                                "type": "divider"
                            },
                            {
                                "type": "button",
                                "label": "View TaxCore Receipt",
                                "icon": "fa-receipt",
                                "class": "btn btn-primary",
                                "action": "invoices:taxcore-receipt"
                            }
                        ]
                    },
                    {
                        "label": "Payments",
                        "icon": "fa-credit-card",
                        "elements": [
                            {
                                "type": "table",
                                "id": "invoicePayments",
                                "options": {
                                    "tableName": "payments",
                                    "filters": {
                                        "reference_table": "invoices",
                                        "reference_id": "{invoice_id}"
                                    },
                                    "showGlobalSearch": false,
                                    "addButton": false,
                                    "columnsToShow": ["payment_date", "amount", "method", "status", "reference"],
                                    "columnLabels": {
                                        "payment_date": "Date",
                                        "amount": "Amount",
                                        "method": "Method",
                                        "status": "Status",
                                        "reference": "Reference"
                                    }
                                }
                            },
                            {
                                "type": "divider"
                            },
                            {
                                "type": "button",
                                "label": "Record Payment",
                                "icon": "fa-credit-card",
                                "class": "btn btn-success",
                                "action": "payments:initiate",
                                "condition": "status != \"paid\" && status != \"cancelled\""
                            }
                        ]
                    },
                    {
                        "label": "History",
                        "icon": "fa-history",
                        "elements": [
                            {
                                "type": "table",
                                "id": "invoiceHistory",
                                "options": {
                                    "tableName": "audit_logs",
                                    "filters": {
                                        "table_name": "invoices",
                                        "record_id": "{invoice_id}"
                                    },
                                    "showGlobalSearch": false,
                                    "addButton": false,
                                    "columnsToShow": ["action", "changed_by", "changed_at", "changes"],
                                    "columnLabels": {
                                        "action": "Action",
                                        "changed_by": "User",
                                        "changed_at": "Date",
                                        "changes": "Changes"
                                    }
                                }
                            }
                        ]
                    }
                ]
            }
        ],
        "footer": [
            {
                "type": "button",
                "label": "Close",
                "class": "btn btn-ghost",
                "action": "close"
            },
            {
                "type": "button",
                "label": "Edit",
                "icon": "fa-edit",
                "class": "btn btn-secondary",
                "action": {
                    "handler": "openInvoiceForm"
                },
                "condition": "status == \"draft\""
            },
            {
                "type": "button",
                "label": "Submit to TaxCore",
                "icon": "fa-upload",
                "class": "btn btn-primary",
                "action": "invoices:submit-taxcore",
                "condition": "status == \"draft\" && taxcore_submission_id == null",
                "confirm": "Submit this invoice to the tax authority?"
            },
            {
                "type": "button",
                "label": "Record Payment",
                "icon": "fa-credit-card",
                "class": "btn btn-success",
                "action": "payments:initiate",
                "condition": "status != \"paid\" && status != \"cancelled\""
            },
            {
                "type": "button",
                "label": "Download PDF",
                "icon": "fa-file-pdf",
                "class": "btn btn-secondary",
                "action": "invoices:pdf"
            }
        ]
    }'::jsonb,
    'fa-file-invoice',
    'Invoice Detail',
    'View and manage individual invoice details with TaxCore integration'
) ON CONFLICT (name) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description,
    updatedAt = now();

-- ============================================================================
-- Success!
-- ============================================================================
COMMENT ON TABLE modules IS 'Phase 4: Invoices module definitions use ActionRegistry, ModalBuilder, and DataLoader enhancements for fully declarative configuration with TaxCore integration';
