<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserDetail;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\CustomExport;
use App\Helpers\Helper;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class UserDetailController extends Controller
{
    public function __construct()
    {
        // $this -> middleware('permission:user-list', ['only' => ['index']]);
        // $this -> middleware('permission:user-list')->except(['index']);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('Admin.users.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $roles = Role::pluck('name','name')->all();
        return view('Admin.users.create',compact('roles'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        
        $input = $request->input();
        unset($input['_token']);
        
        // $findRole = Department::with(['role_detail'])->find($input['department_id']);
        // $role_id = isset($findRole->role_detail->id)?$findRole->role_detail->id:0;

        $user_name = isset($input['user_name'])?$input['user_name']:"";
        $password = isset($input['password'])?$input['password']:"";

        $isUserNameExist = User::where(array("username"=>$user_name))->first();
        if(!empty($isUserNameExist)){
            //User Exist
            Helper::failarMsg("custom", "Username is taken! Try another");
            return redirect()->back()->withInput();
        }
        //Create new user
        $userInput = array(
            'name' => (isset($input['first_name'])?$input['first_name']." ":"" (isset($input['last_name'])?$input['last_name']:"")), 
            'status' => (isset($input['status'])?1:0), 
            'username' => $user_name,
            // 'user_type' => $request->input('roles'),
            'unique_id' => strtoupper(uniqid()).time(),
            'password' => bcrypt($password)
        );
        if($request->hasfile('profile'))
        {
            $image = $request->profile;
            $fileName = date('dmyhisa') . '-' . $image->getClientOriginalName();
            $fileName = str_replace(" ", "-", $fileName);
            $destinationPath = public_path('/images/user/');
            
            if (!is_dir($destinationPath)) {
                mkdir($destinationPath, 0777, TRUE);
                @chmod($destinationPath,0777);
            }
            $image->move($destinationPath, $fileName);
            $userInput['profile_photo_path'] = $fileName;
        }
        $user = User::create($userInput);
        $user->assignRole($request->input('roles'));

        $affactableArray = array(
            "user_id" =>  $user->id,
            "title" =>  isset($input['title'])?$input['title']:"",
            "first_name" =>  isset($input['first_name'])?$input['first_name']:"",
            "last_name" =>  isset($input['last_name'])?$input['last_name']:"",
            "dob" =>  !empty($input['dob'])?date("Y-m-d",strtotime(str_replace("/","-",$input['dob']))):"",
            "join_date" =>  !empty($input['join_date'])?date("Y-m-d",strtotime(str_replace("/","-",$input['join_date']))):"",
            "leaving_date" =>  !empty($input['leaving_date'])?date("Y-m-d",strtotime(str_replace("/","-",$input['leaving_date']))):"",
            "reporting_user_id" =>  isset($input['reporting_user_id'])?$input['reporting_user_id']:NULL,
            "address" =>  isset($input['address'])?$input['address']:"",
            "pincode" =>  isset($input['pincode'])?$input['pincode']:"",
            "country_id" =>  isset($input['country_id'])?$input['country_id']:"",
            "state_id" =>  isset($input['state_id'])?$input['state_id']:"",
            "city_id" =>  isset($input['city_id'])?$input['city_id']:"",
            "official_email" =>  isset($input['official_email'])?$input['official_email']:"",
            "personal_email" =>  isset($input['personal_email'])?$input['personal_email']:"",
            "official_contact_no" =>  isset($input['official_contact_no'])?$input['official_contact_no']:"",
            "personal_contact_no" =>  isset($input['personal_contact_no'])?$input['personal_contact_no']:"",
            "emergency_contact_no" =>  isset($input['emergency_contact_no'])?$input['emergency_contact_no']:"",
            // "access_type" =>  isset($input['access_type'])?1:1
        );

        $userDetail = UserDetail::create($affactableArray);
        Helper::successMsg("insert", "User");
        return redirect()->route('user.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Branch  $branch
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Branch  $branch
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = User::with(['userDetail','roles','userDetail.countryName','userDetail.stateName','userDetail.cityName','userDetail.reportUser'])->find(decrypt($id));
        $roles = Role::pluck('name','name')->all();
        $userRole = $data->roles->pluck('name')->all();
        return view('Admin.users.edit', ['data' => $data,'roles'=>$roles,'userRole'=>$userRole]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Branch  $branch
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // dd($request);
        $input = $request->input();
        unset($input['_token']);
        unset($input['_method']);
        
        // $findRole = Department::with(['role_detail'])->find($input['department_id']);
        // $role_id = isset($findRole->role_detail->id)?$findRole->role_detail->id:0;

        $user_name = isset($input['user_name'])?$input['user_name']:"";
        $password = isset($input['password'])?$input['password']:"";

        $isUserNameExist = User::where(array("username"=>$user_name))->where(array(["id", "!=", $id]))->first();
        if(!empty($isUserNameExist)){
            //User Exist
            Helper::failarMsg("custom", "Username is taken! Try another");
            return redirect()->back()->withInput();
        }
        //Update user
        $user = User::find($id);

        

        $updateData = array(
            'name' => (isset($input['first_name'])?$input['first_name']." ":"" (isset($input['last_name'])?$input['last_name']:"")), 
            'status' => (isset($input['status'])?1:0), 
            'username' => $user_name
        );
        if($password != ""){
            $updateData['password'] = bcrypt($password);
        }
        if($user->id != Auth::user()->id){
            // $updateData['user_type'] = $request->input('roles');
        }
        if($request->hasfile('profile'))
        {
            $destinationPath = public_path('/images/user/');
            File::delete($destinationPath.$user->profile_photo_path);

            $image = $request->profile;
            $fileName = date('dmyhisa') . '-' . $image->getClientOriginalName();
            $fileName = str_replace(" ", "-", $fileName);
            

            if (!is_dir($destinationPath)) {
                mkdir($destinationPath, 0777, TRUE);
                @chmod($destinationPath,0777);
            }
            $image->move($destinationPath, $fileName);
            $updateData['profile_photo_path'] = $fileName;
        }
        User::where("id", $id)->update($updateData);
        DB::table('model_has_roles')->where('model_id',$id)->delete();
        $user = User::find($id);
        $user->assignRole($request->input('roles'));
        
        $affactableArray = array(
            "title" =>  isset($input['title'])?$input['title']:"",
            "first_name" =>  isset($input['first_name'])?$input['first_name']:"",
            "last_name" =>  isset($input['last_name'])?$input['last_name']:"",
            "dob" =>  !empty($input['dob'])?date("Y-m-d",strtotime(str_replace("/","-",$input['dob']))):"",
            "join_date" =>  !empty($input['join_date'])?date("Y-m-d",strtotime(str_replace("/","-",$input['join_date']))):"",
            "leaving_date" =>  !empty($input['leaving_date'])?date("Y-m-d",strtotime(str_replace("/","-",$input['leaving_date']))):"",
            "reporting_user_id" =>  isset($input['reporting_user_id'])?$input['reporting_user_id']:NULL,
            "address" =>  isset($input['address'])?$input['address']:"",
            "pincode" =>  isset($input['pincode'])?$input['pincode']:"",
            "country_id" =>  isset($input['country_id'])?$input['country_id']:"",
            "state_id" =>  isset($input['state_id'])?$input['state_id']:"",
            "city_id" =>  isset($input['city_id'])?$input['city_id']:"",
            "official_email" =>  isset($input['official_email'])?$input['official_email']:"",
            "personal_email" =>  isset($input['personal_email'])?$input['personal_email']:"",
            "official_contact_no" =>  isset($input['official_contact_no'])?$input['official_contact_no']:"",
            "personal_contact_no" =>  isset($input['personal_contact_no'])?$input['personal_contact_no']:"",
            "emergency_contact_no" =>  isset($input['emergency_contact_no'])?$input['emergency_contact_no']:"",
            // "access_type" =>  isset($input['access_type'])?1:1
        );

        $userDtl = UserDetail::where("user_id", $id)->first();
        if(empty($userDtl)){
            $userDetail = UserDetail::create($affactableArray);
        }else{
            $userDetail = UserDetail::where("user_id", $id)->update($affactableArray);
        }
        
        Helper::successMsg("update", "User");
        return redirect()->route('user.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Branch  $branch
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        User::where("id",decrypt($id))->delete();
        Helper::successMsg("delete", "User");
        return redirect()->route('user.index');
    }
    public function delete($id)
    {
        User::where("id",decrypt($id))->delete();
        Helper::successMsg("delete", "User");
        return redirect()->route('user.index');
    }
    public function status(Request $request, $id)
    {
        User::where("id",decrypt($id))->update(array("status"=>$request->status,"updated_at"=>date("Y-m-d H:i:s")));
        Helper::successMsg("Status", "User");
        return redirect()->route('user.index');
    }
    public function data(Request $request)
    {
        $tableData = User::with(['userDetail'])->orderBy('id', 'desc')->get();
        $datatable = DataTables::of($tableData)
            ->addIndexColumn()
            ->addColumn('personal_contact_no', function ($val) {
                $personal_contact_no = !empty($val->userDetail)?$val->userDetail->personal_contact_no:"";
                return $personal_contact_no;
            })
            ->addColumn('emergency_contact_no', function ($val) {
                $emergency_contact_no = !empty($val->userDetail)?$val->userDetail->emergency_contact_no:"";
                return $emergency_contact_no;
            })
            ->addColumn('address', function ($val) {
                $address = !empty($val->userDetail)?$val->userDetail->address:"";
                return $address;
            })
            
            ->addColumn('status', function ($val) {
                $encrypt = encrypt($val->id);
                $status = "";
                
                if($val->status == "0"){
                    //disable
                    $status .= '<button style="" class="btn btn-sm status_btn btn-danger btn-link" data-next_click="1" data-status_link="' . route('user.status', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Deactive"><i class="fas fa-times" aria-hidden="true"></i></button>';
                }else{
                    $status .= '<button style="" class="btn btn-sm status_btn btn-success btn-link" data-next_click="0" data-status_link="' . route('user.status', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Active"><i class="fas fa-check" aria-hidden="true"></i></button>';
                }
                return $status;
            })
            ->addColumn('action', function ($val) {
                $encrypt = encrypt($val->id);
                $action = "";
                
                $action .= '<a class="btn btn-sm btn-primary btn-link" href="' . route('user.edit', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Edit"><i class="fas fa-pen" aria-hidden="true"></i></a>';
                $action .= '<button style="" class="btn btn-sm delete_btn btn-danger btn-link" data-delete_link="' . route('user.delete', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Delete"><i class="fas fa-trash" aria-hidden="true"></i></button>';
                
                return $action;
            })
            ->rawColumns(['personal_contact_no','emergency_contact_no','address','status','action'])
            ->make(true);
        return $datatable;
    }
    public function export()
    {
        $data = User::with(['userDetail','userDetail.countryName','userDetail.stateName','userDetail.cityName'])->orderBy('id', 'desc')->get();
        return Excel::download(new CustomExport("Admin.users.export", ["data"=>$data, "title"=>"User"]),  'user.xlsx');
    }
}
