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

/**
 * Class End_contracts_model
 */
class Terminations_model extends App_Model
{

  public $table_name = 'hr_end_contracts';

  /**
   * Create new employee
   *
   * @param array $data
   *
   * @return int
   */
  public function add($data)
  {
    if (is_staff_logged_in()) {
      $data['addedfrom'] = get_staff_user_id();
    }

    $data['date']  = date('Y-m-d', strtotime($data['date']));
    $data['date_finish']  = date('Y-m-d', strtotime($data['date_finish']));
    $this->db->insert(db_prefix() . $this->table_name, $data);

    $id  = $this->db->insert_id();
    $log = 'ID: ' . $id;

    $isStaff = null;
    if (!is_client_logged_in() && is_staff_logged_in()) {
      $log     .= ', From Staff: ' . get_staff_user_id();
      $isStaff = get_staff_user_id();
    }

    log_activity('New Termination Created [' . $log . ']', $isStaff);

    return $id;
  }

  /**
   * Update employye informations
   *
   * @param array $_POST data
   * @param integer ID
   *
   * @return boolean
   */
  public function update($data, $id)
  {
    $this->db->where('id', $id);

    $data['date']  = date('Y-m-d', strtotime($data['date']));
    $data['date_finish']  = date('Y-m-d', strtotime($data['date']));

    $this->db->update(db_prefix() . $this->table_name, $data);

    if ($this->db->affected_rows() > 0) {
      log_activity('Termination Info Updated [ID: ' . $id . ']');

      return true;
    }

    return false;
  }

  /**
   * Get employee
   *
   * @param int|null $id
   *
   * @return array
   */
  public function get($id)
  {
    $id = is_numeric($id) ? (int)$id : null;
    if ($id) {
      $this->db->where('id', (int)$id);

      return $this->db->get(db_prefix() . $this->table_name)->row();
    }

    $this->db->order_by('date', 'desc');

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

  /**
   * Delete employee
   *
   * @param int $id
   *
   * @return bool
   */
  public function delete($id)
  {

    $this->db->where('id', (int)$id);
    $this->db->delete(db_prefix() . $this->table_name);

    return $this->db->affected_rows() > 0;
  }
}
