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

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

use Google\Cloud\Firestore\FirestoreClient;

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

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

    /**
     * Test method to verify controller works
     */
    public function test()
    {
        echo "Admin Controller is working!<br>";
        echo "Firebase library loaded: " . (isset($this->firebase) ? "Yes" : "No") . "<br>";
        echo "Admin model loaded: " . (isset($this->admin_model) ? "Yes" : "No") . "<br>";
        echo "<br><a href='" . base_url('admin/addAdmin') . "'>Go to Add Admin</a>";
    }

    /**
     * Display all admin users
     */
    public function admins()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $searchText = '';
            if (!empty($this->input->post('searchText'))) {
                $searchText = $this->security->xss_clean($this->input->post('searchText'));
            }
            $data['searchText'] = $searchText;

            // Get all admins from Firebase
            $allAdmins = $this->admin_model->getall_admins();
            
            // Sort by createdDate descending (newest first)
            if (!empty($allAdmins)) {
                uasort($allAdmins, function($a, $b) {
                    $aDate = isset($a['createdDate']) ? $a['createdDate'] : 0;
                    $bDate = isset($b['createdDate']) ? $b['createdDate'] : 0;
                    return $bDate - $aDate;
                });
            }
            
            // Filter based on search text if provided
            if (!empty($searchText)) {
                $filtered = array();
                foreach ($allAdmins as $key => $admin) {
                    if (stripos($admin['fullName'], $searchText) !== false || 
                        stripos($admin['email'], $searchText) !== false ||
                        (isset($admin['role']) && stripos($admin['role'], $searchText) !== false)) {
                        $filtered[$key] = $admin;
                    }
                }
                $data['admins'] = $filtered;
            } else {
                $data['admins'] = $allAdmins;
            }

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

    /**
     * Filter by department
     */
    public function byDepartment($department = 'admin')
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $this->load->helper('role');
            
            $searchText = '';
            if (!empty($this->input->post('searchText'))) {
                $searchText = $this->security->xss_clean($this->input->post('searchText'));
            }
            $data['searchText'] = $searchText;
            $data['filterDepartment'] = $department;

            // Get all admins from Firebase
            $allAdmins = $this->admin_model->getall_admins();
            // echo '<pre>';
            // print_r($allAdmins);
            // echo '</pre>';
            
            // Filter by department
            $filteredByDepartment = array();
            foreach ($allAdmins as $key => $admin) {
                if (isset($admin['role']) && $admin['role'] === $department) {
                    $filteredByDepartment[$key] = $admin;
                }
            }
            
            // Filter based on search text if provided
            if (!empty($searchText)) {
                $filtered = array();
                foreach ($filteredByDepartment as $key => $admin) {
                    if (stripos($admin['fullName'], $searchText) !== false || 
                        stripos($admin['email'], $searchText) !== false) {
                        $filtered[$key] = $admin;
                    }
                }
                $data['admins'] = $filtered;
            } else {
                $data['admins'] = $filteredByDepartment;
            }

            $this->global['pageTitle'] = 'StreamAdmin : Admin Management - ' . get_department_info($department)['name'];
            $this->loadViews("admins/admins", $this->global, $data, NULL);
        }
    }

    /**
     * Filter by role (Legacy support)
     */
    public function byRole($role = 'admin')
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $searchText = '';
            if (!empty($this->input->post('searchText'))) {
                $searchText = $this->security->xss_clean($this->input->post('searchText'));
            }
            $data['searchText'] = $searchText;
            $data['filterRole'] = $role;

            // Get all admins from Firebase
            $allAdmins = $this->admin_model->getall_admins();
            
            // Filter by role
            $filteredByRole = array();
            foreach ($allAdmins as $key => $admin) {
                $roleKey = isset($admin['roleKey']) ? $admin['roleKey'] : (isset($admin['role']) ? $admin['role'] : '');
                if (strtolower($roleKey) === strtolower($role)) {
                    $filteredByRole[$key] = $admin;
                }
            }
            
            // Apply search filter
            if (!empty($searchText)) {
                $filtered = array();
                foreach ($filteredByRole as $key => $admin) {
                    if (stripos($admin['fullName'], $searchText) !== false || 
                        stripos($admin['email'], $searchText) !== false) {
                        $filtered[$key] = $admin;
                    }
                }
                $data['admins'] = $filtered;
            } else {
                $data['admins'] = $filteredByRole;
            }

            $this->global['pageTitle'] = 'StreamAdmin : ' . ucfirst($role) . ' Users';
            $this->loadViews("admins/admins", $this->global, $data, NULL);
        }
    }

    /**
     * Display add admin form
     */
    public function addAdmin()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            try {
                $this->global['pageTitle'] = 'StreamAdmin : Add New Admin';
                $data = array(); // Empty data array for the view
                $this->loadViews("admins/addAdmin", $this->global, $data, NULL);
            } catch (Exception $e) {
                log_message('error', 'Error loading addAdmin view: ' . $e->getMessage());
                show_error('Unable to load the add admin page: ' . $e->getMessage());
            }
        }
    }

    /**
     * Add new admin user
     */
    public function addNewAdmin()
    {


        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $this->load->library('form_validation');
            $this->load->helper('role');

            $this->form_validation->set_rules('fullName', 'Full Name', 'trim|required|max_length[128]');
            $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|max_length[128]');
            $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|max_length[20]');
            $this->form_validation->set_rules('phone', 'Phone', 'required');

            if ($this->form_validation->run() == FALSE) {
                $this->addAdmin();
            } else {
                $fullName = ucwords(strtolower($this->security->xss_clean($this->input->post('fullName'))));
                $email = strtolower($this->security->xss_clean($this->input->post('email')));
                $password = $this->input->post('password');
                $role = $this->security->xss_clean($this->input->post('role'));
                $phone = $this->security->xss_clean($this->input->post('phone'));

                $currentTime = time() * 1000; // Convert to milliseconds
                
                $adminInfo = array(
                    'fullName' => $fullName,
                    'email' => $email,
                    'password' => $password, // Will be handled by Firebase Auth
                    'role' => $role,
                    'phone' => $phone,
                    'isActive' => true,
                    'createdDate' => $currentTime,
                    'lastLoginDate' => null
                );
                $result = $this->admin_model->add_admin($adminInfo);
                
                if ($result) {
                    $this->session->set_flashdata('success', 'New Admin user created successfully');
                } else {
                    $this->session->set_flashdata('error', 'Admin creation failed');
                }

                redirect('admin/admins');
            }
        }
    }

    /**
     * View admin details
     */
    public function viewAdmin($adminId = NULL)
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            if ($adminId == null) {
                redirect('admin/admins');
            }

            $data['adminInfo'] = $this->admin_model->get_admin($adminId);
            $data['adminId'] = $adminId;

            $this->global['pageTitle'] = 'StreamAdmin : Admin Details';
            $this->loadViews("admins/viewAdmin", $this->global, $data, NULL);
        }
    }

    /**
     * Edit admin form
     */
    public function editAdmin($adminId = NULL)
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            if ($adminId == null) {
                redirect('admin/admins');
            }

            $data['adminInfo'] = $this->admin_model->get_admin($adminId);
            $data['adminId'] = $adminId;

            $this->global['pageTitle'] = 'StreamAdmin : Edit Admin';
            $this->loadViews("admins/editAdmin", $this->global, $data, NULL);
        }
    }

    /**
     * Update admin
     */
    public function updateAdmin()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $this->load->library('form_validation');
            $this->load->helper('role');

            $adminId = $this->input->post('adminId');

            $this->form_validation->set_rules('fullName', 'Full Name', 'trim|required|max_length[128]');
            $this->form_validation->set_rules('department', 'Department', 'required');
            $this->form_validation->set_rules('roleKey', 'Role', 'required');

            if ($this->form_validation->run() == FALSE) {
                $this->editAdmin($adminId);
            } else {
                $fullName = ucwords(strtolower($this->security->xss_clean($this->input->post('fullName'))));
                $department = $this->security->xss_clean($this->input->post('department'));
                $roleKey = $this->security->xss_clean($this->input->post('roleKey'));
                $phone = $this->security->xss_clean($this->input->post('phone'));
                $isActive = $this->input->post('isActive') === 'true' ? true : false;

                // Get role information
                $roleInfo = get_role_info($roleKey);

                $adminData = array(
                    'fullName' => $fullName,
                    'department' => $department,
                    'departmentName' => $roleInfo['department'],
                    'roleKey' => $roleKey,
                    'roleTitle' => $roleInfo['title'],
                    'phone' => $phone,
                    'isActive' => $isActive
                );

                $result = $this->admin_model->update_admin($adminId, $adminData);

                if ($result) {
                    $this->session->set_flashdata('success', 'Admin updated successfully');
                } else {
                    $this->session->set_flashdata('error', 'Admin update failed');
                }

                redirect('admin/admins');
            }
        }
    }

    /**
     * Update admin password
     */
    public function updatePassword()
    {
        if (!$this->isAdmin()) {
            echo (json_encode(array('status' => 'access')));
        } else {
            $adminId = $this->input->post('adminId');
            $newPassword = $this->input->post('newPassword');

            if (empty($adminId) || empty($newPassword)) {
                echo (json_encode(array('status' => FALSE, 'message' => 'Invalid data')));
                return;
            }

            $result = $this->admin_model->update_password($adminId, $newPassword);

            if ($result) {
                echo (json_encode(array('status' => TRUE, 'message' => 'Password updated successfully')));
            } else {
                echo (json_encode(array('status' => FALSE, 'message' => 'Password update failed')));
            }
        }
    }

    /**
     * Toggle admin status
     */
    public function toggleStatus()
    {
        if (!$this->isAdmin()) {
            echo (json_encode(array('status' => 'access')));
        } else {
            $adminId = $this->input->post('adminId');
            $currentStatus = $this->input->post('currentStatus') === 'true' ? true : false;

            if (empty($adminId)) {
                echo (json_encode(array('status' => FALSE, 'message' => 'Invalid data')));
                return;
            }

            // Update Firestore
            $adminData = array(
                'isActive' => !$currentStatus
            );

            $firestoreResult = $this->admin_model->update_admin($adminId, $adminData);

            if ($firestoreResult) {
                // Update Firebase Auth
                $this->load->model('common');
                $authStatus = $currentStatus ? 'active' : 'disable';
                $authResult = $this->common->update_customerstatus($adminId, $authStatus);

                if ($authResult) {
                    echo (json_encode(array('status' => TRUE, 'message' => 'Admin status updated successfully')));
                } else {
                    // Rollback
                    $this->admin_model->update_admin($adminId, array('isActive' => $currentStatus));
                    echo (json_encode(array('status' => FALSE, 'message' => 'Failed to update Firebase Auth')));
                }
            } else {
                echo (json_encode(array('status' => FALSE, 'message' => 'Failed to update admin status')));
            }
        }
    }

    /**
     * Delete admin
     */
    public function deleteAdmin()
    {
        if (!$this->isAdmin()) {
            echo (json_encode(array('status' => 'access')));
        } else {
            $adminId = $this->input->post('adminId');

            if (empty($adminId)) {
                echo (json_encode(array('status' => FALSE, 'message' => 'Admin ID is required')));
                return;
            }

            // Get admin details before deletion
            $adminInfo = $this->admin_model->get_admin($adminId);
            
            if (empty($adminInfo)) {
                echo (json_encode(array('status' => FALSE, 'message' => 'Admin not found')));
                return;
            }

            // Delete from Firebase Auth first
            $authResult = $this->admin_model->delete_admin_auth($adminId);

            if ($authResult) {
                // Delete from Firestore Admin collection
                $firestoreResult = $this->admin_model->delete_admin($adminId);
                
                if ($firestoreResult) {
                    echo (json_encode(array('status' => TRUE, 'message' => 'Admin deleted successfully from both Auth and Firestore')));
                } else {
                    echo (json_encode(array('status' => FALSE, 'message' => 'Admin deleted from Auth but Firestore deletion failed')));
                }
            } else {
                echo (json_encode(array('status' => FALSE, 'message' => 'Failed to delete admin from Firebase Auth')));
            }
        }
    }

    /**
     * Get permissions array based on role
     */
    private function getPermissionsByRole($role)
    {
        $permissions = array();
        
        switch($role) {
            case 'admin':
                $permissions = array(
                    'dashboard' => true,
                    'users' => true,
                    'customers' => true,
                    'announcements' => true,
                    'promotions' => true,
                    'gifts' => true,
                    'transactions' => true,
                    'revenue' => true,
                    'reports' => true,
                    'settings' => true,
                    'admins' => true,
                    'roles' => true
                );
                break;
                
            case 'content':
                $permissions = array(
                    'dashboard' => true,
                    'users' => false,
                    'customers' => false,
                    'announcements' => false,
                    'promotions' => true,
                    'gifts' => true,
                    'transactions' => false,
                    'revenue' => false,
                    'reports' => false,
                    'settings' => false,
                    'admins' => false,
                    'roles' => false
                );
                break;
                
            case 'accountant':
                $permissions = array(
                    'dashboard' => true,
                    'users' => false,
                    'customers' => false,
                    'announcements' => false,
                    'promotions' => false,
                    'gifts' => false,
                    'transactions' => true,
                    'revenue' => true,
                    'reports' => true,
                    'settings' => false,
                    'admins' => false,
                    'roles' => false
                );
                break;
                
            default:
                $permissions = array(
                    'dashboard' => true
                );
        }
        
        return $permissions;
    }

    /**
     * Get role permissions (AJAX)
     */
    public function getRolePermissions()
    {
        $role = $this->input->post('role');
        
        if (empty($role)) {
            echo json_encode(array('status' => FALSE));
            return;
        }
        
        $permissions = $this->getPermissionsByRole($role);
        echo json_encode(array('status' => TRUE, 'permissions' => $permissions));
    }
}

