<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;

class FileController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        

    }

    public function readFile(Request $request)
    {       
     
        if ($request->f != null) {
            $filePath = storage_path('app/'.$request->d.'/'. $request->f);
                  
            if (file_exists($filePath)) {
                
                $path = storage_path('app/'.$request->d.'/'.$request->f);
                if(!Storage::exists($request->d.'/'.$request->f)){
                    abort(404);
                }
                
                $file = Storage::get($request->d.'/'.$request->f);
                $type = Storage::mimeType($request->d.'/'.$request->f);
                return Response::make($file,200)->header("Content-Type", $type);
            } else {
                // return response()->json([], 404);
                // return response()->json(['error' => 'File not found'], 404);
                // return response()->json(['error' => 'File not found'], 204);
                return response()->json([
                    'message' => 'File not found',
                    'status' => false,
                ], 204);
            }
        } else {
            return response()->json(['error' => 'File not specified'], 400);
        }
    }


    public function downloadFile($file)
    {
        $filePath = storage_path('app/proposal/' . $file);
        if (file_exists($filePath)) {
            $url = Storage::disk('local')->url('proposal/' . $file);
            return response()->json(['url' => $url]);
        } else {
            return response()->json(['message' => "File not found.", 'error' => 'File not found.'], 404);
        }
    }


    private function getMimeType($extension)
    {
        switch ($extension) {
            case 'pdf':
                return 'application/pdf';
            case 'jpg':
            case 'jpeg':
                return 'image/jpeg';
            case 'png':
                return 'image/png';
            case 'xls':
            case 'xlsx':
                return 'application/vnd.ms-excel';
            default:
                return 'application/octet-stream'; // Default MIME type for unknown file types
    }
}

}
