myLogger = \Config\Services::mylogger(); $this->userModel = new UserModel(); $this->roleModel = new RoleModel(); $this->teamModel = new TeamModel(); $this->userTeamsModel = new UserTeamsModel(); $this->bookStack = new BookStackUserHelper(); $this->authHistoryModel = new AuthHistoryModel(); $this->userActivityHistoryModel = new UserActivityHistoryModel(); } public function list() { $data['page_name'] = 'User'; $this->myLogger->logme('error','User list function called'); $data['UserList'] = $this->userModel->getUserList(); // echo '
';
        // print_r($data); die;
        $data['roleData'] = $this->roleModel->select('id, role')->findAll();        
        $data['teamData'] = $this->teamModel->select('id, name')->findAll();
        $this->loadLayout('UserList', $data);
    }


    public function create()
    {
        $this->myLogger->logme('error', 'User create function called');
        $teams = $this->request->getPost('team');

        //if this is get method return to user creation page
        if (!$this->request->getPost()) {
            return redirect()->to(base_url('/user/list'));
        } else {

            $userData = $this->request->getPost();
            $userData['created_by'] =  get_session_userid();
            $temp_team = $userData['team'];
            unset($userData['team']);

            $insert = $this->userModel->insert($userData);

            $bookStackData = [
                'name' => $userData['first_name'],
                'email' => $userData['email'],
                
            ];
            $this->bookStack->createEditUser($bookStackData);

            if ($insert) {
                $teamData['user_id'] = $insert;
                foreach ($teams as $value) {
                    $teamData['team_id'] = $value;
                    $teamData['created_by'] =  get_session_userid();
                    $this->userTeamsModel->insert($teamData);
                }

                $db = \Config\Database::connect();
                $tableName = 'hdz_staff';
                
                // Set default values
                $admin = 0;
                $acm = 0;
                $acm_id = null;
                
                if ($userData['role'] == 3) {
                    $admin = 0;
                    $acm = 1;
                    $acm_id = $insert;
                } else if (in_array($userData['role'], [1, 5])) {
                    $admin = 1;
                    $acm = 0;
                    $acm_id = null;
                }
                
                $password = '12345678'; // Default password
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                
                $hdz_staff = [
                    'emp_code' => $userData['emp_code'],
                    'fullname' => $userData['first_name'],
                    'username' => strtolower($userData['first_name']),
                    'email' => $userData['email'],
                    'admin' => $admin,
                    'acm' => $acm,
                    'acm_id' => $acm_id,
                    'registration' => time(),
                    'password' => $hashedPassword,
                    'active' => 1,
                    'department' => 'a:7:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"5";i:3;s:1:"3";i:4;s:1:"9";i:5;s:1:"4";i:6;s:2:"10";}',
                ];
                
                $db->table($tableName)->insert($hdz_staff);
                
            }
        }
        $this->myLogger->logme('error', 'User create Successfully created by id {data}', ['data' =>  get_session_userid()]);
        return redirect()->to(base_url('/user/list'));
    }

    public function getuser($id = null)
    {
        $userTeamData = $this->userTeamsModel->where('user_id', $id)->findAll();
        $data         = $this->userModel->getUserById($id);
        if($data){
           echo json_encode(array("status" => true , 'data' => $data, 'userTeamData' => $userTeamData));
        }else{
            echo json_encode(array("status" => false));
        }
    }

    public function edit()
    {

        if (!$this->request->getPost()) {
            return redirect()->to(base_url('/user/list'));
        } else {
            $id = $this->request->getPost('PrimaryKey');
            $teams = $this->request->getPost('team');
            $userData = $this->request->getPost();
            unset($userData['csrf_test_name']);
            unset($userData['PrimaryKey']);

            $existingData = $this->userModel->where('id',$id)->first();;

            // Update data in the 'users' table based on the $id
            $userData['updated_by'] =  get_session_userid();
            $update = $this->userModel->where('id', $id)->set($userData)->update();

            $bookStackData = [
                'name' => $userData['first_name'],
                'email' => $userData['email'],
            ];

            $this->bookStack->createEditUser($bookStackData,$existingData);


            if ($update) {

                if ($teams) {
                    $this->userTeamsModel->where('user_id', $id)->delete();
                    $teamData['user_id'] = $id;
                    foreach ($teams as $value) {
                        $teamData['team_id'] = $value;
                        $teamData['created_by'] =  get_session_userid();
                        $this->userTeamsModel->insert($teamData);
                    }
                }

                $db = \Config\Database::connect();
                $tableName = 'hdz_staff';
                
                $hdz_staff = [
                    'emp_code' => $userData['emp_code'],
                    'fullname' => $userData['first_name'],
                    'username' => strtolower($userData['first_name']),
                    'email' => $userData['email'],
                    'registration' => time(),
                    'active' => 1,
                    'department' => 'a:7:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"5";i:3;s:1:"3";i:4;s:1:"9";i:5;s:1:"4";i:6;s:2:"10";}',
                ];
                
                if ($userData['role'] == 3) {
                    $hdz_staff['admin'] = 0;
                    $hdz_staff['acm'] = 1;
                    $hdz_staff['acm_id'] = $id;
                } elseif (in_array($userData['role'], [1, 5])) {
                    $hdz_staff['admin'] = 1;
                    $hdz_staff['acm'] = 0;
                    $hdz_staff['acm_id'] = null;
                } else {
                    
                    return redirect()->to(base_url('/user/list'));
                }
                
                // Check if staff data exists
                $staffData = $db->table($tableName)
                    // ->where('emp_code', $userData['emp_code'])
                    ->where('email', $userData['email'])
                    ->get()->getResult();
                
                if (!empty($staffData)) {

                    // Update existing record
                    $db->table($tableName)
                        // ->where('emp_code', $userData['emp_code'])
                        ->where('email', $userData['email'])
                        ->set($hdz_staff)->update();

                } else {

                    $password = '12345678'; // Default password
                    $hdz_staff['password'] = password_hash($password, PASSWORD_DEFAULT);
                
                    // Insert new record
                    $db->table($tableName)->insert($hdz_staff);
                }
                
            }

            return redirect()->to(base_url('/user/list'));
        }
    }

    public function deactive($id = null)
    {   
        $model = new UserModel();

        $emailToDelete = $model->where('id', $id)->first();
        $deactive = $model->where('id', $id)->set(['is_active' => 0])->update();

        $this->bookStack->deleteUser($emailToDelete);
        if($deactive)
        {
            // $db = \Config\Database::connect();
            // $tableName = 'hdz_staff'; 

            // $db->table($tableName)->insert($hdz_staff);
                 

           echo json_encode(array("status" => true));
        }else{
           echo json_encode(array("status" => false));
        }
    }

    public function getRolesAndTeams()
    {
        $roleData = $this->roleModel->select('id, role')->findAll();
        $teamData = $this->teamModel->select('id, name')->findAll();
        echo json_encode(array("status" => true , 'roleData' => $roleData, 'teamData' => $teamData,));
    }


    // public function getUserActivityHistory()
    // {
    //     $user_id = $this->request->getVar('user_id');
    //     $pre_hr_id = $this->request->getVar('pre_hr_id');
    //     $user_type = $this->request->getVar('user_type');

    //     // echo $user_id.' - '.$pre_hr_id;
    //     $field_for_where_condition = 'user_id';
    //     if($user_id == 0 || $user_id == NULL)
    //     {
    //         $field_for_where_condition = 'pre_hr_id';
    //         $user_id = $pre_hr_id;
    //     }

    //     if($field_for_where_condition == "pre_hr_id"){
    //         //get login history
    //         $auth_data =  $this->authHistoryModel->where('is_active', 1)->where('user_id',$user_id)->where('user_type', $user_type)->findAll();
    //     }else{
    //         $preDB = \Config\Database::connect('preDB');
    //         $auth_data = $preDB->table('auth_history')->where('is_active', 1)->where('user_id',$user_id)->where('user_type', $user_type)->get()->getResultArray();
    //     }

    //     //get activity history
    //     $activity_data = $this->userActivityHistoryModel->where($field_for_where_condition,$user_id)->where('user_type', $user_type)->findAll();

    // }


    // public function getUserActivityHistory()
    // {
    //     try {
    //         $client_id   = $this->request->getVar('client_id');
    //         $user_id   = $this->request->getVar('user_id');
    //         $pre_hr_id = $this->request->getVar('pre_hr_id');
    //         $user_type = $this->request->getVar('user_type');

    //         $clientController = new ClientController;

    //         if (empty($client_id)) {
    //             return $this->respond(['status'  => false,'message' => 'Client Id is required'], 400);
    //         }

    //         if (empty($user_type)) {
    //             return $this->respond(['status'  => false,'message' => 'User type is required'], 400);
    //         }

    //         $field_for_where_condition = 'user_id';

    //         if (empty($user_id) || $user_id == 0) {
    //             if (empty($pre_hr_id)) {
    //                 return $this->respond(['status'  => false,'message' => 'user_id or pre_hr_id must be provided'], 400);
    //             }

    //             $field_for_where_condition = 'pre_hr_id';
    //             $user_id = $pre_hr_id;
    //         }

    //         // Get login/auth history
    //         if ($field_for_where_condition == 'user_id') {
    //             $auth_data = $this->authHistoryModel
    //                 ->where('is_active', 1)
    //                 ->where('user_id', $user_id)
    //                 ->where('user_type', $user_type)
    //                 ->orderBy('created_at', 'desc')
    //                 ->findAll();
    //             // print_r(db_connect()->getLastQuery()); die;
    //         } else {
    //             $preDB = \Config\Database::connect('preDB');
    //             $auth_data = $preDB->table('auth_history')
    //                 ->where('is_active', 1)
    //                 ->where('user_id', $user_id)
    //                 ->where('user_type', $user_type)
    //                 ->orderBy('created_at', 'desc')
    //                 ->get()
    //                 ->getResultArray();
    //         }

    //         // Get activity history
    //         $activity_data = $this->userActivityHistoryModel
    //             ->where($field_for_where_condition, $user_id)
    //             ->where('user_type', $user_type)
    //             ->findAll();

    //         $merged_data = $this->getMergedUserHistory($auth_data, $activity_data);

    //         return $this->respond([
    //             'status'        => true,
    //             'message'       => 'User history fetched successfully',
    //             'auth_history'  => $auth_data,
    //             'activity_log'  => $activity_data,
    //             'merged_data'   => $merged_data,
    //         ]);

    //     } catch (\Exception $e) {
    //         $this->myLogger->logme("error", ($e->getMessage().' --- '.$e->getLine() . '----' . $e->getTraceAsString()));
    //         return $this->respond([
    //             'status'  => false,
    //             'message' => 'Error: ' . $e->getMessage()
    //         ], 500);
    //     }
    // }    
    
    public function getUserActivityHistory()
    {
        try {
            $this->myLogger->logme("error", "User activity history fetch initiated.");

            $client_id = $this->request->getVar('client_id');
            $startDate = $this->request->getVar('startDate');
            $endDate = $this->request->getVar('endDate');
            $user_type = 'hr';
            $clientController = new ClientController;

            // Convert to DB format with full time range
            $startDateTime = null;
            $endDateTime = null;

            if (!empty($startDate)) {
                $startDateTime = \DateTime::createFromFormat('d-m-Y', $startDate)->format('Y-m-d 00:00:00');
                $endDateTime   = \DateTime::createFromFormat('d-m-Y', $endDate)->format('Y-m-d 23:59:59');
            }


            $this->myLogger->logme("error", "Received client_id: " . $client_id);

            if (empty($client_id)) {
                $this->myLogger->logme("warning", "Client ID is missing.");
                return $this->respond(['status' => false, 'message' => 'Client Id is required'], 400);
            }

            $hr_access_data = $clientController->getHrAccessData($client_id)['hr_access_data'] ?? [];
            $this->myLogger->logme("error", "Fetched HR access data: " . json_encode($hr_access_data));

            if (empty($hr_access_data)) {
                $this->myLogger->logme("error", "No HR access data found for client_id: $client_id");
                $html = view('hr_activity_history');
                return $this->respond(['status' => true, 'data' => $html, 'list_of_activity_data' => []], 200);
            }

            $activityMap = [
                'export_empdata'       => 'Exporting post employee data',
                'export_cddata'        => 'Exporting cd data',
                'export_cdsummary'     => 'Exporting cd summary data',
                'export_preempdata'    => 'Exporting pre employee data',
                'import_enrollempdata' => 'Import enrolment file',
            ];

            $list_of_activity_data = [];

            foreach ($hr_access_data as $key => $value) {
                $this->myLogger->logme("error", "Processing HR user: " . json_encode($value));

                $auth_data = [];
                $activity_data = [];

                $hr_name = $value['hr_name'] ?? '';
                $hr_mail = $value['hr_mail'] ?? '';

                if (!empty($value['pre_hr_id']) && !empty($value['post_hr_id'])) {
                    $this->myLogger->logme("error", "Both pre_hr_id and post_hr_id found. Using post DB for user_id: {$value['post_hr_id']}");

                    // Fetch Auth History
                    $auth_query = $this->authHistoryModel
                        ->select("DATE_FORMAT(created_at, '%d-%m-%Y %r') AS created_at")
                        ->where('is_active', 1)
                        ->where('user_id', $value['post_hr_id'])
                        ->where('user_type', $user_type);

                    if (!empty($startDate)) {
                        $auth_query->where('created_at >=', $startDateTime)
                                ->where('created_at <=', $endDateTime);
                    }

                    $auth_data = $auth_query->orderBy('created_at', 'desc')->findAll();


                    // Fetch User Activity
                    $activity_query = $this->userActivityHistoryModel
                        ->select("DATE_FORMAT(created_at, '%d-%m-%Y %r') AS created_at, activity")
                        ->where('user_id', $value['post_hr_id'])
                        ->where('user_type', $user_type);

                    if (!empty($startDate)) {
                        $activity_query->where('created_at >=', $startDateTime)
                                    ->where('created_at <=', $endDateTime);
                    }

                    $activity_data = $activity_query->findAll();


                } elseif (!empty($value['post_hr_id'])) {
                    $this->myLogger->logme("error", "Only post_hr_id found. user_id: {$value['post_hr_id']}");

                    $auth_query = $this->authHistoryModel
                        ->select("DATE_FORMAT(created_at, '%d-%m-%Y %r') AS created_at")
                        ->where('is_active', 1)
                        ->where('user_id', $value['post_hr_id'])
                        ->where('user_type', $user_type);

                    if (!empty($startDate)) {
                        $auth_query->where('created_at >=', $startDateTime)
                                ->where('created_at <=', $endDateTime);
                    }

                    $auth_data = $auth_query->orderBy('created_at', 'desc')->findAll();

                    $activity_query = $this->userActivityHistoryModel
                        ->select("DATE_FORMAT(created_at, '%d-%m-%Y %r') AS created_at, activity")
                        ->where('user_id', $value['post_hr_id'])
                        ->where('user_type', $user_type);

                    if (!empty($startDate)) {
                        $activity_query->where('created_at >=', $startDateTime)
                                    ->where('created_at <=', $endDateTime);
                    }

                    $activity_data = $activity_query->findAll();

                } elseif (!empty($value['pre_hr_id'])) {
                    $this->myLogger->logme("error", "Only pre_hr_id found. user_id: {$value['pre_hr_id']}");

                    $preDB = \Config\Database::connect('preDB');

                    $auth_query = $preDB->table('auth_history')
                        ->select("DATE_FORMAT(created_at, '%d-%m-%Y %r') AS created_at")
                        ->where('is_active', 1)
                        ->where('user_id', $value['pre_hr_id'])
                        ->where('user_type', $user_type);

                    if (!empty($startDate)) {
                        $auth_query->where('created_at >=', $startDateTime)
                                ->where('created_at <=', $endDateTime);
                    }

                    $auth_data = $auth_query->orderBy('created_at', 'desc')->get()->getResultArray();

                    $activity_query = $this->userActivityHistoryModel
                        ->select("DATE_FORMAT(created_at, '%d-%m-%Y %r') AS created_at, activity")
                        ->where('pre_hr_id', $value['pre_hr_id'])
                        ->where('user_type', $user_type);

                    if (!empty($startDate)) {
                        $activity_query->where('created_at >=', $startDateTime)
                                    ->where('created_at <=', $endDateTime);
                    }

                    $activity_data = $activity_query->findAll();
                }

                foreach ($auth_data as &$entry) {
                    $entry['user_name'] = $hr_name;
                    $entry['user_mail'] = $hr_mail;
                    $entry['activity'] = "Login";
                }

                foreach ($activity_data as &$entry) {
                    $entry['user_name'] = $hr_name;
                    $entry['user_mail'] = $hr_mail;

                    if (!empty($entry['activity']) && isset($activityMap[$entry['activity']])) {
                        $entry['activity'] = $activityMap[$entry['activity']];
                    }
                }

                $merged_data = array_merge($auth_data, $activity_data);
                $list_of_activity_data = array_merge($list_of_activity_data, $merged_data);

                $this->myLogger->logme("error", "Merged data count after processing: " . count($list_of_activity_data));
            }

            usort($list_of_activity_data, function ($a, $b) {
                return strtotime($b['created_at']) <=> strtotime($a['created_at']);
            });

            $this->myLogger->logme("error", "Final sorted list_of_activity_data count: " . count($list_of_activity_data));

            $html = view('hr_activity_history', ['data' => $list_of_activity_data]);

            return $this->respond([
                'status'        => true,
                'message'       => 'User history fetched successfully',
                'data'          => $html,
                'list_of_activity_data' => $list_of_activity_data,
            ]);

        } catch (\Exception $e) {
            $this->myLogger->logme("error", $e->getMessage() . ' --- ' . $e->getLine() . ' ---- ' . $e->getTraceAsString());
            return $this->respond([
                'status'  => false,
                'message' => 'Error: ' . $e->getMessage()
            ], 500);
        }
    }

}