<?php

use app\libraries\Userstamp;

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

class Referral_scheme_model extends MY_Model
{
    public $database;
    public $short = "rscheme";
    public $table;
    public $tbl;

    public function __construct()
    {
        parent::__construct();
        $this->database = $this->getTenantNo();
        $this->table_prefix = '';
        $this->tbl = 'referral_scheme';
        $this->table = $this->tbl . ' ' . $this->short;

        $this->db = $this->load->database($this->database, true);
    }

    public function listing()
    {
        return $this->db
            ->from($this->table_prefix . $this->tbl)
            ->order_by('sort_order', 'ASC')
            ->get()
            ->result_array();
    }

    public function detail($id)
    {
        return $this->db->get_where($this->table_prefix . $this->tbl, array('id' => $id))->row_array();
    }

    public function save($params, $mode, $id = 0)
    {
        if ($mode === 'c') {
            $this->db->insert($this->table_prefix . $this->tbl, Userstamp::create($params));
        } else {
            $this->db->update($this->table_prefix . $this->tbl, Userstamp::update($params), array('id' => $id));
        }
        return $this->db->insert_id();
    }

    public function delete($id)
    {
        return $this->db->delete($this->table_prefix . $this->tbl, array('id' => $id));
    }

    public function update_sort_order($params)
    {
        $this->db->update_batch($this->table_prefix . $this->tbl, $params, 'id');
    }

    public function get_referral_scheme($join_quantity, $join_quantity_unit)
    {
        $this->db = $this->load->database($this->database, true);
        return $this->db->from($this->table_prefix . $this->tbl)
            ->where('join_quantity', $join_quantity)
            ->where('join_quantity_unit', $join_quantity_unit)
            ->order_by('created_at', 'desc')
            ->get()
            ->row_array();
    }

    public function get_referral_schemes()
    {
        $now = date('Y-m-d H:i:s');
        $res = $this->db
            ->from($this->table_prefix . $this->tbl)
            ->where('valid_from <=  ', $now)
            ->group_start()
            ->where('valid_to', null)
            ->or_where('valid_to >=', $now)
            ->group_end()
            ->select('*, CONCAT(join_quantity, " ", join_quantity_unit) AS join_period', false)
            ->get()
            ->result_array();

        log_message('debug', $this->db->last_query());
        return $res;
    }
}
