<?php
class CustomerlocationsController extends Controller
{
    public function accessRules()
    {
        return array(
            array('allow',
                'actions' => array('login', 'error', 'logout', 'newlogin'),
                'users' => array('*'),
            ),
            array('allow',
                'actions' => array('index', 'getList', 'create', 'save', 'disable', 'getCustomers'),
                'expression' => '$user->isMember()',
            ),
            array('deny',
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex()
    {
        $this->render('index');
    }

    // Get customers for dropdown AJAX
    public function actionGetCustomers()
    {
        $customers = Customers::model()->findAll(array(
            'condition' => 'isActive="Y"',
            'order' => 'customer_name ASC'
        ));
        $customerList = array();
        foreach($customers as $c) {
            $customerList[] = array(
                'id' => $c->id,
                'customer_name' => $c->customer_name
            );
        }
        echo CJSON::encode($customerList);
        Yii::app()->end();
    }

    public function actionGetList()
    {
        $draw   = (int) $_POST['draw'];
        $offset = (int) $_POST['start'];
        $limit  = (int) $_POST['length'];

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

        $criteria = new CDbCriteria();
        $criteria->with = array('customer');
        $criteria->together = true;

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

        $totalCriteria = clone $criteria;
        $recordsTotal = CustomerLocations::model()->count($totalCriteria);

        if (!empty($_POST['search']['value'])) {
            $search = $_POST['search']['value'];
            $criteria->addSearchCondition('customer.customer_name', $search, true, 'OR');
            $criteria->addSearchCondition('t.customer_locations', $search, true, 'OR');
        }

        $filteredCriteria = clone $criteria;
        $recordsFiltered = CustomerLocations::model()->count($filteredCriteria);

        $criteria->limit  = $limit;
        $criteria->offset = $offset;
        $criteria->order  = 't.id ASC';

        $models = CustomerLocations::model()->findAll($criteria);

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

        foreach ($models as $row) {
            $status = ($row->isActive === 'Y')
                ? '<span class="label label-success">Active</span>'
                : '<span class="label label-warning">Inactive</span>';

            $rowData[] = [
                ++$m,
                $row->customer ? $row->customer->customer_name : '-',
                $row->customer_locations,
                $status,
                ['id' => $row->id, 'isActive' => $row->isActive]
            ];
        }

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

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

        if ($id > 0) {
            $model = CustomerLocations::model()->findByPk($id);
            if ($model === null) {
                throw new CHttpException(404, 'Record not found');
            }
        }

        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', array(
            'model' => $model,
            'editId' => $id
        ), false, true);
    }

    public function actionSave()
    {
        $editId = (int) Yii::app()->request->getParam('edit_id', 0);
        
        if (empty($_POST['CustomerLocations'])) {
            echo CJSON::encode(array('status'=>'error','message'=>'No data received'));
            Yii::app()->end();
        }

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

        try {
            // EDIT MODE: Update single record
            if ($editId > 0) {
                $model = CustomerLocations::model()->findByPk($editId);
                if (!$model) {
                    throw new Exception("Record not found");
                }
                
                $model->customer_id = $rows[0]['customer_id'];
                $model->customer_locations = trim($rows[0]['customer_locations']);
                $model->isActive = 'Y';
                $model->updated_by = Yii::app()->user->id;
                $model->updated_date_time = date('Y-m-d H:i:s');
                
                if (!$model->save(false)) {
                    throw new Exception("Update failed");
                }
                
                $transaction->commit();
                echo CJSON::encode(array('status'=>'success', 'message'=>'Updated successfully'));
                Yii::app()->end();
            }
            
            // ADD MODE: Create new records
            foreach ($rows as $row) {
                if (empty($row['customer_id']) || empty($row['customer_locations'])) {
                    continue;
                }

                $model = new CustomerLocations();
                $model->customer_id = $row['customer_id'];
                $model->customer_locations = trim($row['customer_locations']);
                $model->isActive = 'Y';
                $model->created_by = Yii::app()->user->id;
                $model->created_date_time = date('Y-m-d H:i:s');
                $model->updated_by = Yii::app()->user->id;
                $model->updated_date_time = date('Y-m-d H:i:s');

                if (!$model->save(false)) {
                    throw new Exception("Save failed for customer: " . $row['customer_id']);
                }
            }

            $transaction->commit();
            echo CJSON::encode(array('status'=>'success', 'message'=>'Added successfully'));
        } catch (Exception $e) {
            $transaction->rollback();
            echo CJSON::encode(array(
                'status'=>'error',
                'message'=>array($e->getMessage())
            ));
        }
        Yii::app()->end();
    }

    public function actionDisable()
    {
        $id     = Yii::app()->request->getParam('id');
        $status = Yii::app()->request->getParam('status');

        $model = CustomerLocations::model()->findByPk($id);

        if ($model === null) {
            echo CJSON::encode(array('status' => 'fail'));
            Yii::app()->end();
        }

        $model->isActive = ($status == 'Y') ? 'N' : 'Y';
        $model->updated_by = Yii::app()->user->id;
        $model->updated_date_time = date('Y-m-d H:i:s');

        if ($model->save(false)) {
            echo CJSON::encode(array('status' => 'success'));
        } else {
            echo CJSON::encode(array('status' => 'fail'));
        }
        Yii::app()->end();
    }
}
?>
