<?php

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

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

    /**
     * Get age by id
     * @param  mixed $id age 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() . 'ages')->row();
        }
        $this->db->order_by('id', 'ASC');

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

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


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

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

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

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

            return true;
        }

        return false;
    }

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

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

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

        $this->db->where('id', $ageid);
        $this->db->update('ages', $data);

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

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

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

        return $updated;
    }

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

            return true;
        }

        return false;
    }
}