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

class Sync_model extends MY_Model
{

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *         http://example.com/index.php/welcome
     *    - or -
     *         http://example.com/index.php/welcome/index
     *    - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */

    public function __construct()
    {
        parent::__construct();
        $this->tb_name = "tbl_synch";
    }

    public function get_data()
    {
        $query = $this->db->select("a.id as id, b.user_name as user_name, Max(a.last_synch) as created_date")
							->from($this->tb_name . " as a")
							->join("tbl_user as b", "a.user_id = b.id", "right")
							->group_by('a.user_id')
							->order_by('created_date', 'desc')
							->get();
        if ($query->num_rows() > 0) {
            return array("success" => true, "data" => $query->result_array());
        } else {
            return array("success" => false, "data" => array());
        }
    }

    public function save(array $data)
    {
        $query = $this->db->from($this->tb_name)
            ->where('user_id', $data["user_id"])
            ->order_by('last_synch', 'desc')
            ->get();
        if ($query->num_rows() > 0) {
            $row = $query->row_array();
            $data["id"] = $row["id"];
            $this->update($data);
        } else {
            $this->insert($data);
        }
    }

    public function get_user_last_synch($user_id)
    {
        $query = $this->db->select("Max(last_synch) as created_date")
							->from($this->tb_name)
							->where('user_id', $user_id)
							->order_by('created_date', 'desc')
							->get();
        if ($query->num_rows() > 0) {
			$row = $query->row_array();
            return $row['created_date'];
        } else {
            return "";
        }
    }

    public function delete_data_between($start, $end)
    {
        $start_time = $start . " 00:00:00";
        $end_time = $end . " 23:59:59";
        $result = $this->db->where("last_synch between '{$start}' and '{$end}'")
							->delete($this->tb_name);
        return $this->db->affected_rows();
    }

}
