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

class Users extends CI_Controller {

    public function __construct() {
        parent::__construct();
        
        // CORS headers
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization');
        header('Content-Type: application/json');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
        
        $method = $_SERVER['REQUEST_METHOD'];
        if ($method == "OPTIONS") {
            die();
        }

        $this->load->model('User_model');
        $this->load->helper(['jwt', 'authorization']);
    }

    /**
     * Get all users
     * GET /users
     */
    public function index() {
        try {
            // Verify authorization (admin and above only)
            $token_data = $this->verify_admin_access();
            
            $page = $this->input->get('page') ? (int)$this->input->get('page') : 1;
            $per_page = $this->input->get('per_page') ? (int)$this->input->get('per_page') : 20;
            $offset = ($page - 1) * $per_page;
            
            $users = $this->User_model->get_users($per_page, $offset);
            $total = $this->User_model->count_users();
            
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'message' => 'USERS_FETCHED_SUCCESSFULLY',
                    'data' => $users,
                    'pagination' => array(
                        'total' => $total,
                        'page' => $page,
                        'per_page' => $per_page,
                        'total_pages' => ceil($total / $per_page)
                    )
                )));
        } catch (Exception $e) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(401)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => $e->getMessage()
                )));
        }
    }

    /**
     * Get single user by ID
     * GET /users/{id}
     */
    public function get_user($user_id) {
        try {
            // Verify authorization
            $token_data = $this->verify_admin_access();
            
            $user = $this->User_model->get_user_by_id($user_id);
            
            if (!$user) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(404)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'USER_NOT_FOUND'
                    )));
            }
            
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'message' => 'USER_FETCHED_SUCCESSFULLY',
                    'data' => $user
                )));
        } catch (Exception $e) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(401)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => $e->getMessage()
                )));
        }
    }

    /**
     * Create new user
     * POST /users
     */
    public function create() {
        try {
            // Verify authorization (admin and above only)
            $token_data = $this->verify_admin_access();
            
            $json_data = json_decode(@file_get_contents('php://input'), true);
            
            // Validate required fields
            $required_fields = ['name', 'email', 'password', 'role'];
            foreach ($required_fields as $field) {
                if (empty($json_data[$field])) {
                    return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(400)
                        ->set_output(json_encode(array(
                            'success' => false,
                            'message' => 'MISSING_REQUIRED_FIELD: ' . $field
                        )));
                }
            }
            
            // Validate role
            $valid_roles = ['DATA_ENTRY', 'ADMIN', 'SUPER_ADMIN', 'SUPER_SUPER_ADMIN'];
            if (!in_array($json_data['role'], $valid_roles)) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(400)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'INVALID_ROLE'
                    )));
            }
            
            // Check if email already exists
            $existing_user = $this->User_model->get_user_by_email($json_data['email']);
            if ($existing_user) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(400)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'EMAIL_ALREADY_EXISTS'
                    )));
            }
            
            $user_data = array(
                'name' => $json_data['name'],
                'email' => $json_data['email'],
                'password' => $json_data['password'],
                'role' => $json_data['role'],
                'municipality' => isset($json_data['municipality']) ? $json_data['municipality'] : 'Koboko Municipal Council',
                'division' => isset($json_data['division']) ? $json_data['division'] : null,
                'ward' => isset($json_data['ward']) ? $json_data['ward'] : null,
                'status' => 'active'
            );
            
            if ($this->User_model->create_user($user_data)) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(201)
                    ->set_output(json_encode(array(
                        'success' => true,
                        'message' => 'USER_CREATED_SUCCESSFULLY'
                    )));
            } else {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(500)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'FAILED_TO_CREATE_USER'
                    )));
            }
        } catch (Exception $e) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(401)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => $e->getMessage()
                )));
        }
    }

    /**
     * Update user
     * PUT /users/{id}
     */
    public function update($user_id) {
        try {
            // Verify authorization
            $token_data = $this->verify_admin_access();
            
            $json_data = json_decode(@file_get_contents('php://input'), true);
            
            // Check if user exists
            $user = $this->User_model->get_user_by_id($user_id);
            if (!$user) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(404)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'USER_NOT_FOUND'
                    )));
            }
            
            // Validate role if provided
            if (isset($json_data['role'])) {
                $valid_roles = ['DATA_ENTRY', 'ADMIN', 'SUPER_ADMIN', 'SUPER_SUPER_ADMIN'];
                if (!in_array($json_data['role'], $valid_roles)) {
                    return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(400)
                        ->set_output(json_encode(array(
                            'success' => false,
                            'message' => 'INVALID_ROLE'
                        )));
                }
            }
            
            // Prepare update data
            $update_data = array();
            $allowed_fields = ['name', 'email', 'password', 'role', 'municipality', 'division', 'ward', 'status'];
            
            foreach ($allowed_fields as $field) {
                if (isset($json_data[$field])) {
                    $update_data[$field] = $json_data[$field];
                }
            }
            
            if (empty($update_data)) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(400)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'NO_FIELDS_TO_UPDATE'
                    )));
            }
            
            if ($this->User_model->update_user($user_id, $update_data)) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => true,
                        'message' => 'USER_UPDATED_SUCCESSFULLY'
                    )));
            } else {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(500)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'FAILED_TO_UPDATE_USER'
                    )));
            }
        } catch (Exception $e) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(401)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => $e->getMessage()
                )));
        }
    }

    /**
     * Delete user
     * DELETE /users/{id}
     */
    public function delete($user_id) {
        try {
            // Verify authorization (super admin and above only)
            $token_data = $this->verify_super_admin_access();
            
            $request_method = $this->input->server('REQUEST_METHOD');
            if (strtoupper($request_method) !== 'DELETE') {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(405)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'WRONG_REQUEST_METHOD'
                    )));
            }
            
            $user = $this->User_model->get_user_by_id($user_id);
            if (!$user) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(404)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'USER_NOT_FOUND'
                    )));
            }
            
            if ($this->User_model->delete_user($user_id)) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => true,
                        'message' => 'USER_DELETED_SUCCESSFULLY'
                    )));
            } else {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(500)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'FAILED_TO_DELETE_USER'
                    )));
            }
        } catch (Exception $e) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(401)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => $e->getMessage()
                )));
        }
    }

    /**
     * Helper function to verify admin access
     * 
     * WARNING: This is a placeholder implementation for development.
     * MUST be replaced with proper JWT verification before production deployment.
     * See API_DOCUMENTATION.md security notes for recommendations.
     */
    private function verify_admin_access() {
        // Get authorization token from header
        $headers = $this->input->request_headers();
        
        if (!isset($headers['Authorization'])) {
            throw new Exception('AUTHORIZATION_REQUIRED');
        }
        
        // TODO: Implement proper JWT verification using firebase/php-jwt
        // This currently bypasses authentication - DO NOT USE IN PRODUCTION
        return array('role' => 'ADMIN');
    }

    /**
     * Helper function to verify super admin access
     * 
     * WARNING: This is a placeholder implementation for development.
     * MUST be replaced with proper JWT verification before production deployment.
     */
    private function verify_super_admin_access() {
        // Get authorization token from header
        $headers = $this->input->request_headers();
        
        if (!isset($headers['Authorization'])) {
            throw new Exception('AUTHORIZATION_REQUIRED');
        }
        
        // TODO: Implement proper JWT verification
        // This currently bypasses authentication - DO NOT USE IN PRODUCTION
        return array('role' => 'SUPER_ADMIN');
    }
}
