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

class Household_model extends CI_Model {

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

    // ===================== HOUSEHOLD CRUD =====================

    public function create_household($data) {
        $this->db->insert('households', $data['household']);
        $household_id = $this->db->insert_id();
        if (!$household_id) return false;

        if (!empty($data['members'])) {
            $this->_save_members($household_id, $data['members']);
        }
        if (!empty($data['agriculture'])) {
            $data['agriculture']['household_id'] = $household_id;
            $this->db->insert('household_agriculture', $data['agriculture']);
        }
        if (!empty($data['social_services'])) {
            $data['social_services']['household_id'] = $household_id;
            $this->db->insert('household_social_services', $data['social_services']);
        }

        return $household_id;
    }

    public function update_household($id, $data) {
        if (!empty($data['household'])) {
            $this->db->where('id', $id)->update('households', $data['household']);
        }
        if (isset($data['members'])) {
            $this->db->where('household_id', $id)->delete('household_members');
            if (!empty($data['members'])) {
                $this->_save_members($id, $data['members']);
            }
        }
        if (!empty($data['agriculture'])) {
            $existing = $this->db->get_where('household_agriculture', ['household_id' => $id])->row();
            if ($existing) {
                $this->db->where('household_id', $id)->update('household_agriculture', $data['agriculture']);
            } else {
                $data['agriculture']['household_id'] = $id;
                $this->db->insert('household_agriculture', $data['agriculture']);
            }
        }
        if (!empty($data['social_services'])) {
            $existing = $this->db->get_where('household_social_services', ['household_id' => $id])->row();
            if ($existing) {
                $this->db->where('household_id', $id)->update('household_social_services', $data['social_services']);
            } else {
                $data['social_services']['household_id'] = $id;
                $this->db->insert('household_social_services', $data['social_services']);
            }
        }

        return $this->db->affected_rows() >= 0;
    }

    public function get_all_households($filters = []) {
        $this->db->select('h.*, c.name as cell_name, w.name as ward_name, d.name as division_name');
        $this->db->from('households h');
        $this->db->join('cells c', 'c.id = h.cell_id', 'left');
        $this->db->join('wards w', 'w.id = c.ward_id', 'left');
        $this->db->join('divisions d', 'd.id = w.division_id', 'left');

        if (!empty($filters['cell_id']))      $this->db->where('h.cell_id', $filters['cell_id']);
        if (!empty($filters['ward_id']))      $this->db->where('w.id', $filters['ward_id']);
        if (!empty($filters['division_id'])) $this->db->where('d.id', $filters['division_id']);

        $page     = isset($filters['page']) ? (int)$filters['page'] : 1;
        $per_page = isset($filters['per_page']) ? (int)$filters['per_page'] : 20;
        $offset   = ($page - 1) * $per_page;

        $this->db->limit($per_page, $offset);
        $this->db->order_by('h.created_at', 'DESC');

        return $this->db->get()->result_array();
    }

    public function get_household_by_id($id) {
        $this->db->select('h.*, c.name as cell_name, w.name as ward_name, d.name as division_name');
        $this->db->from('households h');
        $this->db->join('cells c', 'c.id = h.cell_id', 'left');
        $this->db->join('wards w', 'w.id = c.ward_id', 'left');
        $this->db->join('divisions d', 'd.id = w.division_id', 'left');
        $this->db->where('h.id', $id);
        $household = $this->db->get()->row_array();

        if (!$household) return null;

        $household['members'] = $this->db
            ->order_by('member_number', 'ASC')
            ->get_where('household_members', ['household_id' => $id])
            ->result_array();

        $household['agriculture'] = $this->db
            ->get_where('household_agriculture', ['household_id' => $id])
            ->row_array();

        $household['social_services'] = $this->db
            ->get_where('household_social_services', ['household_id' => $id])
            ->row_array();

        return $household;
    }

    public function delete_household($id) {
        $this->db->where('id', $id)->delete('households');
        return $this->db->affected_rows() > 0;
    }

    public function count_households($filters = []) {
        $this->db->from('households h');
        $this->db->join('cells c', 'c.id = h.cell_id', 'left');
        $this->db->join('wards w', 'w.id = c.ward_id', 'left');
        $this->db->join('divisions d', 'd.id = w.division_id', 'left');
        if (!empty($filters['cell_id']))      $this->db->where('h.cell_id', $filters['cell_id']);
        if (!empty($filters['ward_id']))      $this->db->where('w.id', $filters['ward_id']);
        if (!empty($filters['division_id'])) $this->db->where('d.id', $filters['division_id']);
        return $this->db->count_all_results();
    }

    // ===================== PRIVATE HELPERS =====================

    private function _save_members($household_id, $members) {
        foreach ($members as $member) {
            $member['household_id'] = $household_id;
            $this->db->insert('household_members', $member);
        }
    }
}
