<?php

namespace App\Core;

/**
 * Query Performance Logger
 * يسجل جميع الاستعلامات مع execution time
 */
class QueryLogger
{
    private Logger $logger;
    private array $queries = [];
    private bool $enabled;
    private float $slowQueryThreshold;

    public function __construct(Logger $logger, bool $enabled = true, float $slowQueryThreshold = 1.0)
    {
        $this->logger = $logger;
        $this->enabled = $enabled;
        $this->slowQueryThreshold = $slowQueryThreshold;
    }

    /**
     * تسجيل query
     */
    public function log(string $sql, array $params = [], float $executionTime = 0, int $rowCount = 0): void
    {
        if (!$this->enabled) {
            return;
        }

        $query = [
            'sql' => $sql,
            'params' => $params,
            'execution_time' => $executionTime,
            'row_count' => $rowCount,
            'timestamp' => microtime(true)
        ];

        $this->queries[] = $query;

        // تسجيل slow queries
        if ($executionTime > $this->slowQueryThreshold) {
            $this->logger->warning('Slow query detected', [
                'sql' => $sql,
                'params' => $params,
                'execution_time' => round($executionTime, 3),
                'row_count' => $rowCount
            ]);
        }
    }

    /**
     * جلب جميع queries
     */
    public function getQueries(): array
    {
        return $this->queries;
    }

    /**
     * جلب slow queries فقط
     */
    public function getSlowQueries(): array
    {
        return array_filter($this->queries, function($query) {
            return $query['execution_time'] > $this->slowQueryThreshold;
        });
    }

    /**
     * إحصائيات queries
     */
    public function getStats(): array
    {
        if (empty($this->queries)) {
            return [
                'total' => 0,
                'total_time' => 0,
                'average_time' => 0,
                'slow_queries' => 0
            ];
        }

        $totalTime = array_sum(array_column($this->queries, 'execution_time'));
        $slowCount = count($this->getSlowQueries());

        return [
            'total' => count($this->queries),
            'total_time' => round($totalTime, 3),
            'average_time' => round($totalTime / count($this->queries), 3),
            'slow_queries' => $slowCount,
            'slow_query_percentage' => round(($slowCount / count($this->queries)) * 100, 2)
        ];
    }

    /**
     * مسح queries
     */
    public function clear(): void
    {
        $this->queries = [];
    }

    /**
     * تفعيل/تعطيل
     */
    public function setEnabled(bool $enabled): void
    {
        $this->enabled = $enabled;
    }
}
