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

class Administrative 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('Administrative_model');
    }

    // ===================== DIVISIONS =====================
    
    /**
     * Get all divisions
     * GET /administrative/divisions
     */
    public function get_divisions() {
        $divisions = $this->Administrative_model->get_all_divisions();
        
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'DIVISIONS_FETCHED_SUCCESSFULLY',
                'data' => $divisions
            )));
    }

    /**
     * Get division statistics
     * GET /administrative/divisions/statistics
     */
    public function get_division_statistics() {
        $statistics = $this->Administrative_model->get_division_statistics();
        
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'STATISTICS_FETCHED_SUCCESSFULLY',
                'data' => $statistics
            )));
    }

    // ===================== WARDS =====================
    
    /**
     * Get all wards or wards by division
     * GET /administrative/wards?division_id=1
     */
    public function get_wards() {
        $division_id = $this->input->get('division_id');
        
        if ($division_id) {
            $wards = $this->Administrative_model->get_wards_by_division($division_id);
        } else {
            $wards = $this->Administrative_model->get_all_wards();
        }
        
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'WARDS_FETCHED_SUCCESSFULLY',
                'data' => $wards
            )));
    }

    /**
     * Get ward statistics
     * GET /administrative/wards/statistics?division_id=1
     */
    public function get_ward_statistics() {
        $division_id = $this->input->get('division_id');
        $statistics = $this->Administrative_model->get_ward_statistics($division_id);
        
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'STATISTICS_FETCHED_SUCCESSFULLY',
                'data' => $statistics
            )));
    }

    // ===================== CELLS =====================
    
    /**
     * Get all cells or cells by ward/division
     * GET /administrative/cells?ward_id=1&division_id=1
     */
    public function get_cells() {
        $ward_id = $this->input->get('ward_id');
        $division_id = $this->input->get('division_id');
        
        if ($ward_id) {
            $cells = $this->Administrative_model->get_cells_by_ward($ward_id);
        } elseif ($division_id) {
            $cells = $this->Administrative_model->get_cells_by_division($division_id);
        } else {
            $cells = $this->Administrative_model->get_all_cells();
        }
        
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'CELLS_FETCHED_SUCCESSFULLY',
                'data' => $cells
            )));
    }

    /**
     * Get single cell details
     * GET /administrative/cells/{id}
     */
    public function get_cell($cell_id) {
        $cell = $this->Administrative_model->get_cell_by_id($cell_id);
        
        if (!$cell) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(404)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'CELL_NOT_FOUND'
                )));
        }
        
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'CELL_FETCHED_SUCCESSFULLY',
                'data' => $cell
            )));
    }

    /**
     * Create new cell
     * POST /administrative/cells
     */
    public function create_cell() {
        $json_data = json_decode(@file_get_contents('php://input'), true);
        
        // Validate required fields
        if (empty($json_data['ward_id']) || empty($json_data['name'])) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'WARD_ID_AND_NAME_REQUIRED'
                )));
        }
        
        $cell_data = array(
            'ward_id' => $json_data['ward_id'],
            'name' => $json_data['name'],
            'code' => isset($json_data['code']) ? $json_data['code'] : null,
            'population' => isset($json_data['population']) ? $json_data['population'] : 0,
            'households' => isset($json_data['households']) ? $json_data['households'] : 0
        );
        
        if ($this->Administrative_model->create_cell($cell_data)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(201)
                ->set_output(json_encode(array(
                    'success' => true,
                    'message' => 'CELL_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_CELL'
                )));
        }
    }

    /**
     * Update cell
     * PUT /administrative/cells/{id}
     */
    public function update_cell($cell_id) {
        $json_data = json_decode(@file_get_contents('php://input'), true);
        
        // Check if cell exists
        $cell = $this->Administrative_model->get_cell_by_id($cell_id);
        if (!$cell) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(404)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'CELL_NOT_FOUND'
                )));
        }
        
        $update_data = array();
        $allowed_fields = ['name', 'code', 'population', 'households', 'ward_id'];
        
        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->Administrative_model->update_cell($cell_id, $update_data)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'message' => 'CELL_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_CELL'
                )));
        }
    }

    /**
     * Delete cell
     * DELETE /administrative/cells/{id}
     */
    public function delete_cell($cell_id) {
        $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'
                )));
        }
        
        $cell = $this->Administrative_model->get_cell_by_id($cell_id);
        if (!$cell) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(404)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'CELL_NOT_FOUND'
                )));
        }
        
        if ($this->Administrative_model->delete_cell($cell_id)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'message' => 'CELL_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_CELL'
                )));
        }
    }
}
