<?php

namespace App\Modules\HR\Recruitment\Services\ReportBuilders;

use App\Modules\HR\Recruitment\DTOs\RecruitmentReportFilters;
use App\Modules\HR\Recruitment\Repositories\RecruitmentReportRepository;
use Illuminate\Support\Facades\DB;

class SourceAnalysisReportBuilder implements RecruitmentReportBuilder
{
    public function __construct(
        private readonly RecruitmentReportRepository $reports,
    ) {}

    public function build(int $tenantId, RecruitmentReportFilters $filters): array
    {
        $rows = [];
        $summary = [];
        $query = $this->reports->applicationsBase($tenantId, $filters)
            ->select('source', DB::raw('COUNT(*) as total'))
            ->groupBy('source')
            ->orderByDesc('total');

        foreach ($query->get() as $row) {
            $source = $row->source ?: __('recruitment.reports.source_analysis.unknown');
            $total = (int) $row->total;
            $summary[$source] = $total;
            $rows[] = [$source, $total];
        }

        $candidates = $this->reports->candidatesBase($tenantId, $filters)
            ->select('source', DB::raw('COUNT(*) as total'))
            ->groupBy('source')
            ->orderByDesc('total')
            ->get();

        foreach ($candidates as $row) {
            $source = ($row->source ?: __('recruitment.reports.source_analysis.unknown')).' ('.__('recruitment.reports.source_analysis.candidates').')';
            $rows[] = [$source, (int) $row->total];
        }

        return [
            'title_key' => 'recruitment.reports.types.source_analysis',
            'columns' => ['source', 'count'],
            'rows' => $rows,
            'summary' => $summary,
        ];
    }
}
