<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Http\Controllers\masterController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class profileController extends Controller
{


    public function index($id = null)
    {
        if (isset($id)) {
            $user_id = decrypt($id);
            if (!empty($user_id)) {
                $data_user =  DB::table(TBL_ADMIN_USERS)->selectRaw("*")->whereRaw("adm_id = '" . $user_id . "'  ")->get();
                $users_data = json_decode(json_encode($data_user), true);
                $mstObj =  new masterController();
                $mstObj->setMetaData(['title' => 'Edit Admin - IHosting Mart Website', 'meta_desc' => 'Edit Admin -', 'meta_keyword' => 'Edit Admin']);
                $mstObj->setData(['page' => 'admin.admin_users.admin_form', 'page_title' => 'Edit Admin Member', 'results' => ['results' => $users_data[0], 'mode' => 'edit']]);
                $mstObj->renderAdminDashboardPage();
            } else {
                return  redirect()->back()->with('message', 'error|Invalid Data');
            }
        } else {
            $mstObj =  new masterController();
            $mstObj->setMetaData(['title' => 'Add Admin - IHosting Mart Website', 'meta_desc' => 'Admin - Add Admin Member', 'meta_keyword' => ' Admin']);
            $mstObj->setData(['page' => 'admin.admin_users.admin_form', 'page_title' => 'Add Admin Member', 'results' =>  ['results' => [], 'mode' => 'add']]);
            $mstObj->renderAdminDashboardPage();
        }
    }

    public function adminList()
    {
        $data_user =  DB::table(TBL_ADMIN_USERS)->selectRaw("*")->whereRaw("adm_id != '" . session()->get('admin_user_id') . "'")->get();
        $users_data = json_decode(json_encode($data_user), true);
        $mstObj =  new masterController();
        $mstObj->setMetaData(['title' => 'Admin - IHosting Mart Website', 'meta_desc' => 'Admin', 'meta_keyword' => ' Admin']);
        $mstObj->setData(['page' => 'admin.admin_users.admin_list', 'page_title' => 'Admin Members List', 'results' => $users_data]);
        $mstObj->renderAdminDashboardPage();
    }

    public function saveProfile(Request $request)
    {
        $token =   $request->_token;
        $mode =  $request->mode;
        if (isset($token)) {

            $fname = $request->fname;
            $lname = $request->lname;
            $uname = $request->uname;
            $scrname = $request->scrname;
            $utype = $request->utype;
            $atype = $request->atype;
            $uslug = $request->uslug;
            $mobile = $request->mobile;
            $iso = $request->iso;
            $isd = $request->isd;
            if (!empty($mobile)) {
                $phone = strtolower($iso) . '##' . $isd . '##' . $mobile;
            }
            $email = $request->email;
            $status = $request->status;
            $ip_info = $request->ip();

            if ($mode == 'edit') {
                $validate_data = $request->validate([
                    'fname' => 'required|min:2|max:18',
                    'lname' => 'required|min:2|max:18',
                    'uname' => 'required|min:10|max:20',
                    'scrname' => 'required|min:10|max:20',
                    'uslug' => 'required|min:10|max:20',
                    'utype' => 'required',
                    'atype' => 'required',
                    'email' => 'required|email',
                    'mobile' => 'required|numeric'
                ]);

                if ($validate_data) {
                    $adm_id = decrypt($request->adm_id);
                    $data_updated = [
                        'adm_modifiedby' =>  session()->get('admin_user_id'),
                        'adm_modified_date' => date('Y-m-d H:i:s'),
                    ];
                    if (!empty($fname)) {
                        $data_updated['adm_fname'] =  $fname;
                    }

                    if (!empty($lname)) {
                        $data_updated['adm_lname'] =  $lname;
                    }

                    if (!empty($email)) {
                        $data_updated['adm_email'] = $email;
                    }

                    if (!empty($phone)) {
                        $data_updated['adm_phone1'] =  $phone;
                    }

                    if (!empty($utype)) {
                        $data_updated['adm_role'] =  $utype;
                    }

                    if (!empty($images)) {
                        $data_updated['adm_profile_pic'] =  $images;
                    }

                    if (!empty($scrname)) {
                        $data_updated['adm_screen_name'] =  $scrname;
                    }

                    if (!empty($uname)) {
                        $data_updated['adm_user_name'] =  $uname;
                    }

                    if (!empty($uslug)) {
                        $data_updated['adm_slug'] = $uslug;
                    }


                    $data_updated['adm_type'] = $atype;


                    if (!empty($ip_info)) {
                        $data_updated['adm_ip_information'] = $ip_info;
                    }

                    if (!empty($status)) {
                        $data_updated['adm_status'] = $status;
                    }
                    if ($request->input('old_img')) {
                        if ($request->hasFile('images')) {
                            $image = $request->file('images');
                            $image_name = time() . '.' . $image->getClientOriginalExtension();
                            $destination_Path = public_path(UPLOADS_ADMIN_IMG_FOLDER);
                            $image->move($destination_Path, $image_name);
                        } else {
                            $image_name = $request->input('old_img');
                        }
                    } else {
                        if ($request->hasFile('images')) {
                            $image = $request->file('images');
                            $image_name = time() . '.' . $image->getClientOriginalExtension();
                            $destination_Path = public_path(UPLOADS_ADMIN_IMG_FOLDER);
                            $image->move($destination_Path, $image_name);
                        } else {
                            $image_name = null;
                        }
                    }

                    if (!empty($image_name)) {
                        $data_updated['adm_profile_pic'] = $image_name;
                    }
                }

                if (!empty($data_updated)) {
                    $data =  DB::table(TBL_ADMIN_USERS)->where('adm_id', '=', $adm_id)->update($data_updated);
                }

                if (!empty($data)) {
                    return redirect()->back()->with('message', 'success|Member details updated!');
                } else {
                    return redirect()->back()->with('message', 'error|Failed To update Member details');
                }
            } else {
                $validate_data = $request->validate([
                    'fname' => 'required|min:2|max:18',
                    'lname' => 'required|min:2|max:18',
                    'uname' => 'required|min:10|max:20',
                    'scrname' => 'required|min:10|max:20',
                    'uslug' => 'required|min:10|max:20',
                    'utype' => 'required',
                    'atype' => 'required',
                    'email' => 'required|email',
                    'mobile' => 'required|numeric',
                    'status' => 'required',
                    'password' => 'required|min:6|max:18',
                    'confirm_password' => 'required_with:password|same:password|min:6|max:18',
                ]);
                if ($validate_data) {
                    $password = $request->password;
                    $confirm_password = $request->confirm_password;
                    if ($password == $confirm_password) {
                        $data_updated = [
                            'adm_type' => $atype,
                            'adm_slug' => $uslug,
                            'adm_user_name' =>  $uname,
                            'adm_screen_name' =>  $scrname,
                            'adm_phone1' =>  $phone,
                            'adm_role' =>  $utype,
                            'adm_email' => $email,
                            'adm_fname' =>  $fname,
                            'adm_lname' =>  $lname,
                            'adm_status' =>  $status,
                            'adm_password' => (is_development() ? $password : Hash::make($password)),
                            'adm_created_by' =>  session()->get('admin_user_id'),
                            'adm_created_date' => date('Y-m-d H:i:s'),
                            'adm_ip_information' => $ip_info,
                        ];

                        if ($request->input('old_img')) {
                            if ($request->hasFile('images')) {
                                $image = $request->file('images');
                                $image_name = time() . '.' . $image->getClientOriginalExtension();
                                $destination_Path = public_path(UPLOADS_ADMIN_IMG_FOLDER);
                                $image->move($destination_Path, $image_name);
                            } else {
                                $image_name = $request->input('old_img');
                            }
                        } else {
                            if ($request->hasFile('images')) {
                                $image = $request->file('images');
                                $image_name = time() . '.' . $image->getClientOriginalExtension();
                                $destination_Path = public_path(UPLOADS_ADMIN_IMG_FOLDER);
                                $image->move($destination_Path, $image_name);
                            } else {
                                $image_name = null;
                            }
                        }
                        if (!empty($image_name)) {
                            $data_updated['adm_profile_pic'] = $image_name;
                        }
                        if (!empty($data_updated)) {
                            $data =  DB::table(TBL_ADMIN_USERS)->insert($data_updated);
                            $last_insert_id = DB::getPdo()->lastInsertId();
                        }

                        if (!empty($last_insert_id)) {
                            return redirect()->back()->with('message', 'success|New Member details!');
                        } else {
                            return redirect()->back()->with('message', 'error|Failed To update Member details');
                        }
                    } else {
                        return  redirect()->back()->with('message', 'error|password Not match ,Please fill password correctly');
                    }
                }
            }
        } else {
            return  redirect()->back()->with('message', 'error|Invalid Data');
        }
    }

    public function deleteProfile($id)
    {
        if (isset($id)) {
            $user_id = decrypt($id);
            if (!empty($user_id)) {

                $data_user = DB::table(TBL_ADMIN_USERS)->where('adm_id', '=',  $user_id)->get("*");
                $users_data = (array)$data_user[0];

                if (!empty($users_data)) {
                    $data =  DB::table(TBL_ADMIN_USERS)->where('adm_id', '=', $user_id)->update(['adm_is_deleted' => 1, 'adm_deleted_date' => date('Y-m-d H:i:s')]);
                    if ($data) {
                        return  redirect()->back()->with('message', 'success|Admin Member Deleted Successfully!');
                    } else {
                        return  redirect()->back()->with('message', 'error|Error to Deleting Admin!');
                    }
                } else {
                    return  redirect()->back()->with('message', 'error|Invalid Data!');
                }
            } else {
                return  redirect()->back()->with('message', 'error|Invalid Data');
            }
        } else {
            return  redirect()->back()->with('message', 'error|Invalid Data');
        }
    }

    public function deleteProfilePermanently($id)
    {
    }

    public function restoreProfile($id)
    {
        if (isset($id)) {
            $user_id = decrypt($id);
            if (!empty($user_id)) {

                $data_user = DB::table(TBL_ADMIN_USERS)->where('adm_id', '=',  $user_id)->get("*");
                $users_data = (array)$data_user[0];

                if (!empty($users_data)) {
                    $data =  DB::table(TBL_ADMIN_USERS)->where('adm_id', '=', $user_id)->update(['adm_is_deleted' => 0, 'adm_deleted_date' => null]);
                    if ($data) {
                        return  redirect()->back()->with('message', 'success|Admin Member restored Successfully!');
                    } else {
                        return  redirect()->back()->with('message', 'error|Error to Restoring Admin!');
                    }
                } else {
                    return  redirect()->back()->with('message', 'error|Invalid Data!');
                }
            } else {
                return  redirect()->back()->with('message', 'error|Invalid Data');
            }
        } else {
            return  redirect()->back()->with('message', 'error|Invalid Data');
        }
    }

    public function viewProfile($id)
    {
        if (isset($id)) {
            $user_id = decrypt($id);
            if (!empty($user_id)) {
                $data_user = DB::table(TBL_ADMIN_USERS)->selectRaw("* ")->where('adm_id', '=',  $user_id)->get();
                $users_data = json_decode($data_user, true);
                $mstObj =  new masterController();
                $mstObj->setMetaData(['title' => 'View Admin Users - IHosting Mart Website', 'meta_desc' => 'Admin - View Admin Users', 'meta_keyword' => ' Admin Users']);
                $mstObj->setData(['page' => 'admin.admin_users.admin_view', 'page_title' => 'View Admin Users', 'results' => $users_data[0]]);
                $mstObj->renderAdminDashboardPage();
            } else {
                return  redirect()->back()->with('message', 'error|Invalid Data');
            }
        } else {
            return  redirect()->back()->with('message', 'error|Invalid Data');
        }
    }

    public function changePassword($id)
    {
        if (isset($id)) {
            $user_id = decrypt($id);
            if (!empty($user_id)) {
                $data_user =  DB::table(TBL_ADMIN_USERS)->selectRaw("*")->whereRaw("adm_id = '" . $user_id . "'  ")->get();
                $users_data = json_decode(json_encode($data_user), true);
                $mstObj = new masterController();
                $mstObj->setMetaData(['title' => 'Change Password Admin - IHosting Mart Website', 'meta_desc' => 'Change Password Admin', 'meta_keyword' => 'Change Password Admin']);
                $mstObj->setData(['page' => 'admin.admin_users.change_password', 'page_title' => 'Change Password Admin', 'results' =>  $users_data[0]]);
                $mstObj->renderAdminDashboardPage();
            } else {
                return  redirect()->back()->with('message', 'error|Invalid Data');
            }
        } else {
            return  redirect()->back()->with('message', 'error|Invalid Data');
        }
    }

    public function savePassword(Request $request)
    {

        $token = $request->_token;
        $ip_info = $request->ip();
        if (isset($token)) {
            $password = $request->password;
            $new_password = $request->new_password;
            $confirm_password = $request->confirm_password;

            $adm_id = decrypt($request->adm_id);

            $validate_data = $request->validate([
                'password' => 'required|min:6|max:18',
                'new_password' => 'required|min:6|max:18',
                'confirm_password' => 'required_with:new_password|same:new_password|min:6|max:18',
            ]);

            if ($new_password == $confirm_password) {

                $data_user =  DB::table(TBL_ADMIN_USERS)->selectRaw("adm_id as id, adm_password as password")->whereRaw("adm_id = '" . $adm_id . "'")->get();
                $users_data = json_decode(json_encode($data_user), true);

                if (!empty($users_data)) {
                    if (is_development()) {
                        $verify_password = ($password == $users_data[0]['password']);
                    } else {
                        $verify_password = Hash::check($password, $users_data[0]['password']);
                    }
                    if ($verify_password ==  true) {
                        if ($password != $confirm_password) {

                            $data_updated = [
                                'adm_password' => (is_development() ? $new_password : Hash::make($new_password)),
                                'adm_ip_information' => $ip_info,
                                'adm_modifiedby' =>  session()->get('admin_user_id'),
                                'adm_modified_date' => date('Y-m-d H:i:s'),
                            ];

                            if (!empty($data_updated)) {
                                $data =  DB::table(TBL_ADMIN_USERS)->where('adm_id', '=', $adm_id)->update($data_updated);
                            }

                            if (!empty($data)) {
                                return redirect()->back()->with('message', 'success|Password Change Successfully!');
                            } else {
                                return redirect()->back()->with('message', 'error|Failed To update Password details');
                            }
                        } else {
                            return redirect()->back()->with('message', 'error|New Password must be different To current Password');
                        }
                    } else {
                        return  redirect()->back()->with('message', 'error|Enter Correct your current Password');
                    }
                } else {
                    return  redirect()->back()->with('message', 'error|Invalid Data');
                }
            } else {
                return  redirect()->back()->with('message', 'error|password Not match ,Please fill password correctly');
            }
        } else {
            return  redirect()->back()->with('message', 'error|Invalid Data');
        }
    }
}
