<?php

namespace App\Http\Controllers;

use App\Models\PaymentBatch;
use Illuminate\Http\Request;

class PaymentBatchController extends Controller
{
    public function index(Request $request)
    {
        $batches = PaymentBatch::with('user')
            ->orderBy('created_at', 'desc')
            ->paginate(15);

        if ($request->ajax()) {
            return view('payment-batches.index', compact('batches'));
        }

        return view('payment-batches.ajax', compact('batches'));
    }

    public function download($id)
    {
        $batch = PaymentBatch::findOrFail($id);
        $absolutePath = storage_path('app/' . $batch->file_path);

        if (!file_exists($absolutePath)) {
            return redirect('payment-batches')->with('error', 'El archivo ya no está disponible en el servidor.');
        }

        return response()->download($absolutePath, $batch->file_name);
    }
}
