<?php
class Group_model extends CI_Model {

	public function getAll() {
        return $this->db->get('document_groups')->result_array();
    }

    public function insert($data) {
        $this->db->insert('document_groups', ['name' => $data['name']]);
        $document_id = $this->db->insert_id();

        if (!empty($data['grouped_docs'])) {
            foreach ($data['grouped_docs'] as $gid) {
                $this->db->insert('document_groups', [
                    'document_id' => $document_id,
                    'grouped_doc_id' => $gid
                ]);
            }
        }

        return $document_id;
    }

    public function update($id, $data) {
        $this->db->where('id', $id)->update('document_groups', ['name' => $data['name']]);

        // remove old links
        $this->db->where('document_id', $id)->delete('document_groups');

        if (!empty($data['grouped_docs'])) {
            foreach ($data['grouped_docs'] as $gid) {
                $this->db->insert('document_groups', [
                    'document_id' => $id,
                    'grouped_doc_id' => $gid
                ]);
            }
        }
    }

    public function getById($id) {
        $doc = $this->db->where('id', $id)->get('document_groups')->row_array();

        $grouped = $this->db->select('grouped_doc_id')
                            ->where('document_id', $id)
                            ->get('document_groups')
                            ->result_array();
        $doc['grouped_docs'] = array_column($grouped, 'grouped_doc_id');
        return $doc;
    }	
}
