<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use \App\Models\{Plano};
class PlanoController extends Controller
{
    public function index()
    {
        $data = Plano::all();

        return $data;
    }

    public function store(Request $request)
    {
        $item = new Plano;
        $item->name = $request->name;
        $item->description = $request->description;

        $file = $request->file('file');
        if($file){
            $fileName = $file->getClientOriginalName();
            $file->move('uploads', $fileName);
            $item->file = $fileName;   
        }
        //$item->file = $request->file;

        $item->save();

        return ['status' => 'succes', 'data' => $item];
    }

    public function update(Request $request) 
    {
        $item = Plano::find($request->id);

        $item->name = $request->name;
        $item->description = $request->description;

        $file = $request->file('file');
        if($file){
            $fileName = $file->getClientOriginalName();
            $file->move('uploads', $fileName);
            $item->file = $fileName;
        }
        
        $item->save();

        return ['status' => 'succes', 'data' => $item];
    }

    public function destroy($id)
    {
        $data = Plano::find($id);
        $data->delete();

        return ['status' => 'succes', 'data' => $data];
    }

    public function download(Request $request, $filename = false)
    {
        //$path = storage_path().'/app/public/uploads/'.$filename;
        $path = public_path().'/uploads/'.$filename;

        if (file_exists($path)) {
            return response()->download($path);
        }
    }
}
