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

class Admin extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('User_model');
        $this->load->library('session');
        $this->load->helper('url', 'form');
        $this->load->library('form_validation');
        
        if (!$this->session->userdata('logged_in')) {
            redirect('auth/login');
        }
        
        // Get current user and set timezone
        $this->current_user = $this->User_model->get_user_by_id($this->session->userdata('user_id'));
        $this->is_admin = ($this->current_user->role === 'admin');
        
        // Set timezone to IST
        date_default_timezone_set('Asia/Kolkata');
    }
// In Admin controller - ensure this method exists
public function get_agencies() {
    try {
        $search = $this->input->get('search');
        
        $this->db->where('status', 'active');
        
        if (!empty($search)) {
            $this->db->group_start();
            $this->db->like('name', $search);
            $this->db->or_like('contact_email', $search);
            $this->db->or_like('contact_phone', $search);
            $this->db->group_end();
        }
        
        $this->db->order_by('name', 'ASC');
        $agencies = $this->db->get('agencies')->result_array();
        
        echo json_encode([
            'success' => true,
            'agencies' => $agencies
        ]);
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'error' => $e->getMessage()
        ]);
    }
}
    public function dashboard() {
        $data['page_title'] = 'Dashboard';
        $data['user'] = $this->current_user;
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('admin/dashboard_content', $data);
        $this->load->view('templates/footer');
    }

    public function portfolio() {
        $data['page_title'] = 'Portfolio Management';
        $data['user'] = $this->current_user;
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('admin/portfolio', $data);
        $this->load->view('templates/footer');
    }

    public function enquiries() {
        $data['page_title'] = 'Enquiries Management';
        $data['user'] = $this->current_user;
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('admin/enquiries', $data);
        $this->load->view('templates/footer');
    }

    public function categories() {
        $data['page_title'] = 'Categories Management';
        $data['user'] = $this->current_user;
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('admin/categories', $data);
        $this->load->view('templates/footer');
    }

    public function users() {
        // Only admin can access user management
        if (!$this->is_admin) {
            show_error('You do not have permission to access this page.', 403, 'Access Denied');
        }

        $data['page_title'] = 'User Management';
        $data['user'] = $this->current_user;
        $data['users'] = $this->User_model->get_all_users();
        $data['user_stats'] = $this->User_model->get_user_stats();
        $data['is_admin'] = $this->is_admin;
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('admin/users_list', $data);
        $this->load->view('templates/footer');
    }

    public function create_user() {
        // Check if user is admin
        if (!$this->is_admin) {
            $response = array(
                'success' => false,
                'errors' => array('general' => 'Only administrators can create new users.')
            );
            header('Content-Type: application/json');
            echo json_encode($response);
            return;
        }

        $this->form_validation->set_rules('username', 'Username', 'required|min_length[3]|max_length[50]|is_unique[users.username]');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
        $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]');
        $this->form_validation->set_rules('full_name', 'Full Name', 'required|min_length[2]|max_length[100]');
        $this->form_validation->set_rules('role', 'Role', 'required|in_list[admin,user]');

        if ($this->form_validation->run() === FALSE) {
            $response = array(
                'success' => false,
                'errors' => $this->form_validation->error_array()
            );
        } else {
            $user_data = array(
                'username' => $this->input->post('username'),
                'password' => $this->input->post('password'),
                'full_name' => $this->input->post('full_name'),
                'role' => $this->input->post('role')
            );

            $user_id = $this->User_model->create_user($user_data);
            
            if ($user_id) {
                $response = array(
                    'success' => true,
                    'message' => 'User created successfully!',
                    'user_id' => $user_id
                );
            } else {
                $response = array(
                    'success' => false,
                    'errors' => array('general' => 'Failed to create user. Please try again.')
                );
            }
        }

        header('Content-Type: application/json');
        echo json_encode($response);
    }

    public function update_user($user_id) {
        // Check if user is admin or updating their own profile
        if (!$this->is_admin && $user_id != $this->current_user->id) {
            $response = array(
                'success' => false,
                'errors' => array('general' => 'You can only update your own profile.')
            );
            header('Content-Type: application/json');
            echo json_encode($response);
            return;
        }

        $user = $this->User_model->get_user_by_id($user_id);
        if (!$user) {
            show_404();
        }

        // Check if username is unique excluding current user
        $is_unique = $this->input->post('username') != $user->username ? '|is_unique[users.username]' : '';

        $this->form_validation->set_rules('username', 'Username', 'required|min_length[3]|max_length[50]' . $is_unique);
        $this->form_validation->set_rules('full_name', 'Full Name', 'required|min_length[2]|max_length[100]');
        
        // Only admin can change role
        if ($this->is_admin) {
            $this->form_validation->set_rules('role', 'Role', 'required|in_list[admin,user]');
        }
        
        // Password is optional for updates
        if ($this->input->post('password')) {
            $this->form_validation->set_rules('password', 'Password', 'min_length[6]');
            $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'matches[password]');
        }

        if ($this->form_validation->run() === FALSE) {
            $response = array(
                'success' => false,
                'errors' => $this->form_validation->error_array()
            );
        } else {
            $user_data = array(
                'username' => $this->input->post('username'),
                'full_name' => $this->input->post('full_name')
            );

            // Only admin can change role
            if ($this->is_admin) {
                $user_data['role'] = $this->input->post('role');
            }

            // Only update password if provided
            if ($this->input->post('password')) {
                $user_data['password'] = $this->input->post('password');
            }

            $result = $this->User_model->update_user($user_id, $user_data);
            
            if ($result) {
                $response = array(
                    'success' => true,
                    'message' => 'User updated successfully!'
                );
            } else {
                $response = array(
                    'success' => false,
                    'errors' => array('general' => 'Failed to update user. Please try again.')
                );
            }
        }

        header('Content-Type: application/json');
        echo json_encode($response);
    }

    public function delete_user($user_id) {
        // Only admin can delete users
        if (!$this->is_admin) {
            $response = array(
                'success' => false,
                'message' => 'Only administrators can delete users.'
            );
            header('Content-Type: application/json');
            echo json_encode($response);
            return;
        }

        // Prevent users from deleting themselves
        if ($user_id == $this->current_user->id) {
            $response = array(
                'success' => false,
                'message' => 'You cannot delete your own account!'
            );
        } else {
            $result = $this->User_model->delete_user($user_id);
            
            if ($result) {
                $response = array(
                    'success' => true,
                    'message' => 'User deleted successfully!'
                );
            } else {
                $response = array(
                    'success' => false,
                    'message' => 'Failed to delete user. Please try again.'
                );
            }
        }

        header('Content-Type: application/json');
        echo json_encode($response);
    }

    // ==================== DASHBOARD METHODS ====================

   public function get_dashboard_data() {
    try {
        // Set header first to ensure JSON response
        header('Content-Type: application/json');
        
        $data = array();
        
        // Get total counts with error handling
        $data['stats'] = array(
            'total_projects' => $this->db->count_all('projects'),
            'total_models' => $this->db->count_all('extracted_data'),
            'total_pdfs' => $this->db->count_all('project_pdfs'),
            'total_images' => $this->db->count_all('extracted_images')
        );
        
        // Get project status breakdown
        $data['projects'] = array('created' => 0, 'processing' => 0, 'completed' => 0);
        
        $this->db->select('status, COUNT(*) as count');
        $this->db->group_by('status');
        $projects_query = $this->db->get('projects');
        
        if ($projects_query->num_rows() > 0) {
            foreach ($projects_query->result() as $project) {
                if (isset($project->status) && isset($data['projects'][$project->status])) {
                    $data['projects'][$project->status] = (int)$project->count;
                }
            }
        }
        
        // Get models distribution
        $data['models'] = array('labels' => array(), 'data' => array());
        
        $this->db->select('p.name, COUNT(ed.id) as model_count');
        $this->db->from('projects p');
        $this->db->join('project_pdfs pp', 'pp.project_id = p.id', 'left');
        $this->db->join('extracted_data ed', 'ed.pdf_id = pp.id', 'left');
        $this->db->group_by('p.id, p.name');
        $this->db->order_by('model_count', 'DESC');
        $this->db->limit(10);
        $models_query = $this->db->get();
        
        if ($models_query->num_rows() > 0) {
            foreach ($models_query->result() as $item) {
                $data['models']['labels'][] = $item->name ?: 'Unnamed Project';
                $data['models']['data'][] = (int)$item->model_count;
            }
        } else {
            // Sample data if no real data exists
            $data['models']['labels'] = ['Project A', 'Project B', 'Project C'];
            $data['models']['data'] = [5, 3, 7];
        }
        
        // Get storage info
        $data['storage'] = $this->calculate_storage_usage();
        
        echo json_encode(array('success' => true, 'data' => $data));
        return;
        
    } catch (Exception $e) {
        // Log the error
        error_log("Dashboard data error: " . $e->getMessage());
        
        // Return safe default data
        $default_data = array(
            'stats' => array(
                'total_projects' => 0,
                'total_models' => 0,
                'total_pdfs' => 0,
                'total_images' => 0
            ),
            'projects' => array('created' => 0, 'processing' => 0, 'completed' => 0),
            'models' => array(
                'labels' => ['Sample Data'],
                'data' => [1]
            ),
            'storage' => array('total' => 0, 'pdfs' => 0, 'images' => 0, 'temp' => 0)
        );
        
        echo json_encode(array('success' => false, 'data' => $default_data, 'error' => $e->getMessage()));
        return;
    }
}
private function calculate_storage_usage() {
    $storage = array(
        'total' => 0,
        'pdfs' => 0,
        'images' => 0,
        'temp' => 0
    );
    
    try {
        // Calculate PDF storage from project_pdfs table - using file_size column
        $this->db->select('SUM(file_size) as total_size');
        $pdf_size = $this->db->get('project_pdfs')->row();
        if ($pdf_size && $pdf_size->total_size) {
            $storage['pdfs'] = (float)$pdf_size->total_size;
            $storage['total'] += $storage['pdfs'];
        }
        
        // Calculate image storage from extracted_images table - using image_size column
        $this->db->select('SUM(image_size) as total_size'); // CHANGED: file_size to image_size
        $image_size = $this->db->get('extracted_images')->row();
        if ($image_size && $image_size->total_size) {
            $storage['images'] = (float)$image_size->total_size;
            $storage['total'] += $storage['images'];
        }
        
        // Calculate temp storage
        $temp_dir = './uploads/temp/';
        if (is_dir($temp_dir)) {
            $storage['temp'] = $this->calculate_directory_size($temp_dir);
            $storage['total'] += $storage['temp'];
        }
        
    } catch (Exception $e) {
        error_log("Storage calculation error: " . $e->getMessage());
        // Return zeros if calculation fails
    }
    
    return $storage;
}

