<?php

namespace App\Http\Controllers\Setting;

use DataTables;
use Carbon\Carbon;
use App\Models\Bank;
use App\Models\User;
use App\Models\State;
use App\Models\UserDetail;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Route;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = User::role('finance')->get();
        

        if ($request->ajax()) {
            return Datatables::of($data)
            ->addIndexColumn()   
            ->addColumn('user', function($data){
                            
                return '<div class="d-flex align-items-center">
                            <!--begin:: Avatar -->
                            <div class="symbol symbol-circle symbol-50px overflow-hidden">
                                <a href="javascript:void(0);">
                                    <div class="symbol-label">
                                        <img src="'.asset('media/avatars/'.$data->avatar) .'" class="w-100" />
                                    </div>
                                </a>
                            </div>
                            <!--end::Avatar-->
                            <div class="ms-5">
                                <!--begin::Title-->
                                <span class="text-gray-800 text-hover-primary fs-5 fw-bold">'.$data->name.'</span>
                                <!--end::Title-->
                            </div>
                        </div>';
                
            })    
            ->addColumn('role', function($data){
                return '<span class="badge badge-primary">'.ucfirst($data->getRoleNames()->implode(',')).'</span>';
            })      
            ->addColumn('status', function($data){

                return '<div class="badge badge-light-'.$data->user_status->color.'">'.$data->user_status->name.'</div>';
            
            })     
            ->addColumn('action', function($data) {

                return '<a href="'.route('edit-user', $data->id).'" class="btn btn-sm btn-light btn-icon btn-hover-success mr-2" title="Edit details">
                        <span class="svg-icon svg-icon-md svg-icon-success">
                            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1">
                                <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                                    <rect x="0" y="0" width="24" height="24"/>
                                    <path d="M8,17.9148182 L8,5.96685884 C8,5.56391781 8.16211443,5.17792052 8.44982609,4.89581508 L10.965708,2.42895648 C11.5426798,1.86322723 12.4640974,1.85620921 13.0496196,2.41308426 L15.5337377,4.77566479 C15.8314604,5.0588212 16,5.45170806 16,5.86258077 L16,17.9148182 C16,18.7432453 15.3284271,19.4148182 14.5,19.4148182 L9.5,19.4148182 C8.67157288,19.4148182 8,18.7432453 8,17.9148182 Z" fill="#000000" fill-rule="nonzero"\ transform="translate(12.000000, 10.707409) rotate(-135.000000) translate(-12.000000, -10.707409) "/>
                                    <rect fill="#000000" opacity="0.3" x="5" y="20" width="15" height="2" rx="1"/>
                                </g>
                            </svg>
                        </span>
                    </a>';

                
            })
            ->escapeColumns([])
            //->rawColumns(['action'])
            ->make(true);
        } 

        return view('setting.user.index'); 
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $states = State::all();
        $banks = Bank::all();

        return view('setting.user.create', [
            'states' => $states,
            'banks' => $banks
        ]); 
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $val_data = $request->validate([
            'role' => 'required',
            'name' => 'required',
            'nric_number' => 'required',
            'phone_number' => 'required',
            'email' => 'required|email|unique:users,email'
        ]);

        $user = User::create([
            'name' => $request->name,
            'nric_number' => $request->nric_number,
            'phone_number' => $request->phone_number,
            'email' =>$request->email,
            'username' => $request->nric_number,
            'password' =>Hash::make($request->password),
            'user_status_id' => 2,
            'avatar' => 'blank.png'
        ]);

        UserDetail::create([
            'user_id' => $user->id,
            'bank_id' => 1,
            'address' =>$request->address,
            'postcode' =>$request->postcode,
            'city' =>$request->city,
            'state' =>$request->state
        ]);

        $user->assignRole($request->role);

        $token = Str::random(64);

        DB::table('password_resets')->insert([
            'email' => $request->email, 
            'token' => $token, 
            'created_at' => Carbon::now()
        ]);

        $data = array(
            'token' => $token,
            'username' => $request->name,
            'id' => $user->id
        );
            
        Mail::send('mail.first-login', $data, function($message) use($request){
            $message->to($request->email);
            $message->subject('Setup Your Account');
        });

        return redirect()->route('index-user')->with('success', 'Registration Successfully!');
    }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user = User::findorfail($id);

        $states = State::all();
        $banks = Bank::all();

        return view('setting.user.edit', [
            'states' => $states,
            'banks' => $banks,
            'user' => $user
        ]); 
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {   $user = User::findorfail($id);

        if($user->email ==  $request->email)
        {
            $val_data = $request->validate([
                //'role' => 'required',
                'name' => 'required',
                'nric_number' => 'required',
                'phone_number' => 'required',
                'email' => 'required'
            ]);
        }
        else{
            $val_data = $request->validate([
                //'role' => 'required',
                'name' => 'required',
                'nric_number' => 'required',
                'phone_number' => 'required',
                'email' => 'required|email|unique:users,email'
            ]);
        }

        

        /* if($request->role != $user->getRoleNames()->implode(',') )
        {
            DB::table('model_has_roles')->where('model_id',$id)->delete();
            $user->assignRole($request->role); 
        } */

        $user = User::where('id', $id)
        ->update([
            'name' => $request->name,
            'nric_number' => $request->nric_number,
            'phone_number' => $request->phone_number,
            'email' =>$request->email,
        ]);

        UserDetail::where('user_id', $id)
        ->update([
            'address' =>$request->address,
            'postcode' =>$request->postcode,
            'city' =>$request->city,
            'state' =>$request->state
        ]);

        return back()->with('success', 'User profile has been updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
