<?php

declare(strict_types=1);

require __DIR__ . '/ExportHarness.php';

$account = (string)getenv('POC_MEAL_ACCOUNT');
if (!preg_match('/^CDXPAY[A-F0-9]{8}$/D', $account)) {
    throw new RuntimeException('Only a CDXPAY synthetic order may be exported');
}
$h = new ExportHarness('CDXPARSTCEXP');
$query = $h->store->prepare('SELECT m.ID,m.ORDER_NO,m.BIND_TIME,m.ORDER_PRICE,m.PAY_PRICE,'
    . ' m.CASH,m.SUBSIDY,m.GIFT,m.REFUND_AMOUNT FROM ' . $h->s('meal_order') . ' m'
    . ' JOIN ' . $h->s('user') . ' u ON u.ID=m.USER_ID'
    . ' WHERE u.ACCOUNT=? AND u.NAME=? AND m.IS_DELETE=0 ORDER BY m.ID DESC '
    . ($h->dialect === 'dm' ? 'FETCH FIRST 2 ROWS ONLY' : 'LIMIT 2'));
$query->execute([$account, $account]);
$sourceRows = array_map('array_change_key_case', $query->fetchAll(PDO::FETCH_ASSOC));
if (count($sourceRows) !== 1) throw new RuntimeException('One unique CDXPAY meal source required');
$source = $sourceRows[0];
$date = substr((string)$source['bind_time'], 0, 10);
$columns = 'index,order_no,order_price,pay_amount,cash_payment,subsidy_payment,gift_payment,refund_amount';
$form = ['type' => '1', 'order_no' => (string)$source['order_no'],
    'nickname' => $account, 'start_date' => $date, 'end_date' => $date,
    'export_columns' => $columns];
$results = $h->run('/p/mealOrder/export', '/p/mealOrder/exportLogs', 1,
    $form,
    static function (array $conditions) use ($source, $account, $columns): bool {
        return ($conditions['order_no'] ?? null) === (string)$source['order_no']
            && ($conditions['nickname'] ?? null) === $account
            && ($conditions['export_columns'] ?? null) === $columns;
    },
    static function (array $rows) use ($source): array {
        $headers = ['A' => '序号', 'B' => '订单编号', 'C' => '订单金额',
            'D' => '实付金额', 'E' => '现金支付', 'F' => '补贴支付',
            'G' => '赠送支付', 'H' => '退款金额'];
        if (count($rows) !== 3 || $rows[0] !== $headers
            || ($rows[1]['A'] ?? null) !== '1'
            || ($rows[1]['B'] ?? null) !== (string)$source['order_no']
            || ($rows[2]['A'] ?? null) !== '合计') {
            return ['status' => 'tested-fail', 'reason' => 'custom-column-order'];
        }
        $expected = ['C' => (string)$source['order_price'],
            'D' => bcsub((string)$source['pay_price'], (string)$source['refund_amount'], 2),
            'E' => (string)$source['cash'],
            'F' => (string)$source['subsidy'],
            'G' => (string)$source['gift'],
            'H' => (string)$source['refund_amount']];
        foreach ($expected as $column => $money) {
            if (bccomp((string)($rows[1][$column] ?? '0'), $money, 2) !== 0
                || bccomp((string)($rows[2][$column] ?? '0'), $money, 2) !== 0) {
                return ['status' => 'tested-fail', 'reason' => 'custom-amount-' . $column];
            }
        }
        return ['status' => 'tested-pass', 'business_rows' => 1,
            'custom_header_columns' => 8,
            'header_sha256' => hash('sha256', json_encode($rows[0], JSON_UNESCAPED_UNICODE)),
            'money_and_total_match_source' => true];
    });
echo json_encode(['dialect' => $h->dialect, 'module' => 'store-meal-export-custom-columns',
    'results' => $results], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
