<?php

namespace Modules\Organization\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Traits\UploadMedia;
use App\User;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Modules\CourseSetting\Entities\Course;
use Modules\RolePermission\Entities\RolePermission;
use Yajra\DataTables\Facades\DataTables;

class OrganizationController extends Controller
{
    use UploadMedia;

    public function index()
    {
        try {
            return view('organization::organization.index');
        } catch (\Exception $e) {
            Toastr::error(trans('common.Operation failed'), trans('common.Failed'));
            return redirect()->back();
        }
    }

    public function create()
    {
        try {
            return view('organization::organization.create');
        } catch (\Exception $e) {
            Toastr::error(trans('common.Operation failed'), trans('common.Failed'));
            return redirect()->back();
        }
    }

    public function edit($id)
    {
        try {
            $data['user'] = User::with('currency', 'userInfo', 'userInfo.timezone', 'userEducations', 'userSkill', 'userPayoutAccount')->findOrFail($id);

            return view('organization::organization.create', $data);
        } catch (\Exception $e) {
            Toastr::error(trans('common.Operation failed'), trans('common.Failed'));
            return redirect()->back();
        }
    }


    public function store(Request $request)
    {
        if (saasPlanCheck('instructor')) {
            Toastr::error(trans('frontend.You have reached instructor limit'), trans('common.Failed'));
            return redirect()->route('organization.index');
        }
        Session::flash('type', 'store');

        if (demoCheck()) {
            return redirect()->back();
        }


        $rules = [
            'name' => 'required',
            'phone' => 'nullable|string|regex:/^([0-9\s\-\+\(\)]*)$/|min:5|unique:users,phone',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:8|confirmed',
        ];


        $this->validate($request, $rules, validationMessage($rules));


        try {

            $user = new User;
            $user->name = $request->name;
            $user->email = $request->email;
            $user->username = null;
            $user->password = bcrypt($request->password);
            $user->about = $request->about;
            $user->dob = getPhpDateFormat($request->dob);

            if (empty($request->phone)) {
                $user->phone = null;
            } else {
                $user->phone = $request->phone;
            }
            $user->language_id = Settings('language_id');
            $user->language_code = Settings('language_code');
            $user->language_name = Settings('language_name');
            $user->language_rtl = Settings('language_rtl');
            $user->country = Settings('country_id');
            $user->facebook = $request->facebook;
            $user->twitter = $request->twitter;
            $user->linkedin = $request->linkedin;
            $user->instagram = $request->instagram;
            $user->added_by = Auth::id();

            $user->email_verify = 1;
            $user->email_verified_at = now();
            if (isModuleActive('LmsSaas')) {
                $user->lms_id = app('institute')->id;
            } else {
                $user->lms_id = 1;
            }
            if ($request->file('image') != "") {
                $file = $request->file('image');
                $user->image = $this->saveImage($file);
            }
            $user->role_id = 5;
            $user->referral = generateUniqueId();
            $user->special_commission = null;
            $user->save();
            if ($request->image) {
                $user->image = $this->generateLink($request->image, $user->id, get_class($user), 'image');
            }
            $user->save();

            applyDefaultRoleToUser($user);
            assignStaffToUser($user);

            Toastr::success(trans('common.Operation successful'), trans('common.Success'));
            return redirect()->route('organization.index');
        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }


    public function update(Request $request)
    {
        Session::flash('type', 'update');

        if (demoCheck()) {
            return redirect()->back();
        }
        $rules = [
            'name' => 'required',
            'phone' => 'nullable|string|regex:/^([0-9\s\-\+\(\)]*)$/|min:1|unique:users,phone,' . $request->id,
            'email' => 'required|email|unique:users,email,' . $request->id,
            'password' => 'bail|nullable|min:8|confirmed',

        ];

        $this->validate($request, $rules, validationMessage($rules));

        $user = User::findOrFail($request->id);

        try {

            $user->name = $request->name;
            $user->email = $request->email;
            $user->username = null;
            $user->facebook = $request->facebook;
            $user->twitter = $request->twitter;
            $user->linkedin = $request->linkedin;
            $user->instagram = $request->instagram;
            $user->about = $request->about;
            $user->dob = getPhpDateFormat($request->dob);
            if (empty($request->phone)) {
                $user->phone = null;
            } else {
                $user->phone = $request->phone;
            }
            if ($request->password) {
                $user->password = bcrypt($request->password);
            }
            $user->image = null;
            $user->save();

            $this->removeLink($user->id, get_class($user));
            if ($request->image) {
                $user->image = $this->generateLink($request->image, $user->id, get_class($user), 'image');
            }
            $user->save();


            Toastr::success(trans('common.Operation successful'), trans('common.Success'));
            return redirect()->route('organization.index');

        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }


    public function destroy(Request $request)
    {
        if (demoCheck()) {
            return redirect()->back();
        }

        $rules = [
            'id' => 'required'
        ];

        $this->validate($request, $rules, validationMessage($rules));

        $user = User::with('courses')->findOrFail($request->id);
        try {
            if (count($user->courses) > 0) {
                Toastr::error($user->name . ' has course. Please remove it first', 'Failed');
                return back();
            }
            $user->delete();
            Toastr::success(trans('common.Operation successful'), trans('common.Success'));
            return redirect()->route('organization.index');

        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function getAllOrganizationData(Request $request)
    {

        $with = [];

        $query = User::with('totalOrganizationUsers', 'courses');

        if (isModuleActive('LmsSaas')) {
            $query->where('lms_id', app('institute')->id);
        } else {
            $query->where('lms_id', 1);
        }
        if (isModuleActive('UserType')) {
            $query->whereHas('userRoles', function ($q) {
                $q->where('role_id', 5);
            });
        } else {
            $query->where('role_id', 5);
        }
        $query->with($with);

        return Datatables::of($query)
            ->addIndexColumn()
            ->editColumn('name', function ($query) {
                return view('backend.my_panel._user_td', ['row' => $query]);
            })
            ->addColumn('students', function ($query) {
                return translatedNumber($query->totalOrganizationUsers->where('role_id', 3)->count());
            })
            ->addColumn('instructors', function ($query) {
                return translatedNumber($query->totalOrganizationUsers->where('role_id', 2)->count());
            })
            ->addColumn('courses', function ($query) {
                return translatedNumber(Course::whereHas('user', function ($q) use ($query) {
                    $q->where('organization_id', $query->id);
                    $q->orWhere('user_id', $query->id);
                })->where('type', 1)->count());
            })
            ->addColumn('quizzes', function ($query) {
                return translatedNumber(Course::whereHas('user', function ($q) use ($query) {
                    $q->where('organization_id', $query->id);
                    $q->orWhere('user_id', $query->id);
                })->where('type', 2)->count());
            })
            ->addColumn('classes', function ($query) {
                return translatedNumber(Course::whereHas('user', function ($q) use ($query) {
                    $q->where('organization_id', $query->id);
                    $q->orWhere('user_id', $query->id);
                })->where('type', 3)->count());
            })
            ->editColumn('created_at', function ($query) {
                return showDate($query->created_at);
            })
            ->addColumn('status', function ($query) {
                return view('organization::organization.partials._td_status', compact('query'));

            })->addColumn('action', function ($query) {
                return view('organization::organization.partials._td_action', compact('query'));

            })->rawColumns(['status', 'name', 'action'])
            ->make(true);
    }


    public function generateDefaultOrganizationPermission()
    {
        $path = Storage::path('organization.php');
        $organization_permission_route = RolePermission::with(['permission'])->where('role_id', 5)->get();
        $output = [];
        foreach ($organization_permission_route as $permission) {
            $output[] = $permission->permission->route;
        }
        if (file_exists($path)) {
            file_put_contents($path, '');
        }

        file_put_contents($path, '<?php return ' . var_export($output, true) . ';');
    }
}
