<?php

namespace App\Modules\Staff\Model;

use App\Facades\General;
use App\Models\Role;
use App\Models\Tenant;
use App\Models\User;
use App\Modules\Student\Model\ClassSection;
use App\Modules\Student\Model\Section;
use App\Modules\Student\Model\Student;
use Exception;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;

class Staff extends Tenant
{

    use SoftDeletes;

    protected $table = 'staffs';
    protected $fillable = ['user_id',
        'staff_id',
        'role',
        'designation_id',
        'department_id',
        'father_name',
        'mother_name',
        'joining_date',
        'marital_status',
        'qualification',
        'work_exp',
        'note',
        'epf_no',
        'basic_salary',
        'contract_type',
        'work_shift',
        'location',
        'alloted_leave_1',
        'alloted_leave_2',
        'alloted_leave_3',
        'account_title',
        'bank_account_no',
        'bank_name',
        'ifsc_code',
        'bank_branch',
        'fb_url',
        'twitter_url',
        'linkedin_url',
        'instagram_url',
        'resume',
        'document',
        'view_contact',
        'student_action',
        'joining_letter'];

    /**
     * @return BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id')->withDefault();
    }

    /**
     * @return BelongsTo
     */
    public function role()
    {
        return $this->belongsTo(Role::class, 'role')->withDefault();
    }
    /**
     * @return BelongsTo
     */
    public function designation()
    {
        return $this->belongsTo(\App\Modules\Designation\Model\Designation::class, 'designation_id')->withDefault();
    }
    /**
     * @return BelongsTo
     */
    public function department()
    {
        return $this->belongsTo(\App\Modules\Department\Model\Department::class, 'department_id')->withDefault();
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
     public function staffClass(){
        return $this->hasOne(ClassSection::class, 'staff_id');
     }

    /**
     * Return all the staff details
     *
     * @return JsonResponse
     * @throws Exception
     */
    public static function getStaffs()
    {
        $options           = array();
        $options['with']   = ["user"];
        $options['object'] = true;
        $staff             = new Staff();
        $model             = $staff->find($options);

        return DataTables::eloquent($model)
            ->addColumn('name', function (Staff $staff) {
                return $staff->user->name;
            })
            ->addColumn('contact_no', function (Staff $staff) {
                return $staff->user->mobile_number;
            })
            ->addColumn('designation', function (Staff $staff) {
                return $staff->designation->title;
            })
            ->addColumn('class', function (Staff $staff) {
                return ($staff->staffClass->studentClass->title) ?? '';
            })
            ->addColumn('email', function (Staff $staff) {
                return $staff->user->email;
            })
            ->addColumn('action', function (Staff $staff) {
                return $staff->returnAction('staffs', $staff, ['show', 'edit', 'destroy']);
            })
            ->rawColumns(['action'])
            ->make(true);
    }

    /**
     * Save student details into user table
     *
     * @param $request
     * @param bool $update
     * @return User|mixed|object|null
     */
    public static function addUpdateStaffUser($request, $update = false)
    {
        $user   = null;
        $insert = false;
        // Request to update data
        if ($update == true) {
            $user = (new User())->findById($request->user_id);
        }
        if ($user == null) {
            $user   = new User();
            $insert = true;
        }
        // match the requested fields with resource
        $user->fill($request->all());
        if ($insert == true) {
            $user->created_by = Auth::user()->id;
            $user->password = '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi'; // password
        } else {
            $user->updated_by = Auth::user()->id;
        }
        $user->account_id = Config::get('account.id');
        if (!$update) {
            $user->role_id    = $request->role;
        }
//        $user->name       = $request->first_name . ' ' . $request->last_name;

        $user->name       = $request->name;
        // Upload image
        $avatar = self::uploadStaffAvatars($request, 'avatar');
        if ($avatar!=null){
            $user->avatar = $avatar;
        }

        $user->save();

        return $user;
    }

    /**
     * Add student details
     *
     * @param $request
     * @param $user
     * @param $guardianUser
     * @param int $staff
     * @return Student|Model|int
     */
    public static function addUpdateStaff($request, $user, $staff = 0)
    {

        $staff  = (new Staff())->findById($staff);
        $insert = false;
        if ($staff == null) {
            $staff  = new Staff();
            $insert = true;
        }
        $staff->fill($request->all());
        if ($insert == true) {
            $staff->created_by = Auth::user()->id;
        } else {
            $staff->updated_by = Auth::user()->id;
        }


        if (isset($request->view_contact)) {
            $staff->view_contact = ($request->view_contact == 'on' || $request->view_contact == 1 ? 1 : 0);
        }else{
            $staff->view_contact = 0;
        }

        if (isset($request->student_action)) {
            $staff->student_action = ($request->student_action == 'on' || $request->student_action == 1 ? 1 : 0);
        }else{
            $staff->student_action = 0;
        }

        $staff->user_id    = $user->id;
        $staff->account_id = Config::get('account.id');
        $staff->save();

        return $staff;
    }

    /**
     * Upload file on server
     *
     * @param $request
     * @param $fileName
     * @return mixed
     */
    public static function uploadStaffAvatars($request, $fileName)
    {
        if ($request->hasFile($fileName)) {

            return General::uploadAvatar($request, $fileName);
        }

        return null;
    }

    /**
     * Return teachers
     *
     * @return array
     */
    public static function getTeachers()
    {
        $options['where']  = ['staffs.role' => Role::ROLE_TEACHER];
        $options['select'] = ['id'];
        $staffs            = (new Staff())->find($options);

        $optionValues = [];
        foreach ($staffs as $staff) {
            $optionValues[$staff->id] = $staff->user->name;
        }
        asort($optionValues);

        return $optionValues;
    }
}
