<?php
/**
 * IMPORTANT NOTE
 * The code of this system is closed and a private proprietary of Flex Solutions.
 * A written authorization/license from Flex Solutions is required before using or modifying this code.
 * Email: sales@flexsolution.biz, Phone: +962795342585, Website: http://www.flexsolutions.biz
 */
 

/**
 * This is the model class for table "item_request_detail".
 *
 * The followings are the available columns in table 'item_request_detail':
 * @property integer $id
 * @property integer $item_id
 * @property string $item_request_header_id
 * @property integer $quantity
 *
 * The followings are the available model relations:
 * @property Item $item
 * @property ItemRequestHeader $itemRequestHeader
 */
class ItemRequestDetail extends CActiveRecord {

    /**
     * @return string the associated database table name
     */
    public function tableName() {
	return 'item_request_detail';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
	// NOTE: you should only define rules for those attributes that
	// will receive user inputs.
	return array(
	    array('item_id, item_request_header_id, quantity', 'required'),
	    array('item_id', 'numerical', 'integerOnly' => true),
	    array('quantity', 'numerical', 'integerOnly' => true, 'min' => 1),
	    array('item_request_header_id', 'length', 'max' => 25),
	    // The following rule is used by search().
	    // @todo Please remove those attributes that should not be searched.
	    array('id, item_id, item_request_header_id, quantity', 'safe', 'on' => 'search'),
	);
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
	// NOTE: you may need to adjust the relation name and the related
	// class name for the relations automatically generated below.
	return array(
	    'item' => array(self::BELONGS_TO, 'Item', 'item_id'),
	    'itemRequestHeader' => array(self::BELONGS_TO, 'ItemRequestHeader', 'item_request_header_id'),
	);
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
	return array(
	    'id' => 'ID',
	    'item_id' => 'Item',
	    'item_request_header_id' => 'Item Request Header',
	    'quantity' => 'Quantity',
	);
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search() {
	// @todo Please modify the following code to remove attributes that should not be searched.

	$criteria = new CDbCriteria;

	$criteria->compare('id', $this->id);
	$criteria->compare('item_id', $this->item_id);
	$criteria->compare('item_request_header_id', $this->item_request_header_id, true);
	$criteria->compare('quantity', $this->quantity);

	return new CActiveDataProvider($this, array(
	    'criteria' => $criteria,
	));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return ItemRequestDetail the static model class
     */
    public static function model($className=__CLASS__) {
	return parent::model($className);
    }

    /**
     * The Following function is responsible for return array of items detail models
     * @param integer $model_id id of the model    
     * @return ItemRequestDetail[] array of item detail model .
     */
    public static function getItemsDetail($model_id) {
	$items_detail = ItemRequestDetail::model()->findAllByAttributes(array('item_request_header_id' => $model_id));
	return ($items_detail != null) ? $items_detail : array();
    }

    /**
     * The Following function is responsible for return array of data of the item details of the model
     * @param ItemRequestDetail[]  array of item detail models.
     * @return array array of ItemRequestDetail data.
     */
    public static function getItemsDetailData($items_detail) {
	$dataArray = array();
	if ($items_detail != null) {
	    foreach ($items_detail as $value) {
		if ($value != null) {
		    $columns = array();
		    $columns['id'] = $value->id;
		    $columns['item_id'] = $value->item->name;
		    $columns['quantity'] = $value->quantity;
		    $dataArray[] = $columns;
		}
	    }
	}
	return $dataArray;
    }

    public static function saveItemsDetail(&$error_msg, $model) {
	$items_detail_models = ItemRequestDetail::getItemsDetail($model->id);
	$items_detail_array = null;

	if ($model->items_detail_array != null && $model->items_detail_array != "") {
	    $array = json_decode($model->items_detail_array);
	    foreach ($array as $value) {
		if ($value != null) {
		    $columns = array();
		    $columns['id'] = $value->id;
		    $columns['item_name'] = $value->item_name;
		    $columns['quantity'] = $value->quantity;
		    $items_detail_array[] = $columns;
		}
	    }
	    if ($items_detail_array != null) {
		foreach ($items_detail_array as $items_detail) {
		    if (!ItemRequestDetail::checkElementInArrayAndRemoveIt($items_detail['id'], $shareholder_relatives)) {
			$item_id = Item::getIdByName($items_detail['item_name']);
			if ($item_id != null) {
			    $detail_model = new ItemRequestDetail();
			    $detail_model->item_request_header_id = $model->id;
			    $detail_model->item_id = $item_id;
			    $detail_model->quantity = $items_detail['quantity'];
			    if (!$detail_model->save()) {
				$error_msg = CHtml::errorSummary($detail_model);
				return false;
			    }
			} else {
			    $error_msg = yii::t('default', 'This Item (item_name) is not found in the system.', array("item_name" => $items_detail['item_name']));
			    return false;
			}
		    }
		}
	    }
	}


	if ($items_detail_models != null) {
	    if (($items_detail_array == null && $items_detail_array->items_detail_array != "") || ($items_detail_array != null && $model->items_detail_array != null))
		foreach ($items_detail_models as $items_detail_model) {
		    $items_detail_model->delete();
		}
	}

	return true;
    }

    public static function checkElementInArrayAndRemoveIt($id, &$array_ids) {
	$found_index = -1;
	if ($array_ids != null) {
	    foreach ($array_ids as $key => $array_id) {
		if ($array_id['id'] == $id) {
		    $found_index = $key;
		    break;
		}
	    }
	}
	if ($found_index != -1) {
	    unset($array_ids[$found_index]);
	    return true;
	}
	return false;
    }

    public static function getItemDetailHtml($item_header_id) {
	$dialog_content = "";
	$items_detail_models = ItemRequestDetail::getItemsDetail($item_header_id);
	if ($items_detail_models != null) {
	    $dialog_content = "<table style='width:500px'><tr><td style='font-weight:bold'>Item</td><td style='font-weight:bold'>Quantity</td></tr>";
	    foreach ($items_detail_models as $items_detail_model) {
		$dialog_content .= "<tr><td style='width:70%'>" . $items_detail_model->item->name . "</td><td>" . $items_detail_model->quantity . "</td></tr>";
	    }
	    $dialog_content .= "</table>";
	}
	return $dialog_content;
    }

}
