<?php

declare(strict_types=1);

$root = getenv('POC_APP_ROOT');
$dialect = getenv('POC_DIALECT');
if (!$root || !in_array($dialect, ['mysql', 'dm'], true)) exit(2);
foreach (['HOST', 'PORT', 'SCHEMA', 'USER', 'PASSWORD'] as $part) {
    if (!getenv('POC_' . $part)) exit(2);
}
define('APP_PATH', $root . '/application/');
require $root . '/thinkphp/base.php';
require $root . '/application/common.php';
\think\Config::set([
    'type' => $dialect === 'dm' ? \app\cores\database\Dm::class : 'mysql',
    'hostname' => getenv('POC_HOST'),
    'hostport' => (int)getenv('POC_PORT'),
    'database' => getenv('POC_SCHEMA'),
    'username' => getenv('POC_USER'),
    'password' => getenv('POC_PASSWORD'),
    'prefix' => 'ydy_',
    'debug' => false,
    'resultset_type' => 'array',
    'fields_strict' => true,
], 'database');
\think\Db::clear();

$logic = new \app\p\logic\MealOrder();
$onlyNonempty = getenv('POC_ONLY_NONEMPTY') === '1';
if (!$onlyNonempty) {
    $futureDate = date('Y-m-d', strtotime('+1 day'));
    $list = $logic->getDishSalesVolumeDetailUserList([
        'bind_start_date' => $futureDate,
        'bind_end_date' => $futureDate,
        'page' => 1,
        'list_rows' => 1,
    ]);
    if (!isset($list['data']) || !is_array($list['data'])) {
        throw new RuntimeException('Dish sales person list did not return a page');
    }
    $path = sys_get_temp_dir() . '/codex-meal-order-export-' . bin2hex(random_bytes(6)) . '.xlsx';
    try {
        $export = $logic->exportOrdersToFile([
            'start_date' => $futureDate,
            'end_date' => $futureDate,
            'order_no' => 'CODEXDM8_NO_SUCH_ORDER_20260929',
        ], $path);
        if ((int)($export['rows'] ?? -1) !== 1 || !is_file($path)) {
            throw new RuntimeException('Empty meal order export did not create its totals row');
        }
        $zip = new ZipArchive();
        if ($zip->open($path) !== true || $zip->locateName('xl/worksheets/sheet1.xml') === false) {
            throw new RuntimeException('Meal order XLSX is unreadable');
        }
        $zip->close();
    } finally {
        if (is_file($path)) unlink($path);
    }
}
$orderNo = (string)\think\Db::name('meal_order')
    ->where('is_delete', 0)
    ->where('user_id', '>', 0)
    ->where('order_no', '<>', '')
    ->order('id', 'desc')
    ->value('order_no');
if ($orderNo === '') {
    echo json_encode(['dialect' => $dialect, 'status' => 'nonempty_fixture_missing']) . PHP_EOL;
    exit(3);
}
$privateDir = sys_get_temp_dir() . '/codex-meal-order-export-' . bin2hex(random_bytes(6));
if (!mkdir($privateDir, 0700)) throw new RuntimeException('Private export directory unavailable');
$nonemptyPath = $privateDir . '/orders.xlsx';
try {
    $nonempty = (new \app\p\logic\MealOrder())->exportOrdersToFile(['order_no' => $orderNo], $nonemptyPath);
    if ((int)($nonempty['rows'] ?? 0) < 2 || !is_file($nonemptyPath)) {
        throw new RuntimeException('Non-empty meal order export did not include an order and totals');
    }
    $zip = new ZipArchive();
    if ($zip->open($nonemptyPath) !== true || $zip->locateName('xl/worksheets/sheet1.xml') === false) {
        throw new RuntimeException('Non-empty meal order XLSX is unreadable');
    }
    $zip->close();
} finally {
    if (is_file($nonemptyPath)) unlink($nonemptyPath);
    rmdir($privateDir);
}
echo json_encode(['dialect' => $dialect, 'status' => 'passed',
    'sales_person_list_empty_boundary' => !$onlyNonempty,
    'meal_order_xlsx_empty_boundary' => !$onlyNonempty,
    'meal_order_xlsx_nonempty' => true]) . PHP_EOL;
