<?php

namespace Modules\Settings\Controllers;

use App\Controllers\Auth\AuthController;

class SystemPermissions extends AuthController
{

    public function initController($request, $response, $logger)
    {
            parent::initController($request, $response, $logger);
            $this->data['perms'] = $this->permissionsModel->getAll();
    }
    
    //Create Permission
    public function managePermission()
    {
        if ($this->request->getMethod() === 'POST') {
            $id = $this->request->getPost('id');
            $isEdit = !empty($id);
            
            // Dynamic validation rules based on mode
            $nameRule = $isEdit 
                ? "required|is_unique[permissions.name,id,{$id}]"
                : 'required|is_unique[permissions.name]';

            $rules = [
                'name' => [
                    'label' => 'Permission Name', 
                    'rules' => $nameRule,
                    'errors' => [
                        'is_unique' => 'This permission name already exists. Please choose a different name.'
                    ]
                ],
                'module' => ['label' => 'Module', 'rules' => 'required'],
                'module_section_id' => ['label' => 'Section', 'rules' => 'required'],
            ];

            if(!$this->validate($rules)){
                $validation = \Config\Services::validation();
                $errors = $validation->getErrors();
                
                $errorMessage = implode('<br>', $errors);
                session()->setFlashdata('error', $errorMessage, 5);
                return redirect()->to('administrator/settings/all');
            }

            $parentId = $this->request->getPost('parent_id');
            $this->data = [
                'name' => $this->request->getPost('name'),
                'parent_id' => !empty($parentId) ? $parentId : null,
                'module_section_id' => $this->request->getPost('module_section_id'),
                'module' => $this->request->getPost('module'),
                'description' => $this->request->getPost('description'),
            ];

            if ($id = $this->request->getPost('id')) {
                // Update existing Permission
                $this->permissionsModel->update($id, $this->data);
                $message = 'Permission updated successfully';
            } else {
                // Create new Permission
                $this->permissionsModel->save($this->data);
                $message = 'Permission created successfully';
            }

            //Save Notification
            $ntype = 'setting';
            $createdBy = $this->userdata->user_id;
            $this->sendAdminNotifications($message, $ntype, $createdBy);

            return $this->response->setJSON([
                'success' => true,
                'message' => $message,
                'data' => $this->data
            ]);
        }

        // Edit permission
        if ($this->request->getMethod() === 'GET') {
            
            $id = $this->request->getGet('id');
            if ($id) {
                $permission = $this->permissionsModel->find($id);
                return $this->response->setJSON([
                    'data' => $permission ? $permission : null 
                ]);
            }
            
            return $this->response->setJSON([
                'data' => $this->permissionsModel->findAll()
            ]);
        }
    }

    // Delete method updated for AJAX
    public function deletePermission($id)
    {
        // Only handle GET requests for delete
        if($this->request->getMethod() != "GET") {
            session()->setFlashdata('error', 'Invalid request method');
            return redirect()->to('administrator/settings/all');
        }
        
        $permission = $this->permissionsModel->find($id);
        if (!$permission) {
            session()->setFlashdata('error', 'Permission not found');
            return redirect()->to('administrator/settings/all');
        }

        // Check if permission has children (optional safety check)
        $hasChildren = $this->permissionsModel->where('parent_id', $id)->countAllResults() > 0;
        if ($hasChildren) {
            session()->setFlashdata('error', 'Cannot delete permission that has sub-permissions');
            return redirect()->to('administrator/settings/all');
        }

        if ($this->permissionsModel->delete($id)) {
            $message = 'Permission deleted';
            $ntype = 'setting';
            $createdBy = $this->userdata->user_id;
            
            $this->sendAdminNotifications($message, $ntype, $createdBy);

            session()->setFlashdata('success', 'Permission deleted successfully');
            return redirect()->to('administrator/settings/all');
        } else {
            session()->setFlashdata('error', 'Failed to delete permission');
            return redirect()->to('administrator/settings/all');
        }
    }

    // Helper method to load form data (modules, sections, etc.)
    private function loadPermissionFormData()
    {
        // Load dropdown data needed for the form
        $this->data['perms'] = $this->permissionsModel->findAll(); // For parent dropdown
        $this->data['sections'] = $this->moduleSectionsModel->findAll(); // Assuming you have this model
        
        // You can add more data as needed:
        // $this->data['modules'] = $this->moduleModel->findAll();
        // $this->data['parent_permissions'] = $this->permissionsModel->where('parent_id', null)->findAll();
    }


    /**public function createPermission()
    {
        $this->data['title']    = 'General Settings';
        $this->data['bcrumb']   = 'General Settings';

        if($this->request->getMethod() == "POST")
        {
            $rules = [
                'name'      => [
                    'label' => 'Permission Name', 
                    'rules' => 'required|is_unique[permissions.name]',
                    'errors' => [
                        'is_unique' => 'This permission name already exists. Please choose a different name.'
                    ]
                ],
                'module'    =>  ['label' => 'Module', 'rules' => 'required'],
                'module_section_id' => ['label' => 'Section', 'rules' => 'required'],
            ];

            if(!$this->validate($rules)){
                $validation = \Config\Services::validation();
                $errors = $validation->getErrors();
                
                // Set flash message with all errors
                $errorMessage = implode('<br>', $errors);
                session()->setFlashdata('error', $errorMessage, 5);
                return redirect()->to('administrator/settings/all');
            }

            $parentId = $this->request->getVar('parent_id');
            $pData = [
                'name' => $this->request->getVar('name'),
                'parent_id' => !empty($parentId) ? $parentId : Null, //$this->getVarOrNull('parent_id')
                'module_section_id' => $this->request->getVar('module_section_id'),
                'module'    => $this->request->getVar('module'),
                'description' => $this->request->getVar('description'),
            ];
            if($this->permissionsModel->save($pData))
            {
                //For notifications
                $message  = 'Permission created';
                $ntype    = 'setting';
                $createdBy = $this->userdata->user_id;
                $this->sendAdminNotifications($message, $ntype, $createdBy);

                session()->setFlashdata('success', 'Permission created successfully', 3);
            }else{
                session()->setFlashdata('error', 'Permission Not created', 3);
            }
            return redirect()->to('administrator/settings/all');
        }
        return view('Modules\Settings\Views\general\index', $this->data);
    }**/

    // GROUP PERMISSIONS
    public function getGroupPermissions($groupId)
    {
        $permissions = $this->usergrouppermissionsModel
            ->select('permissions.id, permissions.module, permissions.name')
            ->join('permissions', 'permissions.id = user_group_permissions.permission_id')
            ->where('group_id', $groupId)
            ->findAll();

        return $this->response->setJSON($permissions);
    }

    // Update permissions (JSON)
    public function updateGroupPermission()
    {
        $groupId = $this->request->getPost('group_id');
        $permissionId = $this->request->getPost('permission_id');
        $action = $this->request->getPost('action');

        if ($action === 'add') {
            $this->usergrouppermissionsModel->save([
                'group_id' => $groupId,
                'permission_id' => $permissionId
            ]);
        } else {
            $this->usergrouppermissionsModel
                ->where('group_id', $groupId)
                ->where('permission_id', $permissionId)
                ->delete();
        }

        //For notifications
        $message  = 'Group Permission '.$action;
        $ntype    = 'setting';
        $createdBy = $this->userdata->user_id;
        $this->sendAdminNotifications($message, $ntype, $createdBy);

        return $this->response->setJSON(['success' => true]);
    }

}