<?php

namespace App\Modules\Saasuser\Http\Controllers;

use App\Facades\General;
use App\Modules\Saasuser\Http\Requests\StoreSaasUser;
use App\Modules\Saasuser\Model\SaasUser;
use Exception;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use Illuminate\View\View;
use Illuminate\Support\Facades\Auth;

class SaasUserController extends Controller
{
    /**
     * Module variable
     *
     * @var array
     */
    protected $moduleName;

    /**
     * Class Constructor.
     *
     * @return string
     */
    public function __construct()
    {
        $this->moduleName = $this->getModuleName();
    }

    /**
     * Get Module name.
     *
     * @return string
     */
    public function getModuleName()
    {
        return "saas-user";
    }

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return Factory|JsonResponse|View
     * @throws Exception
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            return SaasUser::getSaasUsers($this->moduleName);
        }

        General::saasLog('SL000201', ['action_module' => $this->moduleName]);
        return View('saasuser::index', ['moduleName' => $this->moduleName]);
    }

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function dashboard(Request $request)
    {
        $options          = array();
        $options["where"] = [];
        if(Auth::user()->role_id == \App\Models\Role::ROLE_TEACHER){
            $options["where"] += ["teacher_id" => Auth::user()->staff->id];
         
            $timetable = new \App\Modules\Timetable\Model\Timetable();
            $options["cols"] = [
                "timetables.*",
            ];
            $classes      = $timetable->find($options);
            $total_classes      = $classes->count();
            $options["count"] = true;
            $options["where"] += ["is_online" => 1];
            $total_online     = $timetable->find($options);
            
            //Staff List
            $staffs            = (new \App\Modules\Staff\Model\Staff())->find(["limit" => 6,"whereNot" => ["id" => Auth::user()->staff->id]]);
            $weekDays = General::getWeekDays();
            return View('teacher::dashboard', ['moduleName' => $this->moduleName,"total_classes" => $total_classes, "total_online" => $total_online, 
                "classes" => $classes,"staffs" => $staffs, 'weekDays' => $weekDays]);
        }
        if(Auth::user()->role_id == \App\Models\Role::ROLE_STUDENT){
            return redirect("lectures");
            return View('student::dashboard', ['moduleName' => $this->moduleName]);
        }
        if(Auth::user()->role_id == \App\Models\Role::ROLE_ADMIN){
            return redirect("lectures");
        }
        $total_schools  =  \App\Models\Account::all()->count();
        $total_users  =  SaasUser::all()->count();
        $res = \App\Models\Account::all()
              ->groupBy(function($val) {
              return \Carbon\Carbon::parse($val->created_at)->format('Y');
        });
        $years = range(date("Y") - 10, date("Y"));
        foreach($years as $key => $row){
            $year_schools[$row]  = 0;
            if(isset($res[$row])){
                $year_schools[$row] = count($res[$row]);
            }
        }
        ksort($year_schools, SORT_NUMERIC); 
        $year_schools = array_values($year_schools);
        return View('saasuser::dashboard', ['moduleName' => $this->moduleName,"total_schools" => $total_schools,"total_users" => $total_users,
            "year_schools" => $year_schools, "years" => $years]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        return View('saasuser::createOrUpdate')->with('moduleName', $this->moduleName);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param StoreTruck $request
     * @return RedirectResponse
     */
    public function store(StoreSaasUser $request)
    {
        $saasUser = new SaasUser($request->all());
        if ($request->hasFile("avatar")) {
            $saasUser->avatar = SaasUser::uploadAvatar($request);
        }
        $saasUser->save();

        Session::flash('success',
            trans('locale.success_add_msg', array('module_name' => "Admin")));

        General::saasLog('SL000202', [
            'action_module' => $this->moduleName,
            'parent_id'     => $saasUser->id,
            'event_data'    => ['name' => $saasUser->name, 'url' => route($this->moduleName.'.edit', $saasUser->id)]
        ]);

        return redirect()->route($this->moduleName.'.index');
    }

    /**
     * Display the specified resource.
     *
     * @param SaasUser $saasUser
     * @return Factory|View
     */
    public function show(SaasUser $saasUser)
    {
        General::saasLog('SL000205', [
            'action_module' => $this->moduleName,
            'parent_id'     => $saasUser->id,
            'event_data'    => ['name' => $saasUser->name, 'url' => route($this->moduleName.'.edit', $saasUser->id)]
        ]);

        return View('saasuser::show', compact('saasUser'))->with('moduleName', $this->moduleName);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param SaasUser $saasUser
     * @return Factory|View
     */
    public function edit(SaasUser $saasUser)
    {
        return View('saasuser::createOrUpdate', compact('saasUser'))
            ->with('moduleName', $this->moduleName);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param StoreTruck $request
     * @param Truck $truck
     * @return RedirectResponse
     */
    public function update(StoreSaasUser $request, SaasUser $saasUser)
    {
        $saasUser->fill($request->all());

        if ($request->hasFile("avatar")) {
            $saasUser->avatar = SaasUser::uploadAvatar($request);
        } else {
            if ($request->get("remove_avatar") == 1) {
                $saasUser->avatar = null;
            }
        }

        if (!empty($request->input('confirm_password'))) {
            $saasUser->password = Hash::make($request->get('confirm_password'));
        } else {
            unset($saasUser->password);
        }

        $saasUser->save();

        Session::flash('success',
            trans('locale.success_update_msg', array('module_name' => "Admin")));

        General::saasLog('SL000203', [
            'action_module' => $this->moduleName,
            'parent_id'     => $saasUser->id,
            'event_data'    => ['name' => $saasUser->name, 'url' => route($this->moduleName.'.edit', $saasUser->id)]
        ]);

        return redirect()->route($this->moduleName.'.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param SaasUser $saasUser
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws Exception
     */
    public function destroy(SaasUser $saasUser)
    {
        General::saasLog('SL000205', [
            'action_module' => $this->moduleName,
            'parent_id'     => $saasUser->id,
            'event_data'    => ['name' => $saasUser->name]
        ]);

        Session::flash('success',
            trans('locale.success_delete_msg', array('module_name' => "Admin")));
        $saasUser->delete();

        return redirect()->route($this->moduleName.'.index');
    }
}
