<?php



namespace App\Http\Controllers;



use App\Mail\SendEmailToVendor;

use Illuminate\Http\Request;

use Spatie\Permission\Models\Role;

use Spatie\Permission\Models\Permission;

use Illuminate\Support\Facades\Storage;

use App\Models\User;

use App\Models\Branch;

use App\Models\Department;

use App\Imports\ImportUser;

use App\Exports\ExportUser;

use App\Http\Requests\UserRequest;

use Maatwebsite\Excel\Facades\Excel;

use Auth, DB, Str, Mail, Validator, File, DataTables, Exception;



class AddVendorController extends Controller{

    /** construct */

        public function __construct(){

            $this->middleware('permission:addvendor-create', ['only' => ['create']]);

            $this->middleware('permission:addvendor-edit', ['only' => ['edit']]);

            $this->middleware('permission:addvendor-view', ['only' => ['view']]);

            $this->middleware('permission:addvendor-delete', ['only' => ['delete']]);

        }

    /** construct */



    /** index */

        public function index(Request $request){

            if ($request->ajax()) {

                $data = User::orderBy('id', 'desc')->where('status','!=','deleted')->whereHas('roles', function ($query) {

                    $query->where('id', 41);})->get();

                

                return Datatables::of($data)

                    ->addIndexColumn()

              ->addColumn('branch', function ($data) {

        $branchIds = explode(',', $data->branch);

        $branchNames = Branch::whereIn('id', $branchIds)->pluck('name')->implode(', ');

        return $branchNames;

    })

                    ->addColumn('action', function ($data) {

                        $return = '<div class="btn-group">';



                        if (auth()->user()->can('addvendor-view')) {

                            $return .=  '<a href="'.route('vendor.a_view', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">

                                                <i class="fa fa-eye"></i>

                                            </a> &nbsp;';

                        }



                        if (auth()->user()->can('addvendor-edit')) {

                            $return .= '<a href="'.route('vendor.a_edit', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">

                                                <i class="fa fa-edit"></i>

                                            </a> &nbsp;';

                        }



                        if (auth()->user()->can('addvendor-delete')) {

                            $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">

                                                <i class="fa fa-bars"></i>

                                            </a> &nbsp;

                                            <ul class="dropdown-menu">

                                            <li><a class="dropdown-item" href="' . route('send_email', ['id' => base64_encode($data->id)]) . '" data-status="active">Send Email</a></li>

                                                <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>

                                                <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>

                                                <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="deleted" data-id="' . base64_encode($data->id) . '">Delete</a></li>

                                            </ul>';

                        }



                        $return .= '</div>';



                        return $return;

                    })

            

                    ->editColumn('status', function ($data) {

                        

                        if ($data->status == 'active') {

                            return '<span class="badge badge-pill badge-success">Active</span>';

                        } else if ($data->status == 'inactive') {

                            return '<span class="badge badge-pill badge-warning">Inactive</span>';

                        } else if ($data->status == 'deleted') {

                            return '<span class="badge badge-pill badge-danger">Deleted</span>';

                        } else {

                            return '-';

                        }

                    })



                    ->editColumn('name_of_company', function ($data) {

                        

                        return $data->name_of_company;

                    

                })



                    ->editColumn('role', function ($data) {

                        if(!empty($data->roles->where('id', 41)->first()->name)){

                            return ucfirst(str_replace('_', ' ', $data->roles->first()->name));

                        }else{

                            return null;

                        }

                        

                    })

                    ->editColumn('department', function ($data) {

                        $department = Department::where(['id' => $data->department_id])->first();

                        if(!empty($department)){

                            return $department['name'];

                        }else{

                            return '';

                        }

                        

                        

                    })



                  

                    



                    ->rawColumns([ 'name_of_company','role', 'action', 'status','branch'])

                    ->make(true);

            }

            

            return view('add_vendor.index');

        }

    /** index */

    

    /** Trash */

       



    /** create */

        public function create(Request $request){

            $roles = Role::all();

            $department = Department::all();

  $branch = Branch::where(['status' => 'active'])->get();

            return view('add_vendor.create')->with(['department'=>$department,'roles' => $roles,'branch' => $branch]);

        }

    /** create */



    /** insert */

        public function insert(UserRequest $request){



            if($request->ajax()){ return true; }

            $password = 'Abcd@123?';



            if($request->password != '' && $request->password != NULL)

                $password = $request->password;

if(!empty($request->branch)){

                $request->branch = implode(',', $request->branch);

            }else{

                $request->branch = '';

            }

           



            $data = [

               

                'email' => $request->email,

                'contact_number' => $request->contact_number,

                'department_id' => $request->department,

                 'branch' => $request->branch,

                'name_of_company' => $request->name_of_company,

                'pan_no' => $request->pan_no,

                'status' => 'active',

                'password' => bcrypt($password),

            

                'created_at' => date('Y-m-d H:i:s'),

                'created_by' => auth()->user()->id,

                'updated_at' => date('Y-m-d H:i:s'),

                'updated_by' => auth()->user()->id

            ];



            DB::beginTransaction();

            try {

                $user = User::create($data);

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



                if($user){

                    DB::commit();

                    return redirect()->route('avendor')->with('success', 'Record inserted successfully');

                } else {

                    DB::rollback();

                    return redirect()->back()->with('error', 'Failed to insert record')->withInput();

                }

            } catch (\Throwable $th) {

                DB::rollback();

                return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();

            }

        }

    /** insert */



    /** edit */

        public function edit(Request $request, $id = ''){

            if (isset($id) && $id != '' && $id != null)

                $id = base64_decode($id);

            else

                return redirect()->route('avendor')->with('error', 'Something went wrong');



            $roles = Role::all();

            $department = Department::all();

  $branch = Branch::where(['status' => 'active'])->get();

            

            $data = User::select('id','email', 'name_of_company', 'branch', 'pan_no','contact_number', 'password','department_id')->where(['id' => $id])->first();

            return view('add_vendor.edit')->with(['data' => $data, 'branch' => $branch,'department'=>$department,'roles' => $roles]);

        }

    /** edit */



    

        



    /** update */

        public function update(UserRequest $request){

            if($request->ajax()) { return true; }



            $id = $request->id;

            $exst_rec = User::where(['id' => $id])->first();



            if(!empty($request->branch)){

                $request->branch = implode(',', $request->branch);

            }else{

                $request->branch = '';

            }

           



            $data = [

                'department_id' => $request->department,

                  'branch' => $request->branch,

                'contact_number' => $request->contact_number,

                'email' => $request->email,

                'name_of_company' => $request->name_of_company,

                'pan_no' => $request->pan_no,

                'updated_at' => date('Y-m-d H:i:s'),

                

                'updated_by' => auth()->user()->id

            ];



            if($request->password != '' && $request->password != NULL)

                $data['password'] = bcrypt($request->password);



            DB::beginTransaction();

            try {

                $update = User::where(['id' => $id])->update($data);



                if ($update) {

                    DB::table('model_has_roles')->where(['model_id' => $id])->delete();



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



                    DB::commit();

                    return redirect()->route('avendor')->with('success', 'Record updated successfully');

                } else {

                    DB::rollback();

                    return redirect()->back()->with('error', 'Failed to update record')->withInput();

                }

            } catch (\Throwable $th) {

                DB::rollback();

                return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();

            }

        }

    /** update */



    /** update_team_transfer */

        

    



    /** view */

        public function view(Request $request, $id = ''){

            if (isset($id) && $id != '' && $id != null)

                $id = base64_decode($id);

            else

                return redirect()->route('avendor')->with('error', 'Something went wrong');



            $roles = Role::all();

            $branch = Branch::where(['status' => 'active'])->get();

            $department = User::select('users.department_id', 'department.name as d_name', 'department.id as d_id')

            ->leftJoin('department','department.id','=','users.department_id')

            ->where('users.status', 'active')->get();

            $data = User::select( 'id', 'name_of_company','pan_no', 'branch' ,'email','department_id', 'contact_number', 'password')

                                ->where(['id' => $id])

                                ->first();





           

            

        return view('add_vendor.view')->with(['data' => $data, 'branch' => $branch,'roles' => $roles,'department' => $department]);

        }

    /** view */



    /** change-status */

        public function change_status(Request $request){

            if (!$request->ajax()) { exit('No direct script access allowed'); }



            if (!empty($request->all())) {

                $id = base64_decode($request->id);

                $status = $request->status;



                $data = User::where(['id' => $id])->first();



                if(!empty($data)){

                    $process = User::where(['id' => $id])->update(['status' => $status, 'updated_by' => auth()->user()->id]);

                    if($process){

                        return response()->json(['code' => 200]);

                    }else{

                        return response()->json(['code' => 201]);

                    }

                } else {

                    return response()->json(['code' => 201]);

                }

            } else {

                return response()->json(['code' => 201]);

            }

        }

    /** change-status */

    

    /** permenant-delete */

        public function Permenant_delete(Request $request){

            if (!$request->ajax()) { exit('No direct script access allowed'); }



            if (!empty($request->all())) {

                $id = base64_decode($request->id);

                $status = $request->status;



                $data = User::where(['id' => $id])->first();



                if(!empty($data)){

                    $data = User::where(['id' => $id])->delete();

                    if($process){

                        return response()->json(['code' => 200]);

                    }else{

                        return response()->json(['code' => 201]);

                    }

                } else {

                    return response()->json(['code' => 201]);

                }

            } else {

                return response()->json(['code' => 201]);

            }

        }

    /** permenant-delete */



    /** remove-profile */

        public function profile_remove(Request $request){

            if(!$request->ajax()) { exit('No direct script access allowed'); }



            if(!empty($request->all())){

                $id = base64_decode($request->id);

                $data = User::find($id);



                if($data){

                    if($data->photo != ''){

                        $file_path = public_path().'/uploads/users/'.$data->photo;



                        if(File::exists($file_path) && $file_path != ''){

                            if($data->photo != 'user-icon.jpg') {

                                @unlink($file_path);

                            }

                        }



                        $update = User::where(['id' => $id])->update(['photo' => '']);



                        if($update)

                            return response()->json(['code' => 200]);

                        else

                            return response()->json(['code' => 201]);

                    }else{

                        return response()->json(['code' => 200]);

                    }

                }else{

                    return response()->json(['code' => 201]);

                }

            }else{

                return response()->json(['code' => 201]);

            }

        }

    /** remove-profile */

    

    /** Import */

        public function import(Request $request){

           

            if(Excel::import(new ImportUser, $request->file('file')->store('file'))){

                return redirect()->route('avendor')->with('sucess' ,'File Imported Sucessfully');

            }else{

                return redirect()->route('avendor')->with('error' ,'Faild To Import File!');

            }

        }

    /** Import */

    

    /** Export */

        public function export(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



            $name = 'Users_'.Date('YmdHis').'.xlsx';



            try {

                return Excel::download(new ExportUser($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

    /** Export */

    

    

    

    public function change_password_form(Request $request)

    {

        return view('user.change_password');        

    }

    

    public function change_password_save(Request $request)

    {

        $user = auth()->user();

        

             $user->password = bcrypt($request->input('new_password'));

            $user->save();

            return redirect()->route('dashboard');

    

    }

    public function sendEmail(Request $request)

{

    $id = base64_decode($request->id);



    if (!$id) {

        return response()->json(['error' => 'Invalid ID format'], 400);

    }



    $user = User::find($id);



    if (!$user) {

        return response()->json(['error' => 'User not found'], 404);

    }



    // Send email to the user

    Mail::to($user->email)->send(new SendEmailToVendor($user->email, $user->password));



    return response()->json(['message' => 'Email sent'], 200);

}  

}

