<?php

declare(strict_types=1);

namespace App\Modules\Admin\Application\Services;

use PDO;
use Throwable;

final class DashboardMetricsService
{
    public function gather(PDO $pdo): array
    {
        $todaySales = ['c' => 0, 's' => 0];
        if (table_exists($pdo, 'sales_invoices')) {
            try {
                $today = date('Y-m-d');
                $from = $today . ' 00:00:00';
                $to = date('Y-m-d 00:00:00', strtotime($today . ' +1 day'));
                $statement = $pdo->prepare("SELECT COUNT(*) c, COALESCE(SUM(COALESCE(grand_total,total)),0) s FROM sales_invoices WHERE invoice_date >= ? AND invoice_date < ? AND (status IS NULL OR status='POSTED')");
                $statement->execute([$from, $to]);
                $todaySales = $statement->fetch() ?: ['c' => 0, 's' => 0];
            } catch (Throwable) {
                $todaySales = ['c' => 0, 's' => 0];
            }
        }

        $itemsCount = 0;
        if (table_exists($pdo, 'items')) {
            try {
                $statement = $pdo->query("SELECT COUNT(*) c FROM items WHERE is_active=1");
                $itemsCount = (int) ($statement->fetch()['c'] ?? 0);
            } catch (Throwable) {
                $itemsCount = 0;
            }
        }

        $lowCount = 0;
        if (table_exists($pdo, 'stock_balances') && table_exists($pdo, 'items')) {
            try {
                $statement = $pdo->query("SELECT COUNT(*) c FROM stock_balances sb JOIN items i ON i.id = sb.item_id WHERE sb.warehouse_id=1 AND sb.qty < 5");
                $lowCount = (int) ($statement->fetch()['c'] ?? 0);
            } catch (Throwable) {
                $lowCount = 0;
            }
        }

        $alertsSummary = null;
        if (can('alerts.view')) {
            try {
                $alertsSummary = alerts_dashboard_counts($pdo, 7, 30, 1000, 1000, 7, 60);
            } catch (Throwable) {
                $alertsSummary = ['total' => 0, 'checks' => ['total' => 0], 'inventory' => ['total' => 0, 'stagnant' => 0], 'parties' => ['total' => 0], 'treasury' => ['total' => 0], 'drafts' => ['total' => 0]];
            }
        }

        return [
            'items_count' => $itemsCount,
            'low_count' => $lowCount,
            'today_sales' => $todaySales,
            'alerts_summary' => $alertsSummary,
        ];
    }
}
