<?php

class ExpensesettlementController extends Controller
{
    public function accessRules()
    {
        return array(
            array(
                'allow',
                'actions' => array('login', 'error', 'logout', 'newlogin'),
                'users' => array('*'),
            ),
            array(
                'allow',
                'actions' => array('index', 'GetList', 'Create', 'GetUserBalance','SaveExpenseType','ExpenseDetails','ExpenseList','Print'),
                'expression' => '$user->isMember()',
            ),
            array(
                'deny',
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex()
    {
        $user_id   = (int) Yii::app()->user->id; 
        $modeluser = User::model()->findByPk($user_id);

        if ($modeluser->user_group_id != 1) { 
            $this->redirect(Yii::app()->baseUrl . '/index.php');
            Yii::app()->end();
        }
        $this->render('index');
    }

  public function actionGetList()
{
    $model = new ExpenseSettlement();

    $draw   = isset($_POST['draw']) ? intval($_POST['draw']) : 1;
    $offset = isset($_POST['start']) ? intval($_POST['start']) : 0;
    $limit  = isset($_POST['length']) ? intval($_POST['length']) : 10;

    $condition = '1=1';
    $user_id =  (int)Yii::app()->user->id;
    $modeluser = User::model()->findByPk($user_id);

    if (!empty($_POST['search']['value'])) {
        $searchString = $_POST['search']['value'];
        $condition .= " AND (
            id LIKE :search
            OR settlement_date LIKE :search
            OR user_id LIKE :search
            OR unsettled_expenses LIKE :search
        )";
    }
    if($modeluser->user_group_id != 1 )
    {
    $condition.=' AND user_id ='.$user_id;
    }

    // Count total records
    $count = $model->count(array(
        'condition' => $condition,
        'params'    => !empty($searchString) ? array(':search' => "%$searchString%") : array()
    ));

    // Fetch data with limit and offset
    $modelData = $model->findAll(array(
        'condition' => $condition,
        'params'    => !empty($searchString) ? array(':search' => "%$searchString%") : array(),
        'limit'     => $limit,
        'offset'    => $offset,
        'order'     => 'id DESC'
    ));

    // Prepare user names
    $userIds = array();
    foreach ($modelData as $row) {
        if ($row->user_id) {
            $userIds[] = $row->user_id;
        }
    }

    $userNames = array();
    if (!empty($userIds)) {
        $userNames = User::getUserbyId(implode(',', array_unique($userIds)));
    }

    $data = array(
        'draw'            => $draw,
        'recordsTotal'    => $count,
        'recordsFiltered' => $count,
        'data'            => array()
    );

    $si = $offset;
    foreach ($modelData as $row) {
        $data['data'][] = array(
            ++$si,
            !empty($row->settlement_date) ? date('d/m/Y', strtotime($row->settlement_date)) : '-',
            isset($userNames[$row->user_id]) ? $userNames[$row->user_id] : '',
            number_format($row->unsettled_expenses,2, '.', ','),
            number_format($row->balance,2, '.', ','),
            number_format($row->amount_returned,2, '.', ','),
            number_format($row->amount_dispersed,2, '.', ','),
            number_format($row->new_balance,2, '.', ','),
            $row->id // ID as flat column
        );
    }

    echo json_encode($data);
    Yii::app()->end();
}


public function actionCreate()
{
    $model = new ExpenseSettlement();
    $id = (int) Yii::app()->request->getParam('id');
    if ($id > 0) {
        $model = $model->findByPk($id);
    }

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

    $criteria = new CDbCriteria();
    $criteria->order = 'id ASC';

    if ($modeluser->user_group_id != 1) {
        $criteria->addCondition('created_by = :user_id');
        $criteria->params[':user_id'] = $user_id;
    }

    $users = User::model()->findAll($criteria);

    $found = false;
    foreach ($users as $u) {
        if ($u->id == $user_id) {
            $found = true;
            break;
        }
    }

    if (!$found) {
        $users[] = $modeluser; 
    }

    $userList = CHtml::listData($users, 'id', 'first_name');



    $from = Yii::app()->request->getParam('from', '');

    Yii::app()->clientScript->scriptMap = array(
        '*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', array(
        'model' => $model,
        'from' => $from,
        'users' => $userList
    ), false, true);
}



public function actionGetUserBalance()
{
    if (isset($_POST['user_id'])) {
        $userId = (int)$_POST['user_id'];

        $records = ExpenseDetails::model()->findAll(
            'created_by=:uid AND isActive=:active',
            array(':uid' => $userId, ':active' => 'N')
        );

        $unsettled = 0;
        $expenseDetailsIds = []; 

        foreach ($records as $r) {
            $unsettled += $r->amount;
            $expenseDetailsIds[] = $r->id; 
        }

        $lastSettlement = ExpenseSettlement::model()->find(array(
            'condition' => 'user_id = :uid',
            'params'    => array(':uid' => $userId),
            'order'     => 'id DESC'
        ));

        $balance = ($lastSettlement !== null) ? $lastSettlement->new_balance : 0;
        $new_balance = ($balance > 0) ? ($balance - $unsettled) : $unsettled;

        echo CJSON::encode(array(
            'unsettled'          => $unsettled,
            'balance'            => $new_balance,
            'expense_details_id' => $expenseDetailsIds 
        ));

        Yii::app()->end();
    }
}


public function actionSaveExpenseType()
{
    if (!isset($_POST['ExpenseSettlement'])) {
        Yii::app()->end();
    }


    $post = $_POST['ExpenseSettlement'];

    if (!empty($post['id'])) {
        $model = ExpenseSettlement::model()->findByPk((int)$post['id']);
        if ($model === null) {
            echo CJSON::encode([
                'status' => 'error',
                'msg' => 'Record not found'
            ]);
            Yii::app()->end();
        }

        $model->updated_by = Yii::app()->user->id;

    } else {

        $model = new ExpenseSettlement();
        $model->created_by = Yii::app()->user->id;
    }

    $model->attributes = $post;

    if (!empty($post['settlement_date'])) {

        $timestamp = CDateTimeParser::parse($post['settlement_date'], 'dd/MM/yyyy');

        if ($timestamp !== false) {
            $model->settlement_date = date('Y-m-d', $timestamp);
        }
    } 
    if (!empty($_POST['user_id'])) {
        $model->user_id = $_POST['user_id'];
    }

    $model->isActive = (!empty($post['isActive']) && $post['isActive'] == 1) ? 'Y' : 'N';
    $expense_details_id = $_POST['ExpenseSettlement']['expense_details_id'];
    $model->expense_details_id = '[' . $expense_details_id . ']';

    if ($model->validate()) {

        $model->save(false);

        if ($model->isActive === 'Y') {
            ExpenseDetails::model()->updateAll(
                ['isActive' => 'Y'],
                'created_by = :uid',
                [':uid' => $model->user_id]
            );
        }

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

    } else {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }
}
public function actionExpenseDetails()
{
  Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
  $this->renderPartial('expense_details', array(), false, true);
}
public function actionExpenseList()
{
    $draw   = isset($_POST['draw']) ? (int)$_POST['draw'] : 1;
    $start  = isset($_POST['start']) ? (int)$_POST['start'] : 0;
    $length = isset($_POST['length']) ? (int)$_POST['length'] : 50;

    $id = Yii::app()->request->getParam('id');
    if (!$id) {
        echo CJSON::encode(array(
            'draw' => $draw,
            'recordsTotal' => 0,
            'recordsFiltered' => 0,
            'data' => array()
        ));
        Yii::app()->end();
    }

    $settlement = ExpenseSettlement::model()->findByPk($id);
    if (!$settlement || empty($settlement->expense_details_id)) {
        echo CJSON::encode(array(
            'draw' => $draw,
            'recordsTotal' => 0,
            'recordsFiltered' => 0,
            'data' => array()
        ));
        Yii::app()->end();
    }

    $expenseIds = json_decode($settlement->expense_details_id, true);
    if (!is_array($expenseIds) || empty($expenseIds)) {
        echo CJSON::encode(array(
            'draw' => $draw,
            'recordsTotal' => 0,
            'recordsFiltered' => 0,
            'data' => array()
        ));
        Yii::app()->end();
    }

    $columns = array(
        0 => 't.id',
        1 => 'expense.expense_date',      
        2 => 'expenseType.expense_type', 
        3=> 'description', 
        4 => 't.account_no',
        4 => 't.amount',
        // 5 => 't.created_by'
    );

    $orderCol = isset($_POST['order'][0]['column']) ? (int)$_POST['order'][0]['column'] : 0;
    $orderDir = (isset($_POST['order'][0]['dir']) && $_POST['order'][0]['dir'] === 'desc') ? 'desc' : 'asc';
    $orderBy  = isset($columns[$orderCol]) ? $columns[$orderCol] : 't.id';

    $totalCriteria = new CDbCriteria();
    $totalCriteria->addInCondition('t.id', $expenseIds);
    $recordsTotal = ExpenseDetails::model()->count($totalCriteria);

    $criteria = new CDbCriteria();
    $criteria->addInCondition('t.id', $expenseIds);
    $criteria->with = array('expenseType', 'expense'); 

    if (!empty($_POST['search']['value'])) {
        $search = $_POST['search']['value'];
        $criteria->addCondition(
            '(t.amount LIKE :s OR t.created_by LIKE :s OR expenseType.expense_type LIKE :s OR expense.expense_date LIKE :s)'
        );
        $criteria->params[':s'] = "%$search%";
    }

    $recordsFiltered = ExpenseDetails::model()->count($criteria);

    $criteria->limit  = $length;
    $criteria->offset = $start;
    $criteria->order  = $orderBy . ' ' . $orderDir;

    $rows = ExpenseDetails::model()->findAll($criteria);

    $userIds = array();
    foreach ($rows as $row) {
        if (!empty($row->created_by)) {
            $userIds[] = $row->created_by;
        }
    }
    $userIds = array_unique($userIds);

    $userList = !empty($userIds) ? User::getUserbyId(implode(',', $userIds)) : array();

    $data = array();
    $no = $start + 1;
    foreach ($rows as $row) {
        $username = isset($userList[$row->created_by]) ? $userList[$row->created_by] : '-';
        $data[] = array(
            $no++,                                             
            (!empty($row->expense->expense_date)) 
            ? date('d/m/Y', strtotime($row->expense->expense_date)) 
            : '-',
            isset($row->expenseType->expense_type) ? $row->expenseType->expense_type : '-', 
             isset($row->description) ? $row->description : '-', 
            isset($row->expenseType->account_no) ? $row->expenseType->account_no : '-', 
            number_format((float)$row->amount, 2, '.', ','),
            // $username                                         
        );
    }

    echo CJSON::encode(array(
        'draw' => $draw,
        'recordsTotal' => $recordsTotal,
        'recordsFiltered' => $recordsFiltered,
        'data' => $data
    ));

    Yii::app()->end();
}



public function actionPrint()
{
    $id = Yii::app()->request->getParam('id');
    $settlement = ExpenseSettlement::model()->findByPk($id);


    $expense_details = [];
    $username = ''; 

    if ($settlement) {

        if (!empty($settlement->expense_details_id)) {
            $expenseIds = json_decode($settlement->expense_details_id, true);
            if (!is_array($expenseIds)) {
                $expenseIds = [];
            }

            if (!empty($expenseIds)) {
                $criteria = new CDbCriteria();
                $criteria->addInCondition('t.id', $expenseIds);
                $criteria->with = ['expenseType'];
                $criteria->together = true;

                $expense_details = ExpenseDetails::model()->findAll($criteria);

                $createdByIds = [];
                foreach ($expense_details as $exp) {
                    if (!empty($exp->created_by)) {
                        $createdByIds[] = $exp->created_by;
                    }
                }
                $createdByIds = array_unique($createdByIds);

                if (!empty($createdByIds)) {
                    $usernames = User::getUserbyId(implode(',', $createdByIds));
                    foreach ($expense_details as $exp) {
                        $exp->created_by = $usernames[$exp->created_by] ?? '-';
                        $expenseData = Expense::model()->findByPk($exp->expense_id);
                        $exp->expense_date      = $expenseData->expense_date ?? '';
                        $expenseType = MasExpenseType::model()->findByPk($exp->expense_type_id);
                        $exp->expense_type_name = $expenseType->expense_type ?? '';
                        $exp->account_no        = $expenseType->account_no ?? '';

                    }
                }
            }
        }

        if (!empty($settlement->user_id)) {
            $userData = User::getUserbyId($settlement->user_id);
            if (isset($userData[$settlement->user_id])) {
                $username = $userData[$settlement->user_id];
            }
        }
    }

    $param = [
        'id' => $id,
        'expense_details' => $expense_details,
        'username' => $username,
        'settlement' => $settlement
    ];

    $mpdf = Yii::app()->ePdf->mpdf('', 'A4');
    $stylesheet = file_get_contents(Yii::getPathOfAlias('webroot.css') . '/pdf_style.css');
    $mpdf->WriteHTML($stylesheet, 1);
    $mpdf->WriteHTML($this->renderPartial('print_details', $param, true));
    $mpdf->Output("settlementdetails" . date('dmYhis') . ".pdf", 'I');
}




}
