<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use App\Models\FinancialYear;
use Illuminate\Support\Facades\Auth;

class FinancialYearController extends Controller
{

    const YEARS_BLADE = 'src/financial_years';
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $financialyears = FinancialYear::all();

        return view(FinancialYearController::YEARS_BLADE, 
            ['financialyears' => $financialyears, 'selectedFinancialyear' => null]);
    }

    public function save(Request $request){

        $data = $request->validate([
            'financial_year_name' => 'required|max:255'
        ]);

        $data['created_by'] = Auth::user()->user_id;
    
        $selected = $request->selected_financialyear;
    
        if($selected){
            $financialyear = tap(FinancialYear::where('finanacial_year_id', $selected)->update($data));
        }else {
            $financialyear = tap(new FinancialYear($data))->save();
        }
        return redirect('/financialyears');
    }

    public function search(Request $request){

        $financialyears = FinancialYear::where('financial_year_name', 'like', 
        '%' .$request->keyword. '%')->get();

        return json_encode($financialyears);
    }

    public function edit($id) {
        $financialYearId = $id;
        $selectedFinancialyear = FinancialYear::find($financialYearId);
        $financialyears = FinancialYear::all();

        return view(FinancialYearController::YEARS_BLADE, 
            ['financialyears' => $financialyears, 
            'selectedFinancialyear' => $selectedFinancialyear]);
    }

    public function del(Request $request) {

        $financialYearId = $request->deletefinancialyear;
        $financialyear = FinancialYear::find($financialYearId);
        $financialyear->delete();
        $financialyears = FinancialYear::all();

        return view(FinancialYearController::YEARS_BLADE, 
            ['financialyears' => $financialyears, 'selectedFinancialyear' => null]);
    }
}