<?php

namespace App\Http\Controllers;

use App\Models\Expenses;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

class ExpensesController extends Controller
{
    //

    public  function __construct()
    {
        $this->middleware(['auth', 'members']);
    }

    public function member_all_expenses()
    {
        $expenses = Expenses::all();

        return view('expenses.index', compact('expenses'));
    }

    public function member_new_expense()
    {
        return view('expenses.new');
    }

    public function member_save_expense(Request $request)
    {
        $request->validate([
            'item'=> 'required:string',
            'cost'=> 'required',
            'description'=> 'required',
            'expense_date'=> 'required',
//            'receipt'=> 'required',
        ]);

        If($request->hasFile('receipt')) {

            $file = $request->file('receipt');

            $destinationPath = 'uploads/expenses/receipt';
            $filename = time() . '-' . $file->getClientOriginalName();
            $thumbPath = 'uploads/expenses/thumbReceipt/' . $filename;
            Image::make($file->getRealPath())->resize(300, null, function ($constraint) {
                $constraint->aspectRatio();
            })->save($thumbPath);

            $file->move($destinationPath, $filename);
        }

        $expense = new Expenses([
            'item' =>$request->item,
            'cost' =>$request->cost,
            'description' =>$request->description,
            'receipt' =>$filename,
            'expense_date' =>$request->expense_date,
            'created_by' =>auth()->user()->id,
        ]);


        $expense->save();

        return redirect()->back()->with('success', 'The Expense has been recorded successfully');
    }
}
