<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class QueryLogServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        if (config('app.debug')) {
            DB::listen(function($query) {
                $sql = $query->sql;
                $bindings = $query->bindings;
                $time = $query->time;

                // 格式化SQL语句（替换占位符）
                foreach ($bindings as $binding) {
                    $value = is_numeric($binding) ? $binding : "'".$binding."'";
                    $sql = preg_replace('/\?/', $value, $sql, 1);
                }

                // 记录SQL日志
                Log::channel('sql')->debug('SQL', [
                    'sql' => $sql,
                    'time' => $time.'ms',
                ]);
            });
        }
    }
}
