<?php

namespace App\Http\Controllers\Api\Finance;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Payments\PaypalTransactionsListRequest;
use App\Http\Resources\Payments\PaypalTransactionResource;
use App\Services\Payments\PaypalTransactionsService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;

class PaypalTransactionsController extends BaseApiController
{
    public function __construct(private PaypalTransactionsService $service)
    {
        parent::__construct();
    }

    public function index(PaypalTransactionsListRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $perPage = (int) ($payload['per_page'] ?? 10);
        $rows = $this->service->list($payload['q'] ?? null, $perPage);

        return response()->json([
            'ok' => true,
            'transactions' => PaypalTransactionResource::collection($rows->items()),
            'pagination' => [
                'current_page' => $rows->currentPage(),
                'per_page' => $rows->perPage(),
                'total' => $rows->total(),
                'last_page' => $rows->lastPage(),
            ],
        ]);
    }

    public function downloadCsv(PaypalTransactionsListRequest $request): StreamedResponse
    {
        $payload = $request->validated();
        $rows = $this->service->listAll($payload['q'] ?? null);

        $filename = 'paypal_transactions_' . date('Ymd_His') . '.csv';

        return response()->streamDownload(function () use ($rows) {
            $out = fopen('php://output', 'w');
            fputcsv($out, [
                'ID', 'Transaction ID', 'Order ID', 'Parent School ID',
                'Email', 'Amount', 'Net Amount', 'Currency',
                'Status', 'Event Type', 'Created At',
            ]);

            foreach ($rows as $row) {
                fputcsv($out, [
                    $row['id'] ?? null,
                    $row['transaction_id'] ?? null,
                    $row['order_id'] ?? null,
                    $row['parent_school_id'] ?? null,
                    $row['payer_email'] ?? null,
                    $row['amount'] ?? null,
                    $row['net_amount'] ?? null,
                    $row['currency'] ?? null,
                    $row['status'] ?? null,
                    $row['event_type'] ?? null,
                    $row['created_at'] ?? null,
                ]);
            }

            fclose($out);
        }, $filename, ['Content-Type' => 'text/csv']);
    }
}
