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

/**
 * Super Admin Data Controller
 * Manage master data across all portals
 */
class Data 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'] = 'Master Data Management';
        $data['current_page'] = 'data';
        $data['portals'] = $this->Portal_model->get_all_active();
        $data['portal_filter'] = $portal_filter;
        
        // Get data statistics per portal
        $data['data_stats'] = $this->get_data_stats();
        $data['total_data'] = $this->db->count_all('master_data');
        $data['unassigned_data'] = $this->db->where('portal_id IS NULL OR portal_id = ""', NULL, FALSE)->count_all_results('master_data');
        
        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/data/index', $data);
        $this->load->view('superadmin/layouts/footer');
    }

    private function get_data_stats() {
        return $this->db->query("
            SELECT 
                p.portal_code as code,
                p.portal_name as name,
                COUNT(md.id) as data_count
            FROM portals p
            LEFT JOIN master_data md ON md.portal_id = p.portal_code
            WHERE p.status = 'active'
            GROUP BY p.portal_code, p.portal_name
            ORDER BY data_count DESC
        ")->result();
    }

    public function assign() {
        $data['title'] = 'Assign Data to Portal';
        $data['current_page'] = 'data';
        $data['portals'] = $this->Portal_model->get_all_active();
        
        // Get unassigned data count
        $data['unassigned_count'] = $this->db->where('portal_id IS NULL OR portal_id = ""', NULL, FALSE)->count_all_results('master_data');
        
        if ($this->input->method() == 'post') {
            $portal_id = $this->input->post('portal_id');
            $assign_count = (int)$this->input->post('assign_count');
            $assign_type = $this->input->post('assign_type'); // 'unassigned' or 'all'
            
            if (empty($portal_id)) {
                $this->session->set_flashdata('error', 'Please select a portal');
                redirect('superadmin/data/assign');
            }
            
            if ($assign_count <= 0) {
                $this->session->set_flashdata('error', 'Please enter a valid number of records to assign');
                redirect('superadmin/data/assign');
            }
            
            // Get data to assign
            if ($assign_type == 'unassigned') {
                $this->db->where('portal_id IS NULL OR portal_id = ""', NULL, FALSE);
            }
            $this->db->limit($assign_count);
            $records = $this->db->get('master_data')->result();
            
            $assigned = 0;
            foreach ($records as $record) {
                $this->db->update('master_data', ['portal_id' => $portal_id], ['id' => $record->id]);
                $assigned++;
            }
            
            $this->Super_admin_model->log_activity('data_assigned', "Assigned {$assigned} records to portal: {$portal_id}", $portal_id);
            $this->session->set_flashdata('success', "Successfully assigned {$assigned} records to the selected portal!");
            redirect('superadmin/data');
        }
        
        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/data/assign', $data);
        $this->load->view('superadmin/layouts/footer');
    }

    public function reassign() {
        $data['title'] = 'Reassign Data Between Portals';
        $data['current_page'] = 'data';
        $data['portals'] = $this->Portal_model->get_all_active();
        
        if ($this->input->method() == 'post') {
            $from_portal = $this->input->post('from_portal');
            $to_portal = $this->input->post('to_portal');
            $reassign_count = (int)$this->input->post('reassign_count');
            
            if (empty($from_portal) || empty($to_portal)) {
                $this->session->set_flashdata('error', 'Please select both source and destination portals');
                redirect('superadmin/data/reassign');
            }
            
            if ($from_portal == $to_portal) {
                $this->session->set_flashdata('error', 'Source and destination portals cannot be the same');
                redirect('superadmin/data/reassign');
            }
            
            // Get records from source portal
            $this->db->where('portal_id', $from_portal);
            $this->db->limit($reassign_count);
            $records = $this->db->get('master_data')->result();
            
            $reassigned = 0;
            foreach ($records as $record) {
                $this->db->update('master_data', ['portal_id' => $to_portal], ['id' => $record->id]);
                $reassigned++;
            }
            
            $this->Super_admin_model->log_activity('data_reassigned', "Reassigned {$reassigned} records from {$from_portal} to {$to_portal}", $to_portal);
            $this->session->set_flashdata('success', "Successfully reassigned {$reassigned} records!");
            redirect('superadmin/data');
        }
        
        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/data/reassign', $data);
        $this->load->view('superadmin/layouts/footer');
    }

    public function unassign($portal_code = null) {
        if (!$portal_code) {
            $this->session->set_flashdata('error', 'Portal code is required');
            redirect('superadmin/data');
        }
        
        $count = $this->input->get('count') ?: 'all';
        
        if ($count == 'all') {
            $this->db->update('master_data', ['portal_id' => NULL], ['portal_id' => $portal_code]);
            $affected = $this->db->affected_rows();
        } else {
            $this->db->where('portal_id', $portal_code);
            $this->db->limit((int)$count);
            $records = $this->db->get('master_data')->result();
            
            $affected = 0;
            foreach ($records as $record) {
                $this->db->update('master_data', ['portal_id' => NULL], ['id' => $record->id]);
                $affected++;
            }
        }
        
        $this->Super_admin_model->log_activity('data_unassigned', "Unassigned {$affected} records from portal: {$portal_code}", $portal_code);
        $this->session->set_flashdata('success', "Successfully unassigned {$affected} records from the portal!");
        redirect('superadmin/data');
    }

    public function view($portal_code) {
        $portal = $this->Portal_model->get_by_code($portal_code);
        
        if (!$portal) {
            show_404();
        }
        
        $data['title'] = $portal->name . ' - Data View';
        $data['current_page'] = 'data';
        $data['portal'] = $portal;
        
        // Get paginated data for this portal
        $page = $this->input->get('page') ?: 1;
        $limit = 100;
        $offset = ($page - 1) * $limit;
        
        $this->db->where('portal_id', $portal_code);
        $data['total'] = $this->db->count_all_results('master_data', FALSE);
        
        $this->db->limit($limit, $offset);
        $data['records'] = $this->db->get('master_data')->result();
        
        $data['pagination'] = [
            'current_page' => $page,
            'total_pages' => ceil($data['total'] / $limit),
            'limit' => $limit
        ];
        
        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/data/view', $data);
        $this->load->view('superadmin/layouts/footer');
    }

    /**
     * Assign data to a specific user (admin)
     */
    public function assign_to_user() {
        $data['title'] = 'Assign Data to User';
        $data['current_page'] = 'data';
        $data['portals'] = $this->Portal_model->get_all_active();
        
        // Get users (admins) for each portal
        $data['users'] = $this->db->query("
            SELECT u.id, u.username, u.email, u.portal_id, u.role, p.portal_name
            FROM users u
            LEFT JOIN portals p ON u.portal_id = p.portal_code
            WHERE u.role IN ('admin', 'user') AND u.status = 'active'
            ORDER BY p.portal_name, u.username
        ")->result();
        
        if ($this->input->method() == 'post') {
            $user_id = $this->input->post('user_id');
            $portal_id = $this->input->post('portal_id');
            $assign_count = (int)$this->input->post('assign_count');
            $assign_type = $this->input->post('assign_type'); // 'unassigned_user' or 'portal_data'
            
            if (empty($user_id)) {
                $this->session->set_flashdata('error', 'Please select a user');
                redirect('superadmin/data/assign_to_user');
            }
            
            if ($assign_count <= 0) {
                $this->session->set_flashdata('error', 'Please enter a valid number of records');
                redirect('superadmin/data/assign_to_user');
            }
            
            // Build query based on assign type
            $this->db->select('id');
            if ($assign_type == 'unassigned_user') {
                // Get data that has no assigned user
                $this->db->where('(assigned_user_id IS NULL OR assigned_user_id = 0)', NULL, FALSE);
                if (!empty($portal_id)) {
                    $this->db->where('portal_id', $portal_id);
                }
            } else {
                // Get from portal's data
                if (!empty($portal_id)) {
                    $this->db->where('portal_id', $portal_id);
                }
            }
            $this->db->limit($assign_count);
            $records = $this->db->get('master_data')->result();
            
            $assigned = 0;
            foreach ($records as $record) {
                $this->db->update('master_data', ['assigned_user_id' => $user_id], ['id' => $record->id]);
                $assigned++;
            }
            
            // Get user info for log
            $user = $this->db->get_where('users', ['id' => $user_id])->row();
            $username = $user ? $user->username : 'Unknown';
            
            $this->Super_admin_model->log_activity('data_assigned_to_user', "Assigned {$assigned} records to user: {$username}", $portal_id ?: 'all');
            $this->session->set_flashdata('success', "Successfully assigned {$assigned} records to {$username}!");
            redirect('superadmin/data/user_assignments');
        }
        
        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/data/assign_to_user', $data);
        $this->load->view('superadmin/layouts/footer');
    }

    /**
     * View user data assignments
     */
    public function user_assignments() {
        $data['title'] = 'User Data Assignments';
        $data['current_page'] = 'data';
        $data['portals'] = $this->Portal_model->get_all_active();
        
        // Get assignment stats per user
        $data['assignments'] = $this->db->query("
            SELECT 
                u.id as user_id,
                u.username,
                u.email,
                u.role,
                u.portal_id,
                p.portal_name,
                COUNT(md.id) as assigned_count,
                SUM(CASE WHEN md.status = 'sent' THEN 1 ELSE 0 END) as sent_count,
                SUM(CASE WHEN md.status = 'pending' OR md.status IS NULL THEN 1 ELSE 0 END) as pending_count
            FROM users u
            LEFT JOIN portals p ON u.portal_id = p.portal_code
            LEFT JOIN master_data md ON md.assigned_user_id = u.id
            WHERE u.role IN ('admin', 'user') AND u.status = 'active'
            GROUP BY u.id, u.username, u.email, u.role, u.portal_id, p.portal_name
            ORDER BY assigned_count DESC
        ")->result();
        
        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/data/user_assignments', $data);
        $this->load->view('superadmin/layouts/footer');
    }

    /**
     * View data assigned to a specific user
     */
    public function user_data($user_id) {
        $user = $this->db->get_where('users', ['id' => $user_id])->row();
        
        if (!$user) {
            $this->session->set_flashdata('error', 'User not found');
            redirect('superadmin/data/user_assignments');
        }
        
        $data['title'] = $user->username . ' - Assigned Data';
        $data['current_page'] = 'data';
        $data['user'] = $user;
        
        // Get portal info
        $data['portal'] = $this->Portal_model->get_by_code($user->portal_id);
        
        // Pagination
        $page = $this->input->get('page') ?: 1;
        $limit = 100;
        $offset = ($page - 1) * $limit;
        
        $this->db->where('assigned_user_id', $user_id);
        $data['total'] = $this->db->count_all_results('master_data', FALSE);
        
        $this->db->limit($limit, $offset);
        $data['records'] = $this->db->get('master_data')->result();
        
        $data['pagination'] = [
            'current_page' => $page,
            'total_pages' => ceil($data['total'] / $limit),
            'limit' => $limit
        ];
        
        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/data/user_data', $data);
        $this->load->view('superadmin/layouts/footer');
    }

    /**
     * Unassign data from a user
     */
    public function unassign_from_user($user_id) {
        $user = $this->db->get_where('users', ['id' => $user_id])->row();
        
        if (!$user) {
            $this->session->set_flashdata('error', 'User not found');
            redirect('superadmin/data/user_assignments');
        }
        
        $count = $this->input->get('count') ?: 'all';
        
        if ($count == 'all') {
            $this->db->update('master_data', ['assigned_user_id' => NULL], ['assigned_user_id' => $user_id]);
            $affected = $this->db->affected_rows();
        } else {
            $this->db->where('assigned_user_id', $user_id);
            $this->db->limit((int)$count);
            $records = $this->db->get('master_data')->result();
            
            $affected = 0;
            foreach ($records as $record) {
                $this->db->update('master_data', ['assigned_user_id' => NULL], ['id' => $record->id]);
                $affected++;
            }
        }
        
        $this->Super_admin_model->log_activity('data_unassigned_from_user', "Unassigned {$affected} records from user: {$user->username}", $user->portal_id);
        $this->session->set_flashdata('success', "Successfully unassigned {$affected} records from {$user->username}!");
        redirect('superadmin/data/user_assignments');
    }
}
