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

class Households extends CI_Controller {

    public function __construct() {
        parent::__construct();

        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
        header('Content-Type: application/json');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');

        $this->load->model('Household_model');
    }

    // ===================== PREFLIGHT =====================

    public function preflight() {
        $this->output->set_status_header(200)->set_output('');
    }

    // ===================== LIST =====================

    /**
     * GET /households
     * Query params: page, per_page, cell_id, ward_id, division_id
     */
    public function get_households() {
        $filters = [
            'page'        => $this->input->get('page')        ?: 1,
            'per_page'    => $this->input->get('per_page')    ?: 20,
            'cell_id'     => $this->input->get('cell_id'),
            'ward_id'     => $this->input->get('ward_id'),
            'division_id' => $this->input->get('division_id'),
        ];

        $households = $this->Household_model->get_all_households($filters);
        $total      = $this->Household_model->count_households($filters);

        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode([
                'success' => true,
                'message' => 'HOUSEHOLDS_FETCHED_SUCCESSFULLY',
                'data'    => $households,
                'meta'    => [
                    'total'    => $total,
                    'page'     => (int)$filters['page'],
                    'per_page' => (int)$filters['per_page'],
                ],
            ]));
    }

    // ===================== SINGLE =====================

    /**
     * GET /households/{id}
     */
    public function get_household($id) {
        $household = $this->Household_model->get_household_by_id($id);

        if (!$household) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(404)
                ->set_output(json_encode(['success' => false, 'message' => 'HOUSEHOLD_NOT_FOUND']));
        }

        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode([
                'success' => true,
                'message' => 'HOUSEHOLD_FETCHED_SUCCESSFULLY',
                'data'    => $household,
            ]));
    }

    // ===================== CREATE =====================

    /**
     * POST /households
     */
    public function create_household() {
        $input = json_decode(@file_get_contents('php://input'), true);

        if (empty($input['cell_id']) || empty($input['household_head'])) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400)
                ->set_output(json_encode([
                    'success' => false,
                    'message' => 'CELL_ID_AND_HOUSEHOLD_HEAD_REQUIRED',
                ]));
        }

        $household_fields = [
            // Record header
            'hh_record_date'       => isset($input['hh_record_date'])       ? $input['hh_record_date'] : date('Y-m-d'),
            'main_contact_details' => isset($input['main_contact_details']) ? $input['main_contact_details'] : null,
            'recorded_by'          => isset($input['recorded_by'])          ? $input['recorded_by'] : null,
            // Location
            'cell_id'              => $input['cell_id'],
            // HH head details
            'household_head'       => $input['household_head'],
            'head_gender'          => isset($input['head_gender'])          ? $input['head_gender'] : 'male',
            'household_type'       => isset($input['household_type'])       ? $input['household_type'] : null,
            'marital_status'       => isset($input['marital_status'])       ? $input['marital_status'] : null,
            'nationality'          => isset($input['nationality'])          ? $input['nationality'] : 'Unknown',
            'ethnicity'            => isset($input['ethnicity'])            ? $input['ethnicity'] : null,
            'refugee_status'       => isset($input['refugee_status'])       ? $input['refugee_status'] : 'citizen',
            'documentation_status' => isset($input['documentation_status']) ? $input['documentation_status'] : null,
            'stay_period_uganda'   => isset($input['stay_period_uganda'])   ? $input['stay_period_uganda'] : null,
            'stay_period_kmc'      => isset($input['stay_period_kmc'])      ? $input['stay_period_kmc'] : null,
            // Demographics totals
            'total_members'        => isset($input['total_members'])        ? (int)$input['total_members'] : 0,
            'male_members'         => isset($input['male_members'])         ? (int)$input['male_members'] : 0,
            'female_members'       => isset($input['female_members'])       ? (int)$input['female_members'] : 0,
            'children_under_18'    => isset($input['children_under_18'])    ? (int)$input['children_under_18'] : 0,
            'registration_date'    => date('Y-m-d'),
            'data_entry_user_id'   => isset($input['data_entry_user_id'])   ? $input['data_entry_user_id'] : null,
            // Section B: Assets
            'house_ownership'      => isset($input['house_ownership'])      ? (int)$input['house_ownership'] : 0,
            'house_type'           => isset($input['house_type'])           ? $input['house_type'] : null,
            'comm_radio'           => isset($input['comm_radio'])           ? (int)$input['comm_radio'] : 0,
            'comm_mobile_phone'    => isset($input['comm_mobile_phone'])    ? (int)$input['comm_mobile_phone'] : 0,
            'comm_tv'              => isset($input['comm_tv'])              ? (int)$input['comm_tv'] : 0,
            'transport_bicycle'    => isset($input['transport_bicycle'])    ? (int)$input['transport_bicycle'] : 0,
            'transport_motorcycle' => isset($input['transport_motorcycle']) ? (int)$input['transport_motorcycle'] : 0,
            'transport_vehicle'    => isset($input['transport_vehicle'])    ? (int)$input['transport_vehicle'] : 0,
            'transport_other'      => isset($input['transport_other'])      ? $input['transport_other'] : null,
            // Section C: Energy
            'energy_lighting'      => isset($input['energy_lighting'])      ? $input['energy_lighting'] : null,
            'energy_cooking'       => isset($input['energy_cooking'])       ? $input['energy_cooking'] : null,
            // Section D: Water & Sanitation
            'water_source'         => isset($input['water_source'])         ? $input['water_source'] : null,
            'bathroom_type'        => isset($input['bathroom_type'])        ? $input['bathroom_type'] : null,
            'toilet_facilities'    => isset($input['toilet_facilities'])    ? $input['toilet_facilities'] : null,
            'has_drying_rack'      => isset($input['has_drying_rack'])      ? (int)$input['has_drying_rack'] : 0,
            'has_waste_disposal_area' => isset($input['has_waste_disposal_area']) ? (int)$input['has_waste_disposal_area'] : 0,
            // Section E1: Land
            'total_land_owned'     => isset($input['total_land_owned'])     ? $input['total_land_owned'] : null,
            'land_tenure'          => isset($input['land_tenure'])          ? $input['land_tenure'] : null,
            'land_use_crop'        => isset($input['land_use_crop'])        ? (int)$input['land_use_crop'] : 0,
            'land_use_livestock'   => isset($input['land_use_livestock'])   ? (int)$input['land_use_livestock'] : 0,
            'land_use_agro_forestry' => isset($input['land_use_agro_forestry']) ? (int)$input['land_use_agro_forestry'] : 0,
            'land_use_other'       => isset($input['land_use_other'])       ? $input['land_use_other'] : null,
        ];

        $agriculture    = isset($input['agriculture'])    ? $this->_filter_agriculture($input['agriculture']) : [];
        $social_services = isset($input['social_services']) ? $this->_filter_social_services($input['social_services']) : [];
        $members        = isset($input['members'])        ? $this->_filter_members($input['members']) : [];

        $household_id = $this->Household_model->create_household([
            'household'      => $household_fields,
            'members'        => $members,
            'agriculture'    => $agriculture,
            'social_services' => $social_services,
        ]);

        if (!$household_id) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(500)
                ->set_output(json_encode(['success' => false, 'message' => 'FAILED_TO_CREATE_HOUSEHOLD']));
        }

        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(201)
            ->set_output(json_encode([
                'success'      => true,
                'message'      => 'HOUSEHOLD_CREATED_SUCCESSFULLY',
                'household_id' => $household_id,
            ]));
    }

    // ===================== UPDATE =====================

    /**
     * PUT /households/{id}
     */
    public function update_household($id) {
        $household = $this->Household_model->get_household_by_id($id);
        if (!$household) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(404)
                ->set_output(json_encode(['success' => false, 'message' => 'HOUSEHOLD_NOT_FOUND']));
        }

        $input = json_decode(@file_get_contents('php://input'), true);

        $allowed_household_fields = [
            'hh_record_date','main_contact_details','recorded_by','cell_id',
            'household_head','head_gender','household_type','marital_status',
            'nationality','ethnicity','refugee_status','documentation_status',
            'stay_period_uganda','stay_period_kmc',
            'total_members','male_members','female_members','children_under_18',
            'house_ownership','house_type',
            'comm_radio','comm_mobile_phone','comm_tv',
            'transport_bicycle','transport_motorcycle','transport_vehicle','transport_other',
            'energy_lighting','energy_cooking',
            'water_source','bathroom_type','toilet_facilities','has_drying_rack','has_waste_disposal_area',
            'total_land_owned','land_tenure',
            'land_use_crop','land_use_livestock','land_use_agro_forestry','land_use_other',
        ];

        $update = [];
        foreach ($allowed_household_fields as $field) {
            if (array_key_exists($field, $input)) {
                $update[$field] = $input[$field];
            }
        }

        $data = ['household' => $update];
        if (isset($input['members']))         $data['members']         = $this->_filter_members($input['members']);
        if (isset($input['agriculture']))     $data['agriculture']     = $this->_filter_agriculture($input['agriculture']);
        if (isset($input['social_services'])) $data['social_services'] = $this->_filter_social_services($input['social_services']);

        if ($this->Household_model->update_household($id, $data)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(['success' => true, 'message' => 'HOUSEHOLD_UPDATED_SUCCESSFULLY']));
        }

        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode(['success' => false, 'message' => 'FAILED_TO_UPDATE_HOUSEHOLD']));
    }

    // ===================== DELETE =====================

    /**
     * DELETE /households/{id}
     */
    public function delete_household($id) {
        $household = $this->Household_model->get_household_by_id($id);
        if (!$household) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(404)
                ->set_output(json_encode(['success' => false, 'message' => 'HOUSEHOLD_NOT_FOUND']));
        }

        if ($this->Household_model->delete_household($id)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(['success' => true, 'message' => 'HOUSEHOLD_DELETED_SUCCESSFULLY']));
        }

        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode(['success' => false, 'message' => 'FAILED_TO_DELETE_HOUSEHOLD']));
    }

    // ===================== PRIVATE FILTERS =====================

    private function _filter_members($members) {
        $allowed = [
            'member_number','full_name','relationship_to_head','sex','date_of_birth',
            'nationality','identification_number','main_economic_activity',
            'father_alive','mother_alive','marital_status',
            'highest_education_level','current_schooling_status',
            'terminal_illnesses','disability_type','disability_cause',
        ];
        $result = [];
        foreach ($members as $member) {
            $row = [];
            foreach ($allowed as $f) {
                $row[$f] = isset($member[$f]) ? $member[$f] : null;
            }
            $result[] = $row;
        }
        return $result;
    }

    private function _filter_agriculture($ag) {
        $allowed = [
            'ext_crop_farming','ext_veterinary','ext_poultry','ext_bee_keeping',
            'ext_land_use','ext_water_for_production','ext_agro_forestry','ext_other',
            'ext_service_source',
            'major_crops','crop_land_area_acres','crop_qty_consumed','crop_qty_sold',
            'outlet_farm_gate','outlet_local_market','outlet_online_sales','outlet_other',
            'main_livestock','livestock_products_sold',
            'hive_local_count','hive_ktb_count','hive_lanstroth_count','apiary_production_capacity',
            'other_economic_activities','economic_key_challenges',
        ];
        $row = [];
        foreach ($allowed as $f) {
            if (array_key_exists($f, $ag)) $row[$f] = $ag[$f];
        }
        return $row;
    }

    private function _filter_social_services($ss) {
        $allowed = [
            'credit_bank_microfinance','credit_sacco_vsla','credit_friends_family',
            'credit_business','credit_employer','credit_other',
            'distance_hc3','distance_hc4','distance_hospital',
            'distance_preprimary','distance_primary','distance_secondary','distance_tertiary_university',
            'proximity_local_govt','proximity_police','proximity_courts',
            'proximity_games_sports','proximity_entertainment',
            'network_youth_groups','network_women_groups','network_pwd_groups',
            'network_religious_activities','network_farmer_groups','network_other',
        ];
        $row = [];
        foreach ($allowed as $f) {
            if (array_key_exists($f, $ss)) $row[$f] = $ss[$f];
        }
        return $row;
    }
}
