<?php

namespace App\Http\Controllers\superadmin\adminuser;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\superadmin;

use App\Models\Role;
use App\Models\Websitesetting;
use Validator,Redirect,Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Http;
use Jenssegers\Agent\Agent;
use App\Models\tbl_crud_feature;
use App\Models\tbl_permission;
use Illuminate\Support\Facades\Hash;
use Crypt;
use Session;

class AdminuserController extends Controller
{
    
function adminuser(){
$loginRedirect = sessionlogin();
if ($loginRedirect) {
return $loginRedirect; 
}
$user_id = session('SUPERADMIN_ID');

$hasPermission = permission($user_id, '4', 'action_view');
if ($hasPermission) { 
        $data['roles']=Role::where('status','1')->get();
return view('superadmin.adminuser.adminuser',$data);
}

return redirect(asset('superadmin/permission_denied'))->with('error', 'Permission Denied')->send();

}

function adminuseradd(){
$user_id = session('SUPERADMIN_ID');

$hasPermission = permission($user_id, '4', 'action_add');
if ($hasPermission) { 
      insertLogsAPI($user_id,'3','Admin User View','4','','','','','','',''); 
    $data['role']=Role::where('status','1')->get();
          $data['feature'] = tbl_crud_feature::get();
return view('superadmin.adminuser.adminuseradd',$data);
}


return redirect(asset('superadmin/permission_denied'))->with('error', 'Permission Denied')->send();
}

function adminusercreate(Request $request){
$user_id = session('SUPERADMIN_ID');
$hasPermission = permission($user_id, '4', 'action_add');
if ($hasPermission) { 
$existingMobile = superadmin::where('mobile', $request->number)->first();
if ($existingMobile) {
return redirect()->back()->with('error', 'Mobile number already exists!');
}


$existingEmail = superadmin::where('email', $request->email)->first();
if ($existingEmail) {
return redirect()->back()->with('error', 'Email  already exists!');
}


$create = new superadmin;
$create->firstname = $request->f_name;
$create->lastname = $request->l_name;
$create->mobile= $request->number;
$create->password = Hash::make($request->password);
$create->username = $request->f_name  .  $request->l_name;
$create->role = $request->role??'';
$create->email = $request->email;

      $create->token = substr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", mt_rand(0, 51), 1) . substr(md5(time()), 1);

if ($request->image) {
$img = time().'image.'.$request->image->extension();
$request->image->move(public_path('uploads/adminuser'), $img);
$create->image = $img;
}
$create->ip = $_SERVER['REMOTE_ADDR'];
$create->save();
 $after = json_encode($create);
     $before = json_encode($create);
    $adduser=$create->id;
    insertLogsAPI($user_id,'1','Admin User Add','4','',$adduser,'','',$after,$before,''); 


 foreach ($request->feature as $index => $featuredData) {
        $feature = new tbl_permission();
        $feature->feature_id = $featuredData;
        $feature->action_view = isset($request->viewOwnHidden[$index]) ? $request->viewOwnHidden[$index] : 0;
        $feature->action_add = isset($request->addHidden[$index]) ? $request->addHidden[$index] : 0;
        $feature->action_globle_view = isset($request->viewgHidden[$index]) ? $request->viewgHidden[$index] : 0;
        $feature->action_edit = isset($request->editHidden[$index]) ? $request->editHidden[$index] : 0;
        $feature->action_delete = isset($request->deleteHidden[$index]) ? $request->deleteHidden[$index] : 0;
        $feature->user_id = $create->id;
      
        $feature->ip = $_SERVER['REMOTE_ADDR'];
        $feature->strtotime = strtotime(date('d-m-Y'));
        $feature->save();
    }



return redirect(asset('superadmin/adminuser'))->with('success','Admin User add successfully');
}

return redirect(asset('superadmin/permission_denied'))->with('error', 'Permission Denied')->send();
}  

public function houseajexadminuser(Request $request){
$draw   = $request->draw ?? 1;
$rows   = $request->start ?? 0;
$length = $request->length ?? 10;


$columnIndex     = $request->order[0]['column'] ?? 0;
$columnName      = $request->columns[$columnIndex]['data'] ?? 'id';
$columnSortOrder = $request->order[0]['dir'] ?? 'asc';
$filltersearchValue = $request->columns[$columnIndex]['search']['value'] ?? null;
$searchValue     = $request->search['value'] ?? null;

$user_id  = session('SUPERADMIN_ID');
$roledata = superadmin::where('id', $user_id)->first();

if ($roledata->role == '1') {
$housesurveydata  = superadmin::houseajexadminuser($rows, $searchValue, $columnSortOrder, $columnName, $columnIndex, $filltersearchValue, 1, $length);
$housesurveycount = superadmin::houseajexadminuser($rows, $searchValue, $columnSortOrder, $columnName, $columnIndex, $filltersearchValue, 0, $length);
} else {
$housesurveydata  = superadmin::houseajexadminuser($rows, $searchValue, $columnSortOrder, $columnName, $columnIndex, $filltersearchValue, 1, $length, $user_id);
$housesurveycount = superadmin::houseajexadminuser($rows, $searchValue, $columnSortOrder, $columnName, $columnIndex, $filltersearchValue, 0, $length, $user_id);
}

$data    = [];
$user_id = session('SUPERADMIN_ID');

foreach ($housesurveydata as $row) {
$action = '<ul class="action d-flex m-0 ps-0" style="list-style-type: none; ">';

// chngepassword Button
$action .= '<li class="list-unstyled" style="margin: 0;">';
if (permission($user_id, '4', 'action_edit')) {
$action .= '<a class="btn bg-primary actionedit editbtn btn-sm me-1 " href="' . asset('superadmin/changepassword/' . Crypt::encrypt($row->id)) . '">
<i class="fadeIn animated bx bx-key anji me-0"></i>
</a>';
}
$action .= '</li>';


// Edit Button
$action .= '<li class="list-unstyled" style="margin: 0;">';
if (permission($user_id, '4', 'action_edit')) {
$action .= '<a class="btn actionedit editbtn me-1 btn-sm" href="' . asset('superadmin/adminuseredit/' . Crypt::encrypt($row->id)) . '">
<i class="fadeIn animated bx bx-pencil anji me-0"></i>
</a>';
}
$action .= '</li>';

// Delete Button
if ($row->id != '1') {
$action .= '<li class="list-unstyled">';
if (permission($user_id, '4', 'action_delete')) {
$action .= '<a href="' . asset('superadmin/adminuserdelete/' . Crypt::encrypt($row->id)) . '" onclick="return check_delete()" class="btn  deletebtn btn-sm">
<i class="fadeIn animated bx bx-trash anji me-0"></i>
</a>';
}
$action .= '</li>';
}
$action .= '</ul>';

if ($row->id != '1') {
$status = '<div class="toggle-flip" style="margin-left: 4px;">
<input
type="checkbox"
id="flip' . $row->id . '"
name="status"
class="status-toggle"
data-id="' . $row->id . '"
onclick="round_success_noti()" ' . ($row->status == 1 ? 'checked' : '') . '>
<label class="flip-label" for="flip' . $row->id . '"></label>
</div>';
}else{
$status = "";
}

        $role = Role::where('id', $row->role)->first();
        $roleName = $role->role ?? '';

$data[] = [
"id"    => $row->id,
"image" => '<a href="' . asset('uploads/adminuser/' . $row->image) . '" data-fancybox="images" data-caption=""><img src="' . asset('uploads/adminuser/' . $row->image) . '" style="width: 30px;"></a>',
"role"  => $roleName,
"name"  => $row->firstname . ' ' . $row->lastname,
"number"=> $row->mobile,
"email" => $row->email,
"status"=> $status,
"action"=> $action,
];
}

// Total Records Calculation
$canViewGlobal = permission($user_id, '4', 'action_globle_view');

$city   = superadmin::where('id', $user_id)->first();

if ($user_id == '1') {
$query = DB::table('superadmins')->orderBy('id', 'DESC');
}
elseif ( $canViewGlobal) {
        $query = DB::table('superadmins')->orderBy('id', 'DESC');
} else {
$query = DB::table('superadmins')->where('id', $user_id)->orderBy('id', 'DESC');
}

$tot_rows = $query->count();

$datas = [
"draw"            => intval($draw),
"recordsTotal"    => $tot_rows,
"recordsFiltered" => $housesurveycount,
"data"            => $data,
];

return response()->json($datas);
}

public function adminuserstatus(Request $request) {
$id = $request->id;
$status = superadmin::find($id);

if (!$status) {
return response()->json(['success' => false, 'message' => 'Admin User not found'], 404);
}

$status->status = $request->status;
$status->save();

return response()->json(['success' => true]);
}

function adminuserdelete(Request $request,$id){

$user_id = session('SUPERADMIN_ID');

$hasPermission = permission($user_id, '4', 'action_delete');
if ($hasPermission) {
$id=Crypt::decrypt($id);

$delete = superadmin::findOrFail($id);
$image_path = public_path("uploads/adminuser/{$delete->image}");
   if (File::exists($image_path) && !File::isDirectory($image_path)) {
           
            unlink($image_path);
        }
$delete->delete();
 $after = json_encode($delete);
     $before = json_encode($delete);
    $adduser=$delete->id;
    insertLogsAPI($user_id,'4','Admin User Delete','4','',$adduser,'','',$after,$before,''); 

return redirect()->back()->with('success','Admin User delete successfully');

}

return redirect(asset('superadmin/permission_denied'))->with('error', 'Permission Denied')->send();


}

public function permission_denied(){
$loginRedirect = sessionlogin();
if ($loginRedirect) {
return $loginRedirect; 
}
$user_id = session('SUPERADMIN_ID');
  insertLogsAPI($user_id,'2','Permission Denied','','','','','','','',''); 
return view('superadmin.adminuser.permission_denied');
}

function adminuseredit(Request $request){
$id=Crypt::decrypt($request->id);
$user_id = session('SUPERADMIN_ID');

$hasPermission = permission($user_id, '4', 'action_edit');
if ($hasPermission) { 

$data['adminuserdata']=superadmin::where('id',$id)->first();
         $data['role']=Role::get();

         $data['feature'] = tbl_crud_feature::get();
return view('superadmin.adminuser.adminuseredit',$data);
}
return redirect(asset('superadmin/permission_denied'))->with('error', 'Permission Denied')->send();
}

public function adminuserupdate(Request $request){
$user_id = session('SUPERADMIN_ID');
$hasPermission = permission($user_id, '4', 'action_edit');
if ($hasPermission) { 
try {
$id = Crypt::decrypt($request->id);

$existingMobile = superadmin::where('mobile', $request->number)->where('id', '!=', $id)->first();
if ($existingMobile) {
return redirect()->back()->with('error', 'Mobile number already exists!');
}

$existingEmail = superadmin::where('email', $request->email)->where('id', '!=', $id)->first();
if ($existingEmail) {
return redirect()->back()->with('error', 'Email already exists!');
}

$update = superadmin::findOrFail($id);
 $before = json_encode($update);
        $update->firstname = $request->f_name;
        $update->lastname = $request->l_name;
        $update->mobile  = $request->number;
        $update->role = $request->role;
        $update->email = $request->email;
        $update->ip = $_SERVER['REMOTE_ADDR'];


if ($request->hasFile('image')) {
if ($update->image && file_exists(public_path('uploads/adminuser/' . $update->image))) {
    unlink(public_path('uploads/adminuser/' . $update->image));
}

$img = preg_replace('/\.[^.]+$/', '', $update->image) . '.' . $request->image->extension();
$request->image->move(public_path('uploads/adminuser'), $img);
$update->image = $img;
}

$update->save();

 $after = json_encode($update);
         $adduser=$update->id;
    insertLogsAPI($user_id,'3','Admin User Update','4','',$adduser,'','',$after,$before,''); 
      foreach ($request->feature as $index => $featuredData) {
            $feature = tbl_permission::where('user_id', $id)
                                     ->where('feature_id', $featuredData)
                                     ->first();

            if (!$feature) {
                $feature = new tbl_permission();
                $feature->user_id = $id;
                $feature->feature_id = $featuredData;
            }

            $feature->action_view        = $request->viewOwnHidden[$index] ?? 0;
            $feature->action_globle_view = $request->viewgHidden[$index] ?? 0;
            $feature->action_add         = $request->addHidden[$index] ?? 0;
            $feature->action_edit        = $request->editHidden[$index] ?? 0;
            $feature->action_delete      = $request->deleteHidden[$index] ?? 0;
            $feature->ip = $_SERVER['REMOTE_ADDR'];
            $feature->strtotime = strtotime(date('d-m-Y'));
            $feature->save();
        }



return redirect(asset('superadmin/adminuser'))->with('success','Admin User update successfully');
} catch (\Exception $e) {
return redirect()->back()->with('error', 'Something went wrong: ' . $e->getMessage());
}
}
return redirect(asset('superadmin/permission_denied'))->with('error', 'Permission Denied')->send();
}


