<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

require APPPATH . '/libraries/BaseController.php';

class Role extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('admin_model');
        $this->load->model('common');
        $this->load->helper('url');
    }

    public function index()
    {
        $this->roles();
    }

    /**
     * Display role management page
     */
    public function roles()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            // Define new department-based role structure
            $data['departments'] = $this->getDepartmentStructure();
            
            // Get all admins
            $allAdmins = $this->admin_model->getall_admins();
            
            // Count users by department and role
            $data['departmentCounts'] = $this->countByDepartment($allAdmins);
            $data['roleCounts'] = $this->countByRole($allAdmins);
            $data['totalAdmins'] = count($allAdmins);

            $this->global['pageTitle'] = 'StreamAdmin : Role Management';
            $this->loadViews("role", $this->global, $data, NULL);
        }
    }

    /**
     * Get department structure with roles and permissions
     */
    private function getDepartmentStructure()
    {
        return array(
            'admin' => array(
                'name' => 'Admin Panel Department',
                'icon' => 'shield-fill-check',
                    'color' => 'danger',
                'manager' => 'Admin Panel Manager',
                'roles' => array(
                    'admin_panel_manager' => array(
                        'title' => 'Admin Panel Manager',
                        'description' => 'Department Manager',
                        'permissions' => array('Dashboard', 'Admin Users', 'Roles', 'Settings')
                    ),
                    'hr_operations_officer' => array(
                        'title' => 'HR Operations Officer',
                        'description' => 'Oversees recruitment, staff records, and HR compliance',
                        'permissions' => array('Dashboard', 'Admin Users')
                    ),
                    'panel_access_coordinator' => array(
                        'title' => 'Panel Access Coordinator',
                        'description' => 'Manages permissions, access levels, and system roles',
                        'permissions' => array('Dashboard', 'Roles', 'Settings')
                    )
                )
            ),
            'content' => array(
                'name' => 'Media Panel Department',
                'icon' => 'camera-video',
                    'color' => 'primary',
                'manager' => 'Media Panel Manager',
                'roles' => array(
                    'media_panel_manager' => array(
                        'title' => 'Media Panel Manager',
                        'description' => 'Department Manager',
                        'permissions' => array('Dashboard', 'Content', 'Promotions', 'Blue Tick', 'Announcements')
                    ),
                    'content_strategist' => array(
                        'title' => 'Content Strategist',
                        'description' => 'Handles content creation, scheduling, and optimization',
                        'permissions' => array('Dashboard', 'Content')
                    ),
                    'promotion_specialist' => array(
                        'title' => 'Promotion Specialist',
                        'description' => 'Manages marketing campaigns, events, and user engagement',
                        'permissions' => array('Dashboard', 'Promotions', 'Announcements')
                    ),
                    'verification_officer' => array(
                        'title' => 'Verification Officer',
                        'description' => 'Blue Tick Manager - Oversees account verification',
                        'permissions' => array('Dashboard', 'Blue Tick')
                    )
                )
            ),
            'userdepartment' => array(
                'name' => 'User Panel Department',
                'icon' => 'people-fill',
                'color' => 'info',
                'manager' => 'User Panel Manager',
                'roles' => array(
                    'user_panel_manager' => array(
                        'title' => 'User Panel Manager',
                        'description' => 'Department Manager',
                        'permissions' => array('Dashboard', 'Users', 'Reports', 'Warnings')
                    ),
                    'user_accounts_officer' => array(
                        'title' => 'User Accounts Officer',
                        'description' => 'Manages user profiles, onboarding, and engagement',
                        'permissions' => array('Dashboard', 'Users')
                    ),
                    'reports_analyst' => array(
                        'title' => 'Reports Analyst',
                        'description' => 'Handles user reports, escalations, and issue tracking',
                        'permissions' => array('Dashboard', 'Reports')
                    ),
                    'compliance_warnings_officer' => array(
                        'title' => 'Compliance & Warnings Officer',
                        'description' => 'Oversees policy enforcement and warning issuance',
                        'permissions' => array('Dashboard', 'Warnings', 'Reports')
                    )
                )
            ),
            'accountant' => array(
                'name' => 'Finance Panel Department',
                'icon' => 'currency-dollar',
                    'color' => 'success',
                'manager' => 'Finance Panel Manager',
                'roles' => array(
                    'finance_panel_manager' => array(
                        'title' => 'Finance Panel Manager',
                        'description' => 'Department Manager',
                        'permissions' => array('Dashboard', 'Revenue', 'Gifts & Coins', 'Transactions')
                    ),
                    'revenue_analyst' => array(
                        'title' => 'Revenue Analyst',
                        'description' => 'Tracks income streams and monetization performance',
                        'permissions' => array('Dashboard', 'Revenue')
                    ),
                    'virtual_economy_specialist' => array(
                        'title' => 'Virtual Economy Specialist',
                        'description' => 'Gifts & Coins Manager - Manages digital assets',
                        'permissions' => array('Dashboard', 'Gifts & Coins')
                    ),
                    'transaction_auditor' => array(
                        'title' => 'Transaction Auditor',
                        'description' => 'Oversees transaction logs and fraud prevention',
                        'permissions' => array('Dashboard', 'Transactions')
                    )
                )
            )
        );
    }

    /**
     * Count admins by department
     */
    private function countByDepartment($admins)
    {
        $counts = array(
            'admin_panel' => 0,
            'media_panel' => 0,
            'user_panel' => 0,
            'finance_panel' => 0
        );

        foreach ($admins as $admin) {
            if (isset($admin['department'])) {
                $dept = $admin['department'];
                if (isset($counts[$dept])) {
                    $counts[$dept]++;
                }
            }
        }

        return $counts;
    }

    /**
     * Count admins by role
     */
    private function countByRole($admins)
    {
        $counts = array();

        foreach ($admins as $admin) {
            if (isset($admin['roleKey'])) {
                $role = $admin['roleKey'];
                if (!isset($counts[$role])) {
                    $counts[$role] = 0;
                }
                $counts[$role]++;
            }
        }

        return $counts;
    }

    /**
     * View users by department or role
     */
    public function viewByDepartment($department = 'admin_panel')
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $allAdmins = $this->admin_model->getall_admins();
            
            // Filter by department
            $deptUsers = array();
            foreach ($allAdmins as $adminId => $admin) {
                if (isset($admin['department']) && $admin['department'] === $department) {
                    $deptUsers[$adminId] = $admin;
                }
            }

            $departments = $this->getDepartmentStructure();
            $data['department'] = $department;
            $data['departmentUsers'] = $deptUsers;
            $data['departmentInfo'] = isset($departments[$department]) ? $departments[$department] : null;

            $this->global['pageTitle'] = 'StreamAdmin : Department Users';
            $this->loadViews("roles/viewByDepartment", $this->global, $data, NULL);
        }
    }

    /**
     * Get role information via AJAX
     */
    public function getRoleInfo()
    {
        $roleKey = $this->input->post('roleKey');
        $departments = $this->getDepartmentStructure();
        
        $roleInfo = null;
        $departmentName = '';
        
        foreach ($departments as $deptKey => $dept) {
            if (isset($dept['roles'][$roleKey])) {
                $roleInfo = $dept['roles'][$roleKey];
                $roleInfo['departmentKey'] = $deptKey;
                $departmentName = $dept['name'];
                break;
            }
        }
        
        echo json_encode(array(
            'status' => $roleInfo !== null,
            'roleInfo' => $roleInfo,
            'departmentName' => $departmentName
        ));
    }

    /**
     * Get all roles for dropdown
     */
    public function getAllRoles()
    {
        $departments = $this->getDepartmentStructure();
        $allRoles = array();
        
        foreach ($departments as $deptKey => $dept) {
            foreach ($dept['roles'] as $roleKey => $role) {
                $allRoles[] = array(
                    'key' => $roleKey,
                    'title' => $role['title'],
                    'department' => $dept['name'],
                    'departmentKey' => $deptKey
                );
            }
        }
        
        echo json_encode(array('status' => true, 'roles' => $allRoles));
    }
}