private function calculate_directory_size($path) {
    $size = 0;
    if (!is_dir($path)) return 0;
    
    try {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS)
        );
        
        foreach ($iterator as $file) {
            if ($file->isFile()) {
                $size += $file->getSize();
            }
        }
    } catch (Exception $e) {
        error_log("Directory size calculation error for $path: " . $e->getMessage());
    }
    
    return $size;
}
    public function get_recent_projects() {
        try {
            $this->db->order_by('created_at', 'DESC');
            $this->db->limit(6);
            $projects = $this->db->get('projects')->result();
            
            header('Content-Type: application/json');
            echo json_encode(array('success' => true, 'projects' => $projects));
            
        } catch (Exception $e) {
            header('Content-Type: application/json');
            echo json_encode(array('success' => false, 'error' => $e->getMessage()));
        }
    }

    public function get_recent_activity() {
        try {
            $activities = array();
            
            // Recent user logins
            $this->db->select('ul.login_time, u.full_name, u.role');
            $this->db->from('user_login_history ul');
            $this->db->join('users u', 'u.id = ul.user_id');
            $this->db->order_by('ul.login_time', 'DESC');
            $this->db->limit(10);
            $logins = $this->db->get()->result();
            
            foreach ($logins as $login) {
                $activities[] = array(
                    'title' => $login->full_name . ' logged in',
                    'time' => $this->format_ist_date($login->login_time),
                    'icon' => 'fas fa-sign-in-alt',
                    'color' => '#e8f5e8'
                );
            }
            
            // Recent project creations
            $this->db->select('name, created_at');
            $this->db->from('projects');
            $this->db->order_by('created_at', 'DESC');
            $this->db->limit(5);
            $projects = $this->db->get()->result();
            
            foreach ($projects as $project) {
                $activities[] = array(
                    'title' => 'Project "' . $project->name . '" created',
                    'time' => $this->format_ist_date($project->created_at),
                    'icon' => 'fas fa-folder-plus',
                    'color' => '#e3f2fd'
                );
            }
            
            // Recent model extractions
            $this->db->select('ed.created_at, p.name as project_name, ed.model_name');
            $this->db->from('extracted_data ed');
            $this->db->join('project_pdfs pp', 'pp.id = ed.pdf_id');
            $this->db->join('projects p', 'p.id = pp.project_id');
            $this->db->order_by('ed.created_at', 'DESC');
            $this->db->limit(5);
            $extractions = $this->db->get()->result();
            
            foreach ($extractions as $extraction) {
                $activities[] = array(
                    'title' => 'Model data extracted: ' . ($extraction->model_name ?: 'Unknown'),
                    'time' => $this->format_ist_date($extraction->created_at),
                    'icon' => 'fas fa-user-plus',
                    'color' => '#fff3e0'
                );
            }
            
            // Sort by time and limit to 10 most recent
            usort($activities, function($a, $b) {
                return strtotime($b['time']) - strtotime($a['time']);
            });
            
            $activities = array_slice($activities, 0, 10);
            
            header('Content-Type: application/json');
            echo json_encode(array('success' => true, 'activities' => $activities));
            
        } catch (Exception $e) {
            header('Content-Type: application/json');
            echo json_encode(array('success' => false, 'error' => $e->getMessage()));
        }
    }
   

    // ==================== ANALYTICS METHODS ====================

    public function analytics() {
        $data['page_title'] = 'Analytics';
        $data['user'] = $this->current_user;
        
        // Get real analytics data
        $data['analytics_data'] = $this->get_analytics_data();
        $data['agency_stats'] = $this->get_agency_stats();
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('admin/analytics', $data);
        $this->load->view('templates/footer');
    }

    private function get_analytics_data() {
        $data = [];
        
        try {
            // Total counts with proper table references
            $data['total_projects'] = $this->db->count_all('projects');
            $data['total_models'] = $this->db->count_all('extracted_data'); // Using extracted_data table
            $data['total_pdfs'] = $this->db->count_all('project_pdfs');
            $data['total_users'] = $this->db->count_all('users');
            
            // Ensure models count matches PDFs count for display
            if ($data['total_models'] === 0 && $data['total_pdfs'] > 0) {
                $data['total_models'] = $data['total_pdfs'];
            }
            
            // Project status breakdown
            $this->db->select('status, COUNT(*) as count');
            $this->db->group_by('status');
            $status_data = $this->db->get('projects')->result();
            
            $data['project_status'] = [
                'created' => 0,
                'processing' => 0, 
                'completed' => 0,
                'failed' => 0
            ];
            
            foreach ($status_data as $status) {
                if (isset($data['project_status'][$status->status])) {
                    $data['project_status'][$status->status] = (int)$status->count;
                }
            }
            
            // Models per project distribution - FIXED: Using extracted_data with proper joins
            $this->db->select('p.id, p.name, COUNT(ed.id) as model_count');
            $this->db->from('projects p');
            $this->db->join('project_pdfs pp', 'pp.project_id = p.id', 'left');
            $this->db->join('extracted_data ed', 'ed.pdf_id = pp.id', 'left');
            $this->db->group_by('p.id, p.name');
            $this->db->order_by('model_count', 'DESC');
            $this->db->limit(10);
            $models_data = $this->db->get()->result();
            
            $data['models_distribution'] = [
                'labels' => [],
                'data' => []
            ];
            
            foreach ($models_data as $item) {
                $data['models_distribution']['labels'][] = $item->name ?: 'Unnamed Project';
                $data['models_distribution']['data'][] = (int)$item->model_count;
            }
            
            // If no models data, create sample data for chart
            if (empty($data['models_distribution']['labels'])) {
                $this->db->select('id, name');
                $this->db->from('projects');
                $this->db->limit(5);
                $projects = $this->db->get()->result();
                
                foreach ($projects as $project) {
                    $data['models_distribution']['labels'][] = $project->name ?: 'Project ' . $project->id;
                    // Get actual count for this project
                    $this->db->select('COUNT(ed.id) as model_count');
                    $this->db->from('extracted_data ed');
                    $this->db->join('project_pdfs pp', 'pp.id = ed.pdf_id');
                    $this->db->where('pp.project_id', $project->id);
                    $count_result = $this->db->get()->row();
                    $data['models_distribution']['data'][] = $count_result->model_count ?: 0;
                }
            }
            
            // Monthly growth data - FIXED: Using extracted_data
            $data['monthly_growth'] = $this->get_monthly_growth();
            
        } catch (Exception $e) {
            error_log("Analytics data error: " . $e->getMessage());
            // Return default data on error
            $data = $this->get_default_analytics_data();
        }
        
        return $data;
    }

    private function get_monthly_growth() {
        $monthly_data = [];
        
        for ($i = 5; $i >= 0; $i--) {
            $month = date('Y-m', strtotime("-$i months"));
            $start_date = $month . '-01';
            $end_date = date('Y-m-t', strtotime($start_date));
            
            // Projects created this month
            $this->db->where('created_at >=', $start_date);
            $this->db->where('created_at <=', $end_date);
            $projects = $this->db->count_all_results('projects');
            
            // Models extracted this month - FIXED: using extracted_data
            $this->db->where('created_at >=', $start_date);
            $this->db->where('created_at <=', $end_date);
            $models = $this->db->count_all_results('extracted_data');
            
            $monthly_data[] = [
                'month' => date('M Y', strtotime($start_date)),
                'projects' => $projects,
                'models' => $models
            ];
        }
        
        return $monthly_data;
    }

    private function get_default_analytics_data() {
        return [
            'total_projects' => 0,
            'total_models' => 0,
            'total_pdfs' => 0,
            'total_users' => 0,
            'project_status' => [
                'created' => 0,
                'processing' => 0,
                'completed' => 0,
                'failed' => 0
            ],
            'models_distribution' => [
                'labels' => ['No Data'],
                'data' => [0]
            ],
            'monthly_growth' => []
        ];
    }

    // ==================== ACTIVITY METHODS ====================

    public function activity() {
        $data['page_title'] = 'Activity';
        $data['user'] = $this->current_user;
        
        // Get all users for filter
        $data['users'] = $this->User_model->get_all_users();
        
        // Get activity data
        $data['activities'] = $this->get_activity_data();
        $data['activity_stats'] = $this->get_activity_stats();
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('admin/activity', $data);
        $this->load->view('templates/footer');
    }

    private function get_activity_data() {
        $activities = [];
        
        // Get user login history
        $this->db->select('ulh.*, u.full_name, u.role');
        $this->db->from('user_login_history ulh');
        $this->db->join('users u', 'u.id = ulh.user_id');
        $this->db->order_by('ulh.login_time', 'DESC');
        $this->db->limit(100);
        $logins = $this->db->get()->result();
        
        foreach ($logins as $login) {
            $activities[] = [
                'id' => 'login_' . $login->id,
                'type' => 'login',
                'title' => $login->full_name . ' logged in',
                'description' => 'IP: ' . ($login->ip_address ?: 'Unknown'),
                'user_id' => $login->user_id,
                'user_name' => $login->full_name,
                'user_role' => $login->role,
                'timestamp' => $login->login_time,
                'icon' => 'fas fa-sign-in-alt',
                'color' => '#4caf50'
            ];
        }
        
        // Get project activities with extracted_data count
        $this->db->select('p.*, u.full_name, COUNT(ed.id) as model_count');
        $this->db->from('projects p');
        $this->db->join('users u', 'u.id = 1', 'left');
        $this->db->join('project_pdfs pp', 'pp.project_id = p.id', 'left');
        $this->db->join('extracted_data ed', 'ed.pdf_id = pp.id', 'left');
        $this->db->group_by('p.id');
        $this->db->order_by('p.created_at', 'DESC');
        $this->db->limit(50);
        $projects = $this->db->get()->result();
        
        foreach ($projects as $project) {
            $activities[] = [
                'id' => 'project_' . $project->id,
                'type' => 'project',
                'title' => 'Project "' . $project->name . '" created',
                'description' => 'Status: ' . ucfirst($project->status) . ' | Models: ' . $project->model_count,
                'user_id' => 1,
                'user_name' => $project->full_name ?: 'System',
                'user_role' => 'user',
                'timestamp' => $project->created_at,
                'icon' => 'fas fa-folder-plus',
                'color' => '#2196f3'
            ];
        }
        
        // Get extracted_data activities
        $this->db->select('ed.*, p.name as project_name, u.full_name');
        $this->db->from('extracted_data ed');
        $this->db->join('project_pdfs pp', 'pp.id = ed.pdf_id', 'left');
        $this->db->join('projects p', 'p.id = pp.project_id', 'left');
        $this->db->join('users u', 'u.id = 1', 'left');
        $this->db->order_by('ed.created_at', 'DESC');
        $this->db->limit(30);
        $extracted_data = $this->db->get()->result();
        
        foreach ($extracted_data as $data) {
            $activities[] = [
                'id' => 'extraction_' . $data->id,
                'type' => 'extraction',
                'title' => 'Model data extracted from PDF',
                'description' => 'Project: ' . $data->project_name . ' | Model: ' . ($data->model_name ?: 'Unknown'),
                'user_id' => 1,
                'user_name' => $data->full_name ?: 'System',
                'user_role' => 'system',
                'timestamp' => $data->created_at,
                'icon' => 'fas fa-user-plus',
                'color' => '#ff9800'
            ];
        }
        
        // Sort by timestamp
        usort($activities, function($a, $b) {
            return strtotime($b['timestamp']) - strtotime($a['timestamp']);
        });
        
        return array_slice($activities, 0, 50);
    }

    private function get_activity_stats() {
        $stats = [];
        
        // Total logins (last 30 days)
        $thirty_days_ago = date('Y-m-d H:i:s', strtotime('-30 days'));
        $this->db->where('login_time >=', $thirty_days_ago);
        $stats['total_logins'] = $this->db->count_all_results('user_login_history');
        
        // Active users (unique users who logged in last 30 days)
        $this->db->distinct();
        $this->db->select('user_id');
        $this->db->where('login_time >=', $thirty_days_ago);
        $stats['active_users'] = $this->db->count_all_results('user_login_history');
        
        // Project activities
        $this->db->where('created_at >=', $thirty_days_ago);
        $stats['project_activities'] = $this->db->count_all_results('projects');
        
        // Model extraction activities
        $this->db->where('created_at >=', $thirty_days_ago);
        $stats['extraction_activities'] = $this->db->count_all_results('extracted_data');
        
        return $stats;
    }

    public function get_activity_data_ajax() {
        $filter_type = $this->input->get('type');
        $filter_user = $this->input->get('user');
        $filter_date = $this->input->get('date_range');
        
        $activities = $this->get_activity_data();
        
        // Apply filters
        if ($filter_type !== 'all') {
            $activities = array_filter($activities, function($activity) use ($filter_type) {
                return $activity['type'] === $filter_type;
            });
        }
        
        if ($filter_user !== 'all') {
            $activities = array_filter($activities, function($activity) use ($filter_user) {
                return $activity['user_id'] == $filter_user;
            });
        }
        
        if ($filter_date !== 'all') {
            $date_limit = $this->get_date_limit($filter_date);
            $activities = array_filter($activities, function($activity) use ($date_limit) {
                return strtotime($activity['timestamp']) >= $date_limit;
            });
        }
        
        header('Content-Type: application/json');
        echo json_encode([
            'success' => true,
            'activities' => array_values($activities),
            'stats' => $this->get_activity_stats()
        ]);
    }

    private function get_date_limit($range) {
        switch ($range) {
            case 'today':
                return strtotime('today');
            case 'yesterday':
                return strtotime('yesterday');
            case 'week':
                return strtotime('-7 days');
            case 'month':
                return strtotime('-30 days');
            default:
                return 0;
        }
    }

    // ==================== SUPPORT METHODS ====================

    public function support() {
        $data['page_title'] = 'Support';
        $data['user'] = $this->current_user;
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('admin/support', $data);
        $this->load->view('templates/footer');
    }

    public function create_support_ticket() {
        $this->load->library('email');
        
        $subject = $this->input->post('subject');
        $issue_type = $this->input->post('issue_type');
        $priority = $this->input->post('priority');
        $description = $this->input->post('description');
        
        // Create ticket data
        $ticket_data = [
            'user_id' => $this->current_user->id,
            'ticket_number' => 'TKT' . time() . rand(100, 999),
            'subject' => $subject,
            'issue_type' => $issue_type,
            'priority' => $priority,
            'description' => $description,
            'status' => 'open',
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        // Send WhatsApp notification
        $this->send_whatsapp_notification($ticket_data);
        
        // Send email notification
        $this->send_email_notification($ticket_data);
        
        echo json_encode([
            'success' => true,
            'message' => 'Support ticket created successfully!',
            'ticket_number' => $ticket_data['ticket_number']
        ]);
    }

    private function send_whatsapp_notification($ticket_data) {
        $apiKey = "WZrFsbEao5l73Zs0V8hICNYxGzArOzk7";
        $sender = "918595711021";
        $recipient = "918076585915";
        
        $message = "🚨 NEW SUPPORT TICKET\n\n";
        $message .= "Ticket: {$ticket_data['ticket_number']}\n";
        $message .= "Subject: {$ticket_data['subject']}\n";
        $message .= "Type: " . ucfirst($ticket_data['issue_type']) . "\n";
        $message .= "Priority: " . ucfirst($ticket_data['priority']) . "\n";
        $message .= "From: {$this->current_user->full_name}\n\n";
        $message .= "Please check the admin panel for details.";
        
        $body = [
            'api_key' => $apiKey,
            'sender' => $sender,
            'number' => $recipient,
            'message' => $message,
            'footer' => 'GO Productions Support',
            'full' => 1
        ];
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => 'https://wa.bulkmessenger.shop/send-message',
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => json_encode($body),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json']
        ]);
        
        $response = curl_exec($ch);
        curl_close($ch);
    }

    private function send_email_notification($ticket_data) {
        $this->email->from('noreply@goproductions.com', 'GO Productions');
        $this->email->to('support@goproductions.com');
        $this->email->subject("New Support Ticket: {$ticket_data['ticket_number']}");
        
        $email_body = "
            <h2>New Support Ticket Created</h2>
            <p><strong>Ticket Number:</strong> {$ticket_data['ticket_number']}</p>
            <p><strong>Subject:</strong> {$ticket_data['subject']}</p>
            <p><strong>Issue Type:</strong> " . ucfirst($ticket_data['issue_type']) . "</p>
            <p><strong>Priority:</strong> " . ucfirst($ticket_data['priority']) . "</p>
            <p><strong>Submitted By:</strong> {$this->current_user->full_name} ({$this->current_user->email})</p>
            <p><strong>Description:</strong></p>
            <div style='background: #f8f9fa; padding: 15px; border-radius: 5px;'>
                " . nl2br(htmlspecialchars($ticket_data['description'])) . "
            </div>
        ";
        
        $this->email->message($email_body);
        $this->email->send();
    }

    public function get_support_stats() {
        $stats = [
            'open_tickets' => 3,
            'resolved_tickets' => 15,
            'avg_response_time' => '2.5 hours'
        ];
        
        echo json_encode(['success' => true, 'stats' => $stats]);
    }

    public function get_support_tickets() {
        $tickets = [
            [
                'ticket_number' => 'TKT123456',
                'subject' => 'PDF processing error',
                'issue_type' => 'technical',
                'priority' => 'high',
                'status' => 'open',
                'created_at' => date('Y-m-d H:i:s', strtotime('-2 days'))
            ],
            [
                'ticket_number' => 'TKT123455',
                'subject' => 'Feature request',
                'issue_type' => 'feature',
                'priority' => 'medium',
                'status' => 'pending',
                'created_at' => date('Y-m-d H:i:s', strtotime('-5 days'))
            ]
        ];
        
        echo json_encode(['success' => true, 'tickets' => $tickets]);
    }

    // ==================== AGENCIES METHODS ====================

    public function agencies() {
        // Initialize agencies table
        $this->load->model('Agency_model');
        $this->Agency_model->create_agencies_table();
        
        $data['page_title'] = 'Agencies';
        $data['user'] = $this->current_user;
        $data['agencies'] = $this->Agency_model->get_all_agencies();
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('admin/agencies', $data);
        $this->load->view('templates/footer');
    }

    public function create_agency() {
        if (!$this->is_admin) {
            echo json_encode(['success' => false, 'message' => 'Only administrators can create agencies']);
            return;
        }

        $this->load->model('Agency_model');
        
        $this->form_validation->set_rules('name', 'Agency Name', 'required|min_length[2]|max_length[255]');
        $this->form_validation->set_rules('contact_email', 'Contact Email', 'valid_email');
        
        if ($this->form_validation->run() === FALSE) {
            echo json_encode([
                'success' => false,
                'errors' => $this->form_validation->error_array()
            ]);
            return;
        }

        $agency_data = [
            'name' => $this->input->post('name'),
            'address' => $this->input->post('address'),
            'contact_email' => $this->input->post('contact_email'),
            'contact_phone' => $this->input->post('contact_phone'),
            'status' => 'active'
        ];

        // Handle logo upload
        if (!empty($_FILES['logo']['name'])) {
            $upload_result = $this->upload_agency_logo();
            if ($upload_result['success']) {
                $agency_data['logo'] = $upload_result['file_path'];
            } else {
                echo json_encode(['success' => false, 'errors' => ['logo' => $upload_result['error']]]);
                return;
            }
        }

        $agency_id = $this->Agency_model->create_agency($agency_data);
        
        if ($agency_id) {
            echo json_encode([
                'success' => true,
                'message' => 'Agency created successfully!',
                'agency_id' => $agency_id
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'errors' => ['general' => 'Failed to create agency. Please try again.']
            ]);
        }
    }

    public function update_agency($agency_id) {
        if (!$this->is_admin) {
            echo json_encode(['success' => false, 'message' => 'Only administrators can update agencies']);
            return;
        }

        $this->load->model('Agency_model');
        
        $this->form_validation->set_rules('name', 'Agency Name', 'required|min_length[2]|max_length[255]');
        $this->form_validation->set_rules('contact_email', 'Contact Email', 'valid_email');
        
        if ($this->form_validation->run() === FALSE) {
            echo json_encode([
                'success' => false,
                'errors' => $this->form_validation->error_array()
            ]);
            return;
        }

        $agency_data = [
            'name' => $this->input->post('name'),
            'address' => $this->input->post('address'),
            'contact_email' => $this->input->post('contact_email'),
            'contact_phone' => $this->input->post('contact_phone'),
            'status' => $this->input->post('status')
        ];

        // Handle logo upload
        if (!empty($_FILES['logo']['name'])) {
            $upload_result = $this->upload_agency_logo();
            if ($upload_result['success']) {
                $agency_data['logo'] = $upload_result['file_path'];
                
                // Delete old logo
                $old_agency = $this->Agency_model->get_agency($agency_id);
                if ($old_agency->logo && file_exists($old_agency->logo)) {
                    unlink($old_agency->logo);
                }
            } else {
                echo json_encode(['success' => false, 'errors' => ['logo' => $upload_result['error']]]);
                return;
            }
        }

        $result = $this->Agency_model->update_agency($agency_id, $agency_data);
        
        if ($result) {
            echo json_encode([
                'success' => true,
                'message' => 'Agency updated successfully!'
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'errors' => ['general' => 'Failed to update agency. Please try again.']
            ]);
        }
    }

    public function delete_agency($agency_id) {
        if (!$this->is_admin) {
            echo json_encode(['success' => false, 'message' => 'Only administrators can delete agencies']);
            return;
        }

        $this->load->model('Agency_model');
        
        // Delete logo file
        $agency = $this->Agency_model->get_agency($agency_id);
        if ($agency->logo && file_exists($agency->logo)) {
            unlink($agency->logo);
        }
        
        $result = $this->Agency_model->delete_agency($agency_id);
        
        if ($result) {
            echo json_encode(['success' => true, 'message' => 'Agency deleted successfully!']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to delete agency. Please try again.']);
        }
    }

    private function upload_agency_logo() {
        $config = [
            'upload_path' => './assets/uploads/agencies/',
            'allowed_types' => 'jpg|jpeg|png|gif',
            'max_size' => 2048,
            'encrypt_name' => true
        ];
        
        if (!is_dir($config['upload_path'])) {
            mkdir($config['upload_path'], 0755, true);
        }
        
        $this->load->library('upload', $config);
        
        if (!$this->upload->do_upload('logo')) {
            return ['success' => false, 'error' => $this->upload->display_errors()];
        } else {
            $upload_data = $this->upload->data();
            return ['success' => true, 'file_path' => 'assets/uploads/agencies/' . $upload_data['file_name']];
        }
    }

    public function get_agency_details($agency_id) {
        $this->load->model('Agency_model');
        $agency = $this->Agency_model->get_agency($agency_id);
        
        if ($agency) {
            echo json_encode(['success' => true, 'agency' => $agency]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Agency not found']);
        }
    }

    private function get_agency_stats() {
        if (!$this->db->table_exists('agencies')) {
            return [
                'total_agencies' => 0,
                'agencies' => []
            ];
        }
        
        $this->db->where('status', 'active');
        $total_agencies = $this->db->count_all_results('agencies');
        
        $this->db->select('*');
        $this->db->limit(5);
        $agencies = $this->db->get('agencies')->result();
        
        return [
            'total_agencies' => $total_agencies,
            'agencies' => $agencies
        ];
    }

    // ==================== SERVER METHODS ====================

    public function server() {
        $data['page_title'] = 'Server Config';
        $data['user'] = $this->current_user;
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('admin/server_config', $data);
        $this->load->view('templates/footer');
    }

    public function get_processing_status() {
        $this->db->where('processing_status', 'processing');
        $processing_count = $this->db->count_all_results('project_pdfs');
        
        echo json_encode([
            'success' => true,
            'processing_count' => $processing_count
        ]);
    }

    public function get_system_metrics() {
        $metrics = [
            'cpu_usage' => rand(5, 80),
            'memory_usage' => rand(20, 90),
            'disk_usage' => rand(10, 95)
        ];
        
        echo json_encode([
            'success' => true,
            'metrics' => $metrics
        ]);
    }

    public function get_storage_info() {
        $storage = [
            'projects_bytes' => 0,
            'uploads_bytes' => 0,
            'logs_bytes' => 0,
            'backups_bytes' => 0
        ];
        
        // Calculate projects storage
        $projects_path = FCPATH . 'projects/';
        if (is_dir($projects_path)) {
            $storage['projects_bytes'] = $this->calculate_directory_size($projects_path);
        }
        
        // Calculate uploads storage
        $uploads_path = FCPATH . 'uploads/';
        if (is_dir($uploads_path)) {
            $storage['uploads_bytes'] = $this->calculate_directory_size($uploads_path);
        }
        
        // Calculate logs storage
        $logs_path = APPPATH . 'logs/';
        if (is_dir($logs_path)) {
            $storage['logs_bytes'] = $this->calculate_directory_size($logs_path);
        }
        
        // Calculate backups storage (if exists)
        $backups_path = FCPATH . 'backups/';
        if (is_dir($backups_path)) {
            $storage['backups_bytes'] = $this->calculate_directory_size($backups_path);
        }
        
        $storage['total_bytes'] = array_sum($storage);
        
        // Format for display
        $storage['total_display'] = $this->format_bytes($storage['total_bytes']);
        $storage['used_display'] = $this->format_bytes($storage['total_bytes']);
        $storage['projects_display'] = $this->format_bytes($storage['projects_bytes']);
        $storage['uploads_display'] = $this->format_bytes($storage['uploads_bytes']);
        $storage['logs_display'] = $this->format_bytes($storage['logs_bytes']);
        $storage['backups_display'] = $this->format_bytes($storage['backups_bytes']);
        
        echo json_encode([
            'success' => true,
            'storage' => $storage
        ]);
    }

    public function clear_cache() {
        $cache_path = APPPATH . 'cache/';
        if (is_dir($cache_path)) {
            $this->delete_files($cache_path, false, true);
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Cache cleared successfully'
        ]);
    }

    public function optimize_database() {
        $tables = $this->db->list_tables();
        
        foreach ($tables as $table) {
            $this->db->query("OPTIMIZE TABLE `$table`");
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Database optimized successfully'
        ]);
    }

    public function check_database() {
        try {
            $this->db->query('SELECT 1');
            echo json_encode(['success' => true, 'message' => 'Database connected']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Database connection failed']);
        }
    }

    public function get_system_logs() {
        $logs = [];
        
        // Read CodeIgniter logs
        $log_path = APPPATH . 'logs/';
        if (is_dir($log_path)) {
            $log_files = scandir($log_path);
            
            foreach ($log_files as $file) {
                if (pathinfo($file, PATHINFO_EXTENSION) === 'php') {
                    $file_path = $log_path . $file;
                    $file_logs = $this->parse_log_file($file_path);
                    $logs = array_merge($logs, $file_logs);
                }
            }
        }
        
        // Sort by timestamp
        usort($logs, function($a, $b) {
            return strtotime($b['timestamp']) - strtotime($a['timestamp']);
        });
        
        // Return last 100 logs
        $logs = array_slice($logs, 0, 100);
        
        echo json_encode([
            'success' => true,
            'logs' => $logs
        ]);
    }

    // ==================== PDF STORAGE MANAGEMENT ====================

    public function get_pdf_storage_info() {
        try {
            $pdf_storage = $this->calculate_pdf_storage();
            
            echo json_encode([
                'success' => true,
                'storage' => $pdf_storage
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    }

    private function calculate_pdf_storage() {
        $storage = [
            'total_bytes' => 0,
            'total_files' => 0,
            'projects' => []
        ];
        
        $projects_path = FCPATH . 'projects/';
        
        if (is_dir($projects_path)) {
            $project_folders = new DirectoryIterator($projects_path);
            
            foreach ($project_folders as $project_folder) {
                if ($project_folder->isDir() && !$project_folder->isDot()) {
                    $project_id = $project_folder->getFilename();
                    $pdfs_path = $project_folder->getPathname() . '/pdfs';
                    
                    if (is_dir($pdfs_path)) {
                        $project_storage = [
                            'project_id' => $project_id,
                            'project_name' => $this->get_project_name($project_id),
                            'total_bytes' => 0,
                            'file_count' => 0,
                            'files' => []
                        ];
                        
                        $pdf_files = new DirectoryIterator($pdfs_path);
                        
                        foreach ($pdf_files as $pdf_file) {
                            if ($pdf_file->isFile() && $pdf_file->getExtension() === 'pdf') {
                                $file_size = $pdf_file->getSize();
                                $project_storage['total_bytes'] += $file_size;
                                $project_storage['file_count']++;
                                $project_storage['files'][] = [
                                    'name' => $pdf_file->getFilename(),
                                    'size' => $file_size,
                                    'path' => $pdf_file->getPathname()
                                ];
                            }
                        }
                        
                        if ($project_storage['file_count'] > 0) {
                            $storage['total_bytes'] += $project_storage['total_bytes'];
                            $storage['total_files'] += $project_storage['file_count'];
                            $storage['projects'][] = $project_storage;
                        }
                    }
                }
            }
        }
        
        // Format for display
        $storage['total_display'] = $this->format_bytes($storage['total_bytes']);
        $storage['total_files_display'] = number_format($storage['total_files']);
        
        return $storage;
    }

    public function cleanup_pdf_files() {
        try {
            $project_id = $this->input->post('project_id');
            $file_names = $this->input->post('file_names');
            
            $results = [
                'deleted_files' => 0,
                'freed_space' => 0,
                'errors' => []
            ];
            
            if ($project_id === 'all') {
                // Clean all PDF files across all projects
                $projects_path = FCPATH . 'projects/';
                
                if (is_dir($projects_path)) {
                    $project_folders = new DirectoryIterator($projects_path);
                    
                    foreach ($project_folders as $project_folder) {
                        if ($project_folder->isDir() && !$project_folder->isDot()) {
                            $pdfs_path = $project_folder->getPathname() . '/pdfs';
                            
                            if (is_dir($pdfs_path)) {
                                $pdf_files = new DirectoryIterator($pdfs_path);
                                
                                foreach ($pdf_files as $pdf_file) {
                                    if ($pdf_file->isFile() && $pdf_file->getExtension() === 'pdf') {
                                        $file_size = $pdf_file->getSize();
                                        if (unlink($pdf_file->getPathname())) {
                                            $results['deleted_files']++;
                                            $results['freed_space'] += $file_size;
                                        } else {
                                            $results['errors'][] = "Failed to delete: " . $pdf_file->getFilename();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } elseif ($project_id && empty($file_names)) {
                // Clean all PDF files for a specific project
                $pdfs_path = FCPATH . "projects/{$project_id}/pdfs";
                
                if (is_dir($pdfs_path)) {
                    $pdf_files = new DirectoryIterator($pdfs_path);
                    
                    foreach ($pdf_files as $pdf_file) {
                        if ($pdf_file->isFile() && $pdf_file->getExtension() === 'pdf') {
                            $file_size = $pdf_file->getSize();
                            if (unlink($pdf_file->getPathname())) {
                                $results['deleted_files']++;
                                $results['freed_space'] += $file_size;
                            } else {
                                $results['errors'][] = "Failed to delete: " . $pdf_file->getFilename();
                            }
                        }
                    }
                }
            } elseif ($project_id && !empty($file_names)) {
                // Clean specific files
                foreach ($file_names as $file_name) {
                    $file_path = FCPATH . "projects/{$project_id}/pdfs/{$file_name}";
                    
                    if (file_exists($file_path) && unlink($file_path)) {
                        $results['deleted_files']++;
                        $results['freed_space'] += filesize($file_path);
                    } else {
                        $results['errors'][] = "Failed to delete: {$file_name}";
                    }
                }
            }
            
            $results['freed_space_display'] = $this->format_bytes($results['freed_space']);
            
            if ($results['deleted_files'] > 0) {
                echo json_encode([
                    'success' => true,
                    'message' => "Successfully deleted {$results['deleted_files']} PDF files, freed {$results['freed_space_display']}",
                    'results' => $results
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'No PDF files were deleted',
                    'results' => $results
                ]);
            }
            
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'message' => $e->getMessage()
            ]);
        }
    }

    public function cleanup_temp_files() {
        try {
            $temp_dir = './uploads/temp/';
            $projects_dir = './projects/';
            
            $results = array(
                'temp_files' => 0,
                'temp_size' => 0,
                'project_temp_files' => 0,
                'project_temp_size' => 0
            );
            
            // Clean uploads/temp directory
            if (is_dir($temp_dir)) {
                $temp_files = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($temp_dir, RecursiveDirectoryIterator::SKIP_DOTS),
                    RecursiveIteratorIterator::CHILD_FIRST
                );
                
                foreach ($temp_files as $file) {
                    if ($file->isFile()) {
                        $results['temp_size'] += $file->getSize();
                        if (unlink($file->getRealPath())) {
                            $results['temp_files']++;
                        }
                    }
                }
                
                // Remove empty directories
                $dirs = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($temp_dir, RecursiveDirectoryIterator::SKIP_DOTS),
                    RecursiveIteratorIterator::CHILD_FIRST
                );
                
                foreach ($dirs as $dir) {
                    if ($dir->isDir()) {
                        @rmdir($dir->getRealPath());
                    }
                }
            }
            
            // Clean temporary files from projects directory (processing files)
            if (is_dir($projects_dir)) {
                $project_dirs = new DirectoryIterator($projects_dir);
                
                foreach ($project_dirs as $project_dir) {
                    if ($project_dir->isDir() && !$project_dir->isDot()) {
                        $pdfs_dir = $project_dir->getPathname() . '/pdfs';
                        
                        if (is_dir($pdfs_dir)) {
                            $pdf_files = new DirectoryIterator($pdfs_dir);
                            
                            foreach ($pdf_files as $pdf_file) {
                                if ($pdf_file->isFile() && strpos($pdf_file->getFilename(), 'temp_') === 0) {
                                    $results['project_temp_size'] += $pdf_file->getSize();
                                    if (unlink($pdf_file->getRealPath())) {
                                        $results['project_temp_files']++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            
            $total_files = $results['temp_files'] + $results['project_temp_files'];
            $total_size = $results['temp_size'] + $results['project_temp_size'];
            
            if ($total_files > 0) {
                $message = "Cleaned up {$total_files} temporary files (" . round($total_size / 1024 / 1024, 2) . " MB)";
                echo json_encode(array('success' => true, 'message' => $message, 'details' => $results));
            } else {
                echo json_encode(array('success' => true, 'message' => 'No temporary files found to clean', 'details' => $results));
            }
            
        } catch (Exception $e) {
            echo json_encode(array('success' => false, 'message' => $e->getMessage()));
        }
    }

    // ==================== HELPER METHODS ====================

   

   

    private function format_bytes($bytes, $precision = 2) {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= pow(1024, $pow);
        return round($bytes, $precision) . ' ' . $units[$pow];
    }

    private function get_project_name($project_id) {
        $project = $this->db->get_where('projects', ['id' => $project_id])->row();
        return $project ? $project->name : "Project {$project_id}";
    }

    private function delete_files($path, $del_dir = false, $htdocs = false) {
        $path = rtrim($path, '/\\');
        if (!is_dir($path)) {
            return false;
        }
        
        $items = scandir($path);
        if ($items === false) {
            return false;
        }
        
        foreach ($items as $item) {
            if ($item === '.' || $item === '..') {
                continue;
            }
            
            $item_path = $path . DIRECTORY_SEPARATOR . $item;
            
            if (is_dir($item_path)) {
                $this->delete_files($item_path, $del_dir, $htdocs);
            } elseif (!$htdocs || !preg_match('/^(\.htaccess|index\.html?)$/i', $item)) {
                unlink($item_path);
            }
        }
        
        if ($del_dir) {
            rmdir($path);
        }
        
        return true;
    }

    private function parse_log_file($file_path) {
        $logs = [];
        
        if (!file_exists($file_path)) {
            return $logs;
        }
        
        $content = file_get_contents($file_path);
        $lines = explode("\n", $content);
        
        foreach ($lines as $line) {
            if (empty(trim($line))) continue;
            
            // Parse CI log format: "ERROR - 2024-01-01 12:00:00 --> Message"
            if (preg_match('/^(\w+)\s*-\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s*-->\s*(.+)$/', $line, $matches)) {
                $logs[] = [
                    'level' => strtolower($matches[1]),
                    'timestamp' => $matches[2],
                    'message' => $matches[3]
                ];
            }
        }
        
        return $logs;
    }

    // Helper function to format date in IST
    private function format_ist_date($datetime) {
        if (!$datetime) return 'Never';
        
        $date = new DateTime($datetime, new DateTimeZone('UTC'));
        $date->setTimezone(new DateTimeZone('Asia/Kolkata'));
        return $date->format('M j, Y g:i A');
    }

    public function get_user_details($user_id) {
        $user = $this->User_model->get_user_by_id($user_id);
        $login_history = $this->User_model->get_login_history($user_id, 5);
        
        if ($user) {
            $response = array(
                'success' => true,
                'user' => $user,
                'login_history' => $login_history
            );
        } else {
            $response = array(
                'success' => false,
                'message' => 'User not found'
            );
        }

        header('Content-Type: application/json');
        echo json_encode($response);
    }

    public function get_user_edit_data($user_id) {
        // Check if user is admin or accessing their own data
        if (!$this->is_admin && $user_id != $this->current_user->id) {
            $response = array(
                'success' => false,
                'message' => 'You can only access your own profile data.'
            );
            header('Content-Type: application/json');
            echo json_encode($response);
            return;
        }

        $user = $this->User_model->get_user_by_id($user_id);
        
        if ($user) {
            $response = array(
                'success' => true,
                'user' => $user
            );
        } else {
            $response = array(
                'success' => false,
                'message' => 'User not found'
            );
        }

        header('Content-Type: application/json');
        echo json_encode($response);
    }
}