<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\TradingYear;
use App\Models\Transaction;

use Illuminate\Http\Request;

class DocumentsController extends Controller
{
    public function index(Request $request)
    {

        $userID = auth()->user()->id;
        $trading_year = TradingYear::where('user_id', $userID)->first();
        $documents = auth()->user()->transactions()
             ->where('trading_year_id', $trading_year->id)
             ->whereNotNull('attachment')->get();

        return response()->json($documents);
    }


    public function download($id)
    {
        $doc = Transaction::find($id);

        if (!$doc || !$doc->attachment) {
            abort(404, 'No attachment found');
        }

        // Ensure no URL prefix
        $attachmentPath = str_replace(url('storage') . '/', '', $doc->attachment);

        // Build correct storage path
        $filePath = storage_path('app/public/' . $attachmentPath);

        if (!file_exists($filePath)) {
            return response()->json([
                'error' => 'File not found',
                'checked_path' => $filePath,
            ], 404);
        }
        // dd( $filePath);

        return response()->download($filePath);
    }




}