<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Models\Expence;
use App\Models\ExpenceType;
use App\Models\ExpenceImages;
use Carbon\Carbon;

class ExpenceController extends Controller
{
    public function __construct()
    {
        
    }
    public function createexpence(Request $request)
    {
        $customerid = $request->customerid;
        $expencetype = ExpenceType::orderBy('name','ASC')->get();
        return view('expence_mobile.add',compact('customerid','expencetype'));
    }
    public function saveexpence(Request $request)
    {
        $addexpence = new Expence();
        $addexpence->customer_id = $request->customer_id;
        $addexpence->expensetype = $request->expensetype;
        $addexpence->amount = $request->amount;
        $addexpence->start_location = $request->start_location;
        $addexpence->end_location = $request->end_location;
        $addexpence->save();

        if($request->file('file')){
            foreach($request->file('file') as $key => $val)
            {
                $expenceid = $addexpence->id;
                if(!empty($val)) {
                    $temp = array();
                    if ($request->file('file')[$key]) {
                        $date = Carbon::now();
                        $name = $date->format('YmdHis').'_'.str_replace(' ', '_', $request->file('file')[$key]->getClientOriginalName());
                        $ext = $request->file('file')[$key]->getClientOriginalExtension();
                        //$image = md5(microtime() . $name) . "." . $ext;
                        $path = public_path('../public/uploads/expence/'.$expenceid.'/');
                        $success = $request->file('file')[$key]->move($path,$name);

                        $addexpenceimage = new ExpenceImages();
                        $addexpenceimage->expence_id  = $expenceid;
                        $addexpenceimage->description  = $request->file('file')[$key]->getClientOriginalName();
                        $addexpenceimage->image  = url('uploads/expence/'.$expenceid) .'/'.$name;
                        $addexpenceimage->save();
                    }
                }
            }
        }
        
        return back()->with('success', 'Success! Your expense has been added.');
    }
}
