<?php
declare(strict_types=1);
define('BASE_PATH', dirname(__DIR__));
require BASE_PATH . '/vendor/autoload.php';
\Dotenv\Dotenv::createUnsafeMutable(BASE_PATH)->load();
\Webman\Config::load(BASE_PATH . '/config', ['route', 'plugin']);
\Webman\ThinkOrm\ThinkOrm::start(null);

use app\dice\helper\AdminScopeHelper;
use app\dice\logic\reward_config\DiceRewardConfigLogic;
use app\dice\model\reward_config\DiceRewardConfig;
use plugin\saiadmin\app\cache\UserInfoCache;
use support\think\Db;

$adminInfo = UserInfoCache::getUserInfo(123);

echo "Raw DB count dept 1123: " . Db::table('dice_reward_config')->where('dept_id', 1123)->whereNull('delete_time')->count() . "\n";

$logic = new DiceRewardConfigLogic();
$query = $logic->search([]);
AdminScopeHelper::applyConfigScope($query, $adminInfo, 1123);
$sql = $query->fetchSql(true)->select();
echo "SQL: {$sql}\n";
$rows = $query->fetchSql(false)->select()->toArray();
echo "Model select count: " . count($rows) . "\n";

$model = new DiceRewardConfig();
$q2 = $model->where('dept_id', 1123)->order('id', 'asc');
$rows2 = $q2->select()->toArray();
echo "Direct model dept 1123: " . count($rows2) . "\n";

$tierCounts = Db::table('dice_reward_config')->where('dept_id', 1123)->group('tier')->column('count(*)', 'tier');
echo "Tier counts: " . json_encode($tierCounts, JSON_UNESCAPED_UNICODE) . "\n";

$idCounts = Db::query('SELECT id, COUNT(*) as c FROM dice_reward_config WHERE dept_id=1123 GROUP BY id HAVING c>1');
echo "Duplicate business ids in dept 1123: " . count($idCounts) . "\n";
if ($idCounts) {
    print_r($idCounts);
}
