<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Sexes_model extends App_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Get sex by id
     * @param  mixed $id sex id
     * @return mixed     if id passed return object else array
     */
    public function get($id = '')
    {
        if (is_numeric($id)) {
            $this->db->where('id', $id);

            return $this->db->get(db_prefix() . 'sexes')->row();
        }
        $this->db->order_by('id', 'ASC');

        return $this->db->get(db_prefix() . 'sexes')->result_array();
    }

    /**
     * Add new sex
     * @param array $data sex data
     * @return boolean
     */
    public function add($data)
    {
        unset($data['sexid']);
        $data['name']    = trim($data['name']);


        $data = hooks()->apply_filters('before_sex_created', $data);

        $this->db->insert('sexes', $data);
        $insert_id = $this->db->insert_id();

        if ($insert_id) {
            log_activity('New Sex Added [ID: ' . $insert_id . ', ' . $data['name'] . ']');

            hooks()->do_action('after_sex_created', [
                'id'   => $insert_id,
                'data' => $data,
            ]);

            return true;
        }

        return false;
    }

    /**
     * Edit sex
     * @param  array $data sex data
     * @return boolean
     */
    public function edit($data)
    {
        $updated      = false;
        $sexid        = $data['sexid'];
        $original_sex = $this->get($sexid);
        unset($data['sexid']);

        $data['name']    = trim($data['name']);

        $data = hooks()->apply_filters('before_update_sex', $data, $sexid);

        $this->db->where('id', $sexid);
        $this->db->update('sexes', $data);

        if ($this->db->affected_rows() > 0) {
            $updated = true;
        }

        hooks()->do_action('after_update_sex', [
            'id'      => $sexid,
            'data'    => $data,
            'updated' => &$updated,
        ]);

        if ($updated) {
            log_activity('Sex Updated [ID: ' . $sexid . ', ' . $data['name'] . ']');
        }

        return $updated;
    }

    /**
     * Delete sex from database
     * @param  mixed $id sex id
     * @return boolean
     */
    public function delete($id)
    {
        $this->db->where('id', $id);
        $this->db->delete(db_prefix() . 'sexes');
        if ($this->db->affected_rows() > 0) {
            log_activity('Sex Deleted [ID: ' . $id . ']');

            return true;
        }

        return false;
    }
}