<?php

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

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

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

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

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

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

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

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

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

            return true;
        }

        return false;
    }

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

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

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

        $this->db->where('id', $prefixid);
        $this->db->update('prefixes', $data);

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

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

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

        return $updated;
    }

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

            return true;
        }

        return false;
    }
}