<?php

namespace App\Modules\Finance\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Finance\Contracts\FinanceServiceInterface;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Carbon;
use Illuminate\Pagination\LengthAwarePaginator;

class AccountingReportController extends Controller
{
    protected $financeService;

    public function __construct(FinanceServiceInterface $financeService)
    {
        $this->financeService = $financeService;
    }

    public function index(Request $request)
    {
        $dateStart = $request->input('date_start', Carbon::now()->toDateString());
        $dateEnd = $request->input('date_end', Carbon::now()->toDateString());

        $reportData = $this->financeService->getAccountingReportData($dateStart, $dateEnd);
        $allRecords = $reportData['records'];

        // 3. Manual Pagination
        $perPage = $request->input('per_page', 10);
        $page = $request->input('page', 1);
        $offset = ($page - 1) * $perPage;

        $paginatedRecords = new LengthAwarePaginator(
            $allRecords->slice($offset, $perPage)->values(),
            $allRecords->count(),
            $perPage,
            $page,
            ['path' => $request->url(), 'query' => $request->query()]
        );

        return Inertia::render('Accounting/Report', [
            'records' => $paginatedRecords,
            'summary' => $reportData['summary'],
            'filters' => [
                'date_start' => $dateStart,
                'date_end' => $dateEnd,
                'per_page' => (int)$perPage,
            ],
        ]);
    }

    public function export(Request $request)
    {
        $dateStart = $request->input('date_start', Carbon::now()->toDateString());
        $dateEnd = $request->input('date_end', Carbon::now()->toDateString());
        $selectedIdsParam = $request->input('selected_ids');

        $reportData = $this->financeService->getAccountingReportData($dateStart, $dateEnd);
        $allRecords = $reportData['records'];

        if ($selectedIdsParam) {
            $ids = explode(',', $selectedIdsParam);
            $allRecords = $allRecords->whereIn('id', $ids);
        }

        $exportData = $allRecords->map(function ($record) {
            return [
                $record['date'],
                $record['source'],
                $record['category'],
                $record['item'],
                $record['reference'],
                $record['invoice_number'],
                $record['amount'],
            ];
        });

        $filename = "accounting_report_{$dateStart}_{$dateEnd}.csv";
        $headers = [
            'Content-Type' => 'text/csv; charset=UTF-8',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
        ];

        $callback = function () use ($exportData) {
            $file = fopen('php://output', 'w');
            // BOM for Excel compatibility with UTF-8
            fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));
            
            fputcsv($file, ['日期', '來源', '類別', '項目', '參考單號', '發票號碼', '金額']);

            foreach ($exportData as $row) {
                fputcsv($file, $row);
            }
            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }
}
