<?php

App::uses('Model', 'Model');

/**
 * Application model for Cake.
 *
 * Add your application-wide methods in the class below, your models
 * will inherit them.
 *
 * @package       app.Model
 */

class RedistributorSale extends AppModel {
	public $belongsTo  = array(
				'User' => array('className' => 'User', 'foreignKey' => 'user_id', 'fields' => array('first_name', 'last_name'), 'type'=>'inner'),
				'Customer' => array('className' => 'Customer', 'foreignKey' => 'customer_id', 'fields' => array('id', 'first_name','last_name'), 'type'=>'inner'),
				'Redistributor' => array('className' => 'Redistributor', 'foreignKey' => 'redistributor_id', 'fields' => array('id', 'first_name','last_name'), 'type'=>'inner'),
			);
	
	public $hasMany = array(
		'RedistributorSaleitem' => array(
            'className' => 'RedistributorSaleitem',
            'foreignKey' => 'redistributor_sale_id',
			'dependent' => true
        ),
        /* 'RdFreeItem' => array(
            'className' => 'RdFreeItem',
            'foreignKey' => 'redistributor_sale_id',
			'dependent' => true
        ), */      
        
    );
	
	
	function _userSalesCondition(&$conditions, $user){
		
		switch($user['Role']['grade']){
			case 2:
                if($user['role_id'] == DIVISIONMANAGER) {
                    $conditions[] = 'RedistributorSale.user_id IN (SELECT id FROM users WHERE division_id = ' . $user['division_id'] . ')';
                }
                break;
			case 3:
				$conditions[] = 'RedistributorSale.user_id IN (SELECT id FROM users WHERE region_id = '. $user['region_id'].')';
			break;
			case 4:
				$conditions[] = 'RedistributorSale.user_id IN (SELECT id FROM users WHERE depot_id = '. $user['depot_id'].')';
			break;
			case 5:
				$conditions['OR'] = array( 'RedistributorSale.user_id' => $user['id'], '`RedistributorSale`.`user_id` IN (SELECT uid2 FROM user_relations WHERE user_id = '. $user['id'].')'); 
			break;
			case 6:
				
				$conditions[] = '(RedistributorSale.user_id = '.$user['id'].')';
				
			break;
			
		}
	
	}
	
	function _userSalesItemsCondition(&$conditions, $user){
		
		switch($user['Role']['grade']){
			case 3:
				$conditions[] = 'RedistributorSaleitem.user_id IN (SELECT id FROM users WHERE region_id = '. $user['region_id'].')';
			break;
			case 4:
			case 5:				
			case 6:
				$conditions['OR']['RedistributorSaleitem.user_id'] = $user['id']; 
				$conditions['OR'][] ='RedistributorSaleitem.redistributor_id IN (SELECT id FROM redistributors WHERE depot_id = '. $user['depot_id'].' OR region_id = '.$user['region_id'].')';
			break;
			
		}
	
	}
}