<?php

namespace App\Http\Controllers;

use App\Models\Expense;
use App\Support\BanglaPdf;
use App\Support\ExpenseReport;
use App\Support\TrackerBoot;
use Illuminate\Http\Request;
use Mpdf\Output\Destination;
use Symfony\Component\HttpFoundation\StreamedResponse;

/**
 * The server side of the tracker: the SPA shell plus the three output formats
 * that have to be rendered server-side (print sheet, CSV, PDF report).
 *
 * All reading and writing of expenses happens over the JSON API — see
 * App\Http\Controllers\Api\ExpenseController.
 */
class ExpenseController extends Controller
{
    /** The Vue app's one and only HTML page. */
    public function index()
    {
        return view('app', ['boot' => TrackerBoot::payload()]);
    }

    public function print(Request $request)
    {
        $expenses = ExpenseReport::rows($request);

        return view('expenses.print', [
            'expenses' => $expenses,
            'summary' => ExpenseReport::summary($expenses),
        ]);
    }

    /** mPDF report — inline in the browser, or a download with ?download=1. */
    public function pdf(Request $request)
    {
        abort_unless(BanglaPdf::fontsInstalled(), 503, 'Bangla PDF font missing in storage/fonts.');

        $expenses = ExpenseReport::rows($request);

        $html = view('expenses.pdf', [
            'expenses' => $expenses,
            'summary' => ExpenseReport::summary($expenses),
            'filterSummary' => ExpenseReport::filterSummary(ExpenseReport::filters($request)),
        ])->render();

        $pdf = BanglaPdf::make();
        $pdf->SetTitle(config('tracker.title'));
        $pdf->SetAuthor(config('tracker.title'));
        $pdf->SetHTMLFooter(
            '<div style="border-top:0.5px solid #c9d8e8; padding-top:3px; font-size:7.5pt; color:#666;">'
            .'<table width="100%"><tr>'
            .'<td>'.e(config('tracker.title')).'</td>'
            .'<td align="right">পৃষ্ঠা {PAGENO} / {nbpg}</td>'
            .'</tr></table></div>'
        );
        $pdf->WriteHTML($html);

        $filename = 'expense-report-'.now()->format('Y-m-d').'.pdf';

        return response($pdf->Output('', Destination::STRING_RETURN), 200, [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => ($request->boolean('download') ? 'attachment' : 'inline')
                .'; filename="'.$filename.'"',
        ]);
    }

    public function export(Request $request): StreamedResponse
    {
        $expenses = ExpenseReport::rows($request);
        $labels = config('tracker.labels');

        return response()->streamDownload(function () use ($expenses, $labels) {
            $out = fopen('php://output', 'w');
            fwrite($out, "\xEF\xBB\xBF"); // BOM so Excel reads Bengali correctly

            fputcsv($out, [
                $labels['date'], $labels['category'], $labels['description'],
                $labels['payment_method'], $labels['remark'], $labels['amount'],
            ]);

            foreach ($expenses as $e) {
                fputcsv($out, [
                    $e->expense_date?->format('d/m/Y'),
                    $e->categoryName(),
                    $e->description,
                    $e->payment_method,
                    $e->remark,
                    number_format((float) $e->amount, 2, '.', ''),
                ]);
            }

            fputcsv($out, ['', '', '', '', $labels['total'], number_format((float) $expenses->sum('amount'), 2, '.', '')]);
            fclose($out);
        }, 'expenses-'.now()->format('Y-m-d-His').'.csv', [
            'Content-Type' => 'text/csv; charset=UTF-8',
        ]);
    }
}