     //Role//
public function role()
{
     $loginRedirect = sessionlogin();
    if ($loginRedirect) {
        return $loginRedirect; 
    }
    
    $user_id = session('SUPERADMIN_ID');
     insertLogsAPI($user_id,'2','Role View','3','','','','','','',''); 
    $hasPermission = permission($user_id, '3', 'action_view');
    if (!$hasPermission) {
        return redirect(asset('superadmin/permission_denied'))->with('error', 'Permission Denied')->send();
    }
    return view('superadmin.role.role');
}


  function rolecreate(Request $request) {
  $user_id = session('SUPERADMIN_ID');
     $hasPermission = permission($user_id, '3', 'action_add');
     if ($hasPermission) { 
           $existingRole = Role::where('role', $request->title)->first();
    if ($existingRole) {
        return redirect()->back()->with('error', 'Role already exists!');
    }
    
    $role = new Role;
    $role->role = $request->title;
    $role->ip = CurrentTimestamp()['ip'];
    $role->strtotime = CurrentTimestamp()['strtotime'];
    $role->save();
  $adduser=  $role->id;
    $after = json_encode($role);
    $before = json_encode($role);
    insertLogsAPI($user_id,'1','Role Add','3','',$adduser,'','',$after,$before,'');
     $message = fleshmessage(2,1,'Role');
    return redirect()->back()->with('success','Role Add successfully');
         
     }
       return redirect(asset('superadmin/permission_denied'))->with('error', 'Permission Denied')->send();
         
  
}


function roleajax(Request $request){
    $draw= $request->draw;
    $rows = $request->start;
    $columnIndex = $request->order[0]['column'];
    $columnName = $request->columns[$columnIndex]['data'];
    $columnSortOrder = $request->order[0]['dir'];
    $filltersearchValue = $request->columns[$columnIndex]['search']['value'];
    $searchValue = $request->search['value'];
    $length = $request->length;


 $user_id = session('SUPERADMIN_ID');
  $roledata = superadmin::where('id', $user_id)->first();
    if($user_id =='1'){
    $housesurveydata = Role::roleajax($rows,$searchValue,$columnSortOrder,$columnName,$columnIndex,$filltersearchValue,1,$length);
    $housesurveycount = Role::roleajax($rows,$searchValue,$columnSortOrder,$columnName,$columnIndex,$filltersearchValue,0,$length);
    }else{
       $housesurveydata = Role::roleajax($rows,$searchValue,$columnSortOrder,$columnName,$columnIndex,$filltersearchValue,1,$length,$user_id);
    $housesurveycount = Role::roleajax($rows,$searchValue,$columnSortOrder,$columnName,$columnIndex,$filltersearchValue,0,$length,$user_id);   
    }
  
  
    $i = 1;
    $data = array();
      $user_id=session('SUPERADMIN_ID');
         
     
    foreach ($housesurveydata as $row) {
   $action = '<ul class="ps-0 action d-flex  m-0" style="list-style-type: none; ">';  

    $action .= '<li class="list-unstyled" style="margin: 0;"> ';
   if(permission($user_id,'3','action_edit')){
                  $action .= '<a href="javascript:void(0);" 
                   onClick="categoryupdate(' . $row->id . ', \'' . $row->role . '\');" 
                   class="btn editbtn btn-sm">
                    <i class="fadeIn animated anji bx bx-pencil me-0"></i>
                </a>';
                    }
  
              $action .= '   </li>';



   

  



    $action .= '</ul>';




    
    if($row->status === '1'){ 
    $checked = 'checked'; 
    }
    
   $status = '<div class="toggle-flip" style="margin-left: 4px;">
    <input
        type="checkbox"
        id="flip' . $row->id . '"
        name="status"
        class="status-toggle"
        data-id="' . $row->id . '"
        onclick="round_success_noti()" ' . ($row->status == 1 ? 'checked' : '') . '>
    <label class="flip-label" for="flip' . $row->id . '"></label>
</div>';

 
   
     $data[] = array(
    "id" => $row->id, 
   "role" => $row->role,
   "status" => $status,
    "action" => $action
);
    }
    
$canViewGlobal = permission($user_id, '3', 'action_globle_view');
    if ($user_id == '1') {
$query = DB::table('roles')->orderBy('id', 'DESC');
}
elseif ( $canViewGlobal) {
        $query = DB::table('roles')->orderBy('id', 'DESC');
} else {
$query = DB::table('roles')->where('user_id', $user_id)->orderBy('id', 'DESC');
}

    $tot_rows = $query->count();
    
    $datas = array(
    "draw" => $draw,
    "recordsTotal" => $tot_rows,
    "recordsFiltered" => $housesurveycount,
    "data" => $data
    );
    
    echo json_encode($datas);

    
    }

    
  function roleedit(Request $request) {
        $user_id = session('SUPERADMIN_ID');
     $hasPermission = permission($user_id, '3', 'action_edit');
     if ($hasPermission) { 
               
    $existingRole = Role::where('role', $request->title)->where('id', '!=', $request->id) ->first();

    if ($existingRole) {
        return redirect()->back()->with('error', 'Role already exists!');
    }

    $roleedit = Role::where('id', $request->id)->first();
    $before = json_encode($roleedit);
    if (!$roleedit) {
        return redirect()->back()->with('error', 'Role not found!');
    }

    $roleedit->role = $request->title;
    $roleedit->ip = CurrentTimestamp()['ip'];
    $roleedit->strtotime = CurrentTimestamp()['strtotime'];
    $roleedit->save();
    $adduser=  $roleedit->id;
    $after = json_encode($roleedit);
  insertLogsAPI($user_id,'3','Role Update','3','',$adduser,'','',$after,$before,''); 
   
    return redirect()->back()->with('success','Role Update successfully');

         
     }
     return redirect(asset('superadmin/permission_denied'))->with('error', 'Permission Denied')->send();

}

    
    
    public function rolestatus(Request $request) {
    $id = $request->id;
    $rolestatus = Role::find($id);
    if (!$rolestatus) {
        return response()->json(['success' => false, 'message' => 'Role not found'], 404);
    }

    $rolestatus->status = $request->status;
    $rolestatus->save();
    return response()->json(['success' => true]);
}

      function roledelete($id)
    {
          $user_id = session('SUPERADMIN_ID');
     $hasPermission = permission($user_id, '3', 'action_delete');
     if ($hasPermission) { 
       insertLogsAPI($user_id,'4','Role Delete','4','',$adduser,'','',$after,$before,''); 
          $categorydel = Role::where('id', Crypt::decrypt($id))->delete();
        return redirect()->back()->with('success','Role Delete Successfully');
     }
      return redirect(asset('superadmin/permission_denied'))->with('error', 'Permission Denied')->send();
       
    }
    
  


}