<?php

class PBReusableModel_Partners extends CI_Model {

	const PARTNERS = 'auth_partners';
	const ANALYTICS = 'sq_log';
	const MALLERS = 'sq_users_retailers';

    function __construct() {
        parent::__construct();
		$this->load->helper('date');

		$this->PDB1 = $this->load->database('default', TRUE);
		// $this->dbpartners = $this->load->database();
        // $this->load->model('PBReusableModel_Security','appsecurity');
        // $this->load->model('PBReusableModel_Analytics','analytics');
        // $this->load->model('PBReusableModel_Partners','partners');
        // $this->load->model('PBReusableModel_Global','globals');
    }

	public function isTokenValid($token) {
        $this->PDB1->select('*');
        $this->PDB1->from(self::PARTNERS);
        $this->PDB1->where('api_token',$token);
        $query = $this->PDB1->get();
		$this->PDB1->close();
        return $query->result();
	}

	public function getPartners() {
        $this->load->database();
        $this->db->select('*');
        $this->db->from(self::PARTNERS);
        $query = $this->db->get();
        return $query->result();
	}

	function addPartner() {
		$data = $this->input->post();
		$this->load->database();
		$data['access_type'] = 'api_auth';
		$this->db->insert(self::PARTNERS,$data);
		if ($this->db->insert_id()) {
			$partner_data = array();
			$partner_data['partner_id'] = $this->db->insert_id();
			$partner_data['access_type'] = 'api_auth';
			$valid_data['api_token'] = $this->appsecurity->generateToken($partner_data);
			$this->db->trans_complete();
			if ($this->db->trans_status() === TRUE) {
				return true;
			} else {
				return false;
			}
		}
	}

	public function updatePartner($data) {
		$valid_data = array();
		$valid_data['id'] = $data['id'];
		$valid_data['name'] = $data['name'];
		$valid_data['api_token'] = $data['api_token'];
		$valid_data['active'] = $data['active'];
		$this->load->database();
		$this->db->where('id',$data['id']);
		$this->db->update(self::PARTNERS, $valid_data);
		$this->db->trans_complete();
		if ($this->db->trans_status() === TRUE) {
			return true;
		} else {
			return false;
		}
	}

	public function getPartnerByID($id) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::PARTNERS);
		$this->db->where('id',$id);
		$this->db->limit(1);
		$query = $this->db->get();
		$user = $query->row_array();
		return $user;
	}
}
