<?php

namespace App\Http\Controllers\Api\V1;

use App\Exports\DailyReportExport;
use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Services\DailyReportService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

/**
 * 일일 보고서 컨트롤러
 */
class DailyReportController extends Controller
{
    public function __construct(
        protected DailyReportService $service
    ) {}

    /**
     * 어음 및 외상매출채권 현황 조회
     */
    public function noteReceivables(Request $request): JsonResponse
    {
        return ApiResponse::handle(function () use ($request) {
            $params = $request->validate([
                'date' => 'nullable|date',
            ]);

            return $this->service->noteReceivables($params);
        }, __('message.fetched'));
    }

    /**
     * 일별 계좌 현황 조회
     */
    public function dailyAccounts(Request $request): JsonResponse
    {
        return ApiResponse::handle(function () use ($request) {
            $params = $request->validate([
                'date' => 'nullable|date',
            ]);

            return $this->service->dailyAccounts($params);
        }, __('message.fetched'));
    }

    /**
     * 일일 보고서 요약 통계
     */
    public function summary(Request $request): JsonResponse
    {
        return ApiResponse::handle(function () use ($request) {
            $params = $request->validate([
                'date' => 'nullable|date',
            ]);

            return $this->service->summary($params);
        }, __('message.fetched'));
    }

    /**
     * 일일 보고서 엑셀 다운로드
     */
    public function export(Request $request): BinaryFileResponse
    {
        $params = $request->validate([
            'date' => 'nullable|date',
        ]);

        $reportData = $this->service->exportData($params);
        $filename = '일일일보_'.$reportData['date'].'.xlsx';

        return Excel::download(new DailyReportExport($reportData), $filename);
    }
}
