<?php

namespace App\Http\Controllers\Admin;

use App\Core\Services\Accounting\FinancialReportService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

class FinancialReportController extends Controller
{
    public function __construct(
        private FinancialReportService $service
    ) {}

    /**
     * Display trial balance
     */
    public function trialBalance(Request $request): View
    {
        $dateFrom = $request->get('date_from', now()->startOfYear()->format('Y-m-d'));
        $dateTo = $request->get('date_to', now()->format('Y-m-d'));

        $trialBalance = $this->service->generateTrialBalance($dateFrom, $dateTo);

        return view('admin.accounting.reports.trial-balance', [
            'trialBalance' => $trialBalance,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
        ]);
    }

    /**
     * Export trial balance to CSV
     */
    public function exportTrialBalance(Request $request): Response
    {
        $dateFrom = $request->get('date_from', now()->startOfYear()->format('Y-m-d'));
        $dateTo = $request->get('date_to', now()->format('Y-m-d'));

        $trialBalance = $this->service->generateTrialBalance($dateFrom, $dateTo);

        // Format for CSV
        $csvData = [];
        $csvData[] = ['Account Code', 'Account Name', 'Type', 'Debit', 'Credit', 'Balance'];

        foreach ($trialBalance as $item) {
            $csvData[] = [
                $item['account']->code,
                $item['account']->name,
                $item['account']->type,
                number_format($item['debit'], 2),
                number_format($item['credit'], 2),
                number_format($item['balance'], 2),
            ];
        }

        $filename = 'trial-balance-'.$dateFrom.'-to-'.$dateTo.'.csv';
        $path = $this->service->exportToCsv($csvData, $filename);

        return response()->download($path, $filename)->deleteFileAfterSend(true);
    }

    /**
     * Display profit & loss statement
     */
    public function profitLoss(Request $request): View
    {
        $dateFrom = $request->get('date_from', now()->startOfYear()->format('Y-m-d'));
        $dateTo = $request->get('date_to', now()->format('Y-m-d'));

        $report = $this->service->generateProfitLoss($dateFrom, $dateTo);

        return view('admin.accounting.reports.profit-loss', [
            'report' => $report,
        ]);
    }

    /**
     * Export profit & loss to CSV
     */
    public function exportProfitLoss(Request $request): Response
    {
        $dateFrom = $request->get('date_from', now()->startOfYear()->format('Y-m-d'));
        $dateTo = $request->get('date_to', now()->format('Y-m-d'));

        $report = $this->service->generateProfitLoss($dateFrom, $dateTo);

        $csvData = [];
        $csvData[] = ['Profit & Loss Statement'];
        $csvData[] = ['Period: '.$dateFrom.' to '.$dateTo];
        $csvData[] = [];
        $csvData[] = ['Revenue'];
        foreach ($report['revenue']['details'] as $item) {
            $csvData[] = [$item['account']->name, number_format($item['amount'], 2)];
        }
        $csvData[] = ['Total Revenue', number_format($report['revenue']['total'], 2)];
        $csvData[] = [];
        $csvData[] = ['Expenses'];
        foreach ($report['expenses']['details'] as $item) {
            $csvData[] = [$item['account']->name, number_format($item['amount'], 2)];
        }
        $csvData[] = ['Total Expenses', number_format($report['expenses']['total'], 2)];
        $csvData[] = [];
        $csvData[] = ['Net Income', number_format($report['net_income'], 2)];

        $filename = 'profit-loss-'.$dateFrom.'-to-'.$dateTo.'.csv';
        $path = $this->service->exportToCsv($csvData, $filename);

        return response()->download($path, $filename)->deleteFileAfterSend(true);
    }

    /**
     * Display tax report
     */
    public function taxReport(Request $request): View
    {
        $dateFrom = $request->get('date_from', now()->startOfYear()->format('Y-m-d'));
        $dateTo = $request->get('date_to', now()->format('Y-m-d'));

        $report = $this->service->generateTaxReport($dateFrom, $dateTo);

        return view('admin.accounting.reports.tax-report', [
            'report' => $report,
        ]);
    }

    /**
     * Export tax report to CSV
     */
    public function exportTaxReport(Request $request): Response
    {
        $dateFrom = $request->get('date_from', now()->startOfYear()->format('Y-m-d'));
        $dateTo = $request->get('date_to', now()->format('Y-m-d'));

        $report = $this->service->generateTaxReport($dateFrom, $dateTo);

        $csvData = [];
        $csvData[] = ['Tax Report'];
        $csvData[] = ['Period: '.$dateFrom.' to '.$dateTo];
        $csvData[] = [];
        $csvData[] = ['Income'];
        $csvData[] = ['Total Income', number_format($report['income']['total'], 2)];
        $csvData[] = ['Tax Collected', number_format($report['income']['tax_collected'], 2)];
        $csvData[] = ['Number of Transactions', $report['income']['count']];
        $csvData[] = [];
        $csvData[] = ['Expenses'];
        $csvData[] = ['Total Expenses', number_format($report['expenses']['total'], 2)];
        $csvData[] = ['Tax Paid', number_format($report['expenses']['tax_paid'], 2)];
        $csvData[] = ['Number of Transactions', $report['expenses']['count']];
        $csvData[] = [];
        $csvData[] = ['Net Tax Owed', number_format($report['net_tax_owed'], 2)];

        $filename = 'tax-report-'.$dateFrom.'-to-'.$dateTo.'.csv';
        $path = $this->service->exportToCsv($csvData, $filename);

        return response()->download($path, $filename)->deleteFileAfterSend(true);
    }
}
