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

/**
 * Super Admin Users Controller
 */
class Users extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('superadmin/Portal_model');
        $this->load->model('superadmin/Super_admin_model');
        $this->_check_super_admin();
    }

    private function _check_super_admin() {
        if ($this->session->userdata('super_admin_logged_in') !== TRUE) {
            redirect('superadmin/auth/login');
        }
    }

    public function index() {
        $portal_filter = $this->input->get('portal');
        
        $data['title'] = 'User Management';
        $data['current_page'] = 'users';
        $data['portals'] = $this->Portal_model->get_all_active();
        $data['portal_filter'] = $portal_filter;
        $data['selected_portal'] = $portal_filter;
        
        if ($portal_filter) {
            $data['users'] = $this->get_users_from_portal($portal_filter);
        } else {
            $data['users'] = $this->get_all_users();
        }
        
        // Calculate stats
        $data['stats'] = [
            'total' => count($data['users']),
            'active' => count(array_filter($data['users'], function($u) { return $u->status == 'active'; })),
            'inactive' => count(array_filter($data['users'], function($u) { return $u->status == 'inactive'; })),
            'admins' => count(array_filter($data['users'], function($u) { return $u->role == 'admin'; }))
        ];
        
        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/users/index', $data);
        $this->load->view('superadmin/layouts/footer');
    }
    
    private function get_all_users() {
        $query = $this->db->query("
            SELECT 
                u.id,
                u.username,
                u.email,
                u.role,
                u.status,
                u.created_at,
                u.portal_id as portal_code,
                p.portal_name as portal_name
            FROM users u 
            LEFT JOIN portals p ON u.portal_id = p.portal_code
            ORDER BY u.created_at DESC
        ");
        
        return $query->result();
    }
    
    private function get_users_from_portal($portal_code) {
        $query = $this->db->query("
            SELECT 
                u.id,
                u.username,
                u.email,
                u.role,
                u.status,
                u.created_at,
                u.portal_id as portal_code,
                p.portal_name as portal_name
            FROM users u 
            LEFT JOIN portals p ON u.portal_id = p.portal_code
            WHERE u.portal_id = ?
            ORDER BY u.created_at DESC
        ", [$portal_code]);
        
        return $query->result();
    }

    public function toggle_status($id) {
        $user = $this->db->get_where('users', ['id' => $id])->row();
        
        if (!$user) {
            $this->session->set_flashdata('error', 'User not found');
            redirect('superadmin/users');
        }
        
        $new_status = ($user->status == 'active') ? 'inactive' : 'active';
        
        $this->db->update('users', ['status' => $new_status], ['id' => $id]);
        
        $this->Super_admin_model->log_activity(
            'user_status_change',
            "Changed user {$user->username} status to {$new_status}",
            $user->portal_id
        );
        
        $this->session->set_flashdata('success', 'User status updated successfully');
        redirect('superadmin/users');
    }

    public function create() {
        $data['title'] = 'Add New User';
        $data['current_page'] = 'users';
        $data['portals'] = $this->Portal_model->get_all_active();

        if ($this->input->method() == 'post') {
            $this->form_validation->set_rules('username', 'Username', 'required|trim|is_unique[users.username]');
            $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
            $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
            $this->form_validation->set_rules('portal_id', 'Portal', 'required');
            $this->form_validation->set_rules('role', 'Role', 'required');

            if ($this->form_validation->run() === TRUE) {
                $user_data = [
                    'username' => $this->input->post('username'),
                    'email' => $this->input->post('email'),
                    'password' => password_hash($this->input->post('password'), PASSWORD_DEFAULT),
                    'portal_id' => $this->input->post('portal_id'),
                    'role' => $this->input->post('role'),
                    'status' => $this->input->post('status') ?: 'active',
                    'created_at' => date('Y-m-d H:i:s')
                ];

                $this->db->insert('users', $user_data);
                $user_id = $this->db->insert_id();
                
                if ($user_id) {
                    $this->Super_admin_model->log_activity('user_created', 'Created user: ' . $user_data['username'], $user_data['portal_id']);
                    $this->session->set_flashdata('success', 'User created successfully!');
                    redirect('superadmin/users');
                } else {
                    $this->session->set_flashdata('error', 'Failed to create user.');
                }
            }
        }

        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/users/create', $data);
        $this->load->view('superadmin/layouts/footer');
    }

    public function edit($id) {
        $data['title'] = 'Edit User';
        $data['current_page'] = 'users';
        $data['portals'] = $this->Portal_model->get_all_active();
        $data['user'] = $this->db->get_where('users', ['id' => $id])->row();

        if (!$data['user']) {
            $this->session->set_flashdata('error', 'User not found.');
            redirect('superadmin/users');
        }

        if ($this->input->method() == 'post') {
            $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
            $this->form_validation->set_rules('portal_id', 'Portal', 'required');
            $this->form_validation->set_rules('role', 'Role', 'required');

            if ($this->form_validation->run() === TRUE) {
                $user_data = [
                    'email' => $this->input->post('email'),
                    'portal_id' => $this->input->post('portal_id'),
                    'role' => $this->input->post('role'),
                    'status' => $this->input->post('status') ?: 'active'
                ];

                // Update password only if provided
                if ($this->input->post('password')) {
                    $user_data['password'] = password_hash($this->input->post('password'), PASSWORD_DEFAULT);
                }

                $this->db->update('users', $user_data, ['id' => $id]);
                
                $this->Super_admin_model->log_activity('user_updated', 'Updated user: ' . $data['user']->username, $user_data['portal_id']);
                $this->session->set_flashdata('success', 'User updated successfully!');
                redirect('superadmin/users');
            }
        }

        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/users/edit', $data);
        $this->load->view('superadmin/layouts/footer');
    }

    public function delete($id) {
        $user = $this->db->get_where('users', ['id' => $id])->row();
        
        if (!$user) {
            $this->session->set_flashdata('error', 'User not found.');
            redirect('superadmin/users');
        }

        $this->db->delete('users', ['id' => $id]);
        $this->Super_admin_model->log_activity('user_deleted', 'Deleted user: ' . $user->username, $user->portal_id);
        $this->session->set_flashdata('success', 'User deleted successfully!');

        redirect('superadmin/users');
    }
}
