<?php

class ExpenseController extends Controller
{   

	public function accessRules() {

		return array(

                array('allow', // allow all users to perform 'index' and 'view' actions

                	'actions' => array('login', 'error', 'logout','newlogin'),

                	'users' => array('*'),

                ),

                array('allow', // allow authenticated user to perform 'create' and 'update' actions

                	'actions' => array('Index','GetList','create','save'),

                	'expression' => '$user->isMember()',

                ),

                array('deny', // deny all users

                	'users' => array('*'),

                ),

            );

	}
	public function actionIndex()
	{
		$this->render('index');
	}
	public function actionGetList()
{
    $draw   = (int) $_POST['draw'];
    $offset = (int) $_POST['start'];
    $limit  = (int) $_POST['length'];

    $expense_type_id = !empty($_POST['expense_type_id']) ? $_POST['expense_type_id'] : '';
    $user_id_filter  = !empty($_POST['user_id']) ? (int) $_POST['user_id'] : 0;

    $currentUserId = (int) Yii::app()->user->id;
    $modeluser     = User::model()->findByPk($currentUserId);

    $criteria = new CDbCriteria();
    $criteria->with = array('expenseDetails.expenseType');
    $criteria->together = true;
    $criteria->order = 't.expense_date DESC';
    $criteria->limit  = $limit;
    $criteria->offset = $offset;

    if ($modeluser && $modeluser->user_group_id != 1) {
        $criteria->compare('t.created_by', $currentUserId);
    }

    if (!empty($user_id_filter)) {
        $criteria->compare('t.created_by', $user_id_filter);
    }

    if (!empty($expense_type_id)) {
        $criteria->compare('expenseDetails.expense_type_id', $expense_type_id);
    }


    if (!empty($_POST['search']['value'])) {
        $search = $_POST['search']['value'];
        $criteria->addSearchCondition('t.expense_date', $search, true, 'OR');
        $criteria->addSearchCondition('expenseDetails.description', $search, true, 'OR');
        $criteria->addSearchCondition('expenseDetails.expenseType.expense_type', $search, true, 'OR');
    }

    $models = Expense::model()->findAll($criteria);
    $total  = Expense::model()->count($criteria);

    $userIds = [];
    foreach ($models as $row) {
        if (!empty($row->created_by)) {
            $userIds[] = $row->created_by;
        }
    }
    $userIds = array_unique($userIds);
    $userMap = !empty($userIds) ? User::getUserbyId(implode(',', $userIds)) : [];

    $rowData = [];
    $m = $offset;

    foreach ($models as $row) {
        foreach ($row->expenseDetails as $detail) {

            if (!empty($expense_type_id) && $detail->expense_type_id != $expense_type_id) {
                continue;
            }

            $status = ($detail->isActive === 'Y')
                ? '<span class="label label-success">Settled</span>'
                : '<span class="label label-warning">Unsettled</span>';

            $rowData[] = [
                ++$m,
                !empty($row->expense_date) ? date('d/m/Y', strtotime($row->expense_date)) : '-',
                $detail->expenseType ? $detail->expenseType->expense_type : '-',
                $detail->description,
                number_format($detail->amount, 2, '.', ','),
                $status,
                isset($userMap[$row->created_by]) ? $userMap[$row->created_by] : '-',
                ['id' => $detail->id]
            ];
        }
    }

    echo CJSON::encode([
        'draw'            => $draw,
        'recordsTotal'    => $total,
        'recordsFiltered' => $total,
        'data'            => $rowData
    ]);
}




	public function actionCreate()
	{
		$model = new Expense();
		$id = (int) Yii::app()->request->getParam('id');

		if ($id > 0) {
			$expenseModels = ExpenseDetails::model()->findAllByAttributes([
				'id' => $id
			]);

			if (empty($expenseModels)) {
				throw new CHttpException(404, 'Expense details not found');
			}

			$expenseId = $expenseModels[0]->expense_id;

			$model = Expense::model()->findByPk($expenseId);
			if ($model === null) {
				throw new CHttpException(404, 'Expense not found');
			}

		} else {
			$expenseModels = [new ExpenseDetails()];
		}

		$expenseTypes = CHtml::listData(
			MasExpenseType::model()->findAll(['order' => 'expense_type ASC']),
			'id',
			'expense_type'
		);

		Yii::app()->clientScript->scriptMap = [
			'*jquery.js' => false,
			'*jquery.min.js' => false,
			'jquery.min.js' => false,
			'*jquery-ui.js' => false,
			'*jquery-ui.min.js' => false,
			'jquery-2.1.4.min.js' => false,
		];

		$this->render(
			'create',
			[
				'model' => $model,
				'expenseModels' => $expenseModels,
				'expenseTypes' => $expenseTypes,
			],
			false,
			true
		);
	}
	public function actionSave()
	{
		if (!isset($_POST['Expense'])) {
			throw new CHttpException(400, 'Invalid request.');
		}

		$post = $_POST['Expense'];
		$transaction = Yii::app()->db->beginTransaction();

		$isEdit = !empty($post['id']);
		if ($isEdit) {
			$model = Expense::model()->findByPk((int)$post['id']);
			if (!$model) {
				echo CJSON::encode(['status' => 'error', 'message' => 'Expense not found']);
				Yii::app()->end();
			}
		} else {
			$model = new Expense();
			$model->created_by = Yii::app()->user->id;
			$model->created_date_time = date('Y-m-d H:i:s');
		}

		if (!$isEdit) {
			if (empty($post['expense_date'])) {
				echo CJSON::encode(['status' => 'error', 'message' => 'Expense Date cannot be blank']);
				Yii::app()->end();
			}

			$timestamp = CDateTimeParser::parse($post['expense_date'], 'dd/MM/yyyy');
			$model->expense_date = date('Y-m-d', $timestamp);
		}

		if (!$model->save()) {
			$errors = $model->getErrors();
			$errorMessages = [];
			foreach ($errors as $fieldErrors) {
				$errorMessages = array_merge($errorMessages, $fieldErrors);
			}

			echo CJSON::encode([
				'status' => 'error',
				'message' => implode(', ', $errorMessages)
			]);
			Yii::app()->end();
		}

		$hasDetail = false;

		foreach ($post as $key => $row) {
			if (!is_numeric($key)) continue;
			if (empty($row['expense_type_id']) || empty($row['amount'])) continue;

			$hasDetail = true;

			if (!empty($row['id'])) {
				$detail = ExpenseDetails::model()->findByPk($row['id']);
				if (!$detail) {
					$detail = new ExpenseDetails();
					$detail->expense_id = $model->id;
				}
			} else {
				$detail = new ExpenseDetails();
				$detail->expense_id = $model->id;
			}

			$detail->expense_type_id = $row['expense_type_id'];
			$detail->description = $row['description'];
			$detail->amount = $row['amount'];
			$detail->isActive = 'N';
			$detail->created_by = Yii::app()->user->id;

			if (!$detail->save()) {
				$errors = $detail->getErrors();
				$errorMessages = [];
				foreach ($errors as $fieldErrors) {
					$errorMessages = array_merge($errorMessages, $fieldErrors);
				}

				echo CJSON::encode([
					'status' => 'error',
					'message' => implode(', ', $errorMessages)
				]);
				Yii::app()->end();
			}
		}

		if (!$hasDetail) {
			echo CJSON::encode([
				'status' => 'error',
				'message' => 'Please add at least one expense row'
			]);
			Yii::app()->end();
		}

		$transaction->commit();

		echo CJSON::encode([
			'status' => 'success',
			'id' => $model->id
		]);
		Yii::app()->end();
	}

	




}