<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

/**
 * 收付款综合查询视图（依赖结算收付款表，见 2026_04_19_210000）。
 *
 * dberp_document_queries 见 2026_05_24_140000，须在采购申请、销售报价、结算扩展等表就绪后创建。
 */
return new class extends Migration
{
    public function up(): void
    {
        DB::statement('DROP VIEW IF EXISTS dberp_receipt_payment_queries');
        DB::statement($this->receiptPaymentQueryViewSql());
    }

    public function down(): void
    {
        DB::statement('DROP VIEW IF EXISTS dberp_receipt_payment_queries');
    }

    private function receiptPaymentQueryViewSql(): string
    {
        return <<<'SQL'
CREATE VIEW dberp_receipt_payment_queries AS
SELECT
    (1 * 1000000000) + id AS row_id,
    'receipt' AS direction,
    code,
    status,
    business_time,
    amount,
    customer_id,
    NULL AS supplier_id,
    sales_order_id,
    NULL AS purchase_order_id,
    payment_method_item_id,
    handler_employee_id,
    effective_at,
    voided_at,
    remark
FROM dberp_receipt_orders
UNION ALL
SELECT
    (2 * 1000000000) + id AS row_id,
    'payment' AS direction,
    code,
    status,
    business_time,
    amount,
    NULL AS customer_id,
    supplier_id,
    NULL AS sales_order_id,
    purchase_order_id,
    payment_method_item_id,
    handler_employee_id,
    effective_at,
    voided_at,
    remark
FROM dberp_payment_orders
SQL;
    }
};
