<?php

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

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

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

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

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


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

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

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

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

            return true;
        }

        return false;
    }

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

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

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

        $this->db->where('id', $isd_codeid);
        $this->db->update('isd_codes', $data);

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

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

        if ($updated) {
            log_activity('ISD Code Updated [ID: ' . $isd_codeid . ', ' . $data['name'] . ']');
        }

        return $updated;
    }

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

            return true;
        }

        return false;
    }
}