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

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

    public function actionGetList()
    {
        $request = Yii::app()->request;
        if (!$request->isPostRequest) {
            throw new CHttpException(400, 'Invalid request method.');
        }

        $draw = (int) $request->getPost('draw', 1);
        $offset = (int) $request->getPost('start', 0);
        $limit = max(1, min((int) $request->getPost('length', 10), 100));
        $locationId = !empty($request->getPost('location_id')) ? (int) $request->getPost('location_id') : 0;
        $searchValue = trim((string) @$request->getPost('search.value', ''));

        $criteria = new CDbCriteria();
        $criteria->order = 't.customer_name ASC';
        $criteria->with = array('location', 'country', 'state');
        $criteria->together = true;
        $criteria->limit = $limit;
        $criteria->offset = $offset;

        if ($locationId > 0) {
            $criteria->compare('t.location_id', $locationId);
        }

        if ($searchValue !== '') {
            $criteria->compare('t.customer_name', $searchValue, true, 'OR');
            $criteria->compare('t.email', $searchValue, true, 'OR');
            $criteria->compare('t.phone_no', $searchValue, true, 'OR');
        }

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

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

            $imageCol = '-';
            if (!empty($row->img_upload)) {
                $imageUrl = Yii::app()->baseUrl . '/uploads/customers/' . $row->img_upload;
                $imageCol = '<a href="' . $imageUrl . '" target="_blank"><img src="' . $imageUrl . '" width="40" style="cursor:pointer;"><br>' . $row->img_upload . '</a>';
            }

            $rowData[] = array(
                ++$counter,
                CHtml::encode($row->customer_name),
                CHtml::encode($row->phone_no),
                CHtml::encode($row->email),
                CHtml::encode($row->Address),
                $imageCol,
                $status,
                $row->location ? CHtml::encode($row->location->location_name) : '-',
                $row->country ? CHtml::encode($row->country->country_name) : '-',
                $row->state ? CHtml::encode($row->state->state_name) : '-',
                array('id' => $row->id, 'status' => $row->isActive) // Action data
            );
        }

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

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

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

        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), false, true);
    }

    /**
     * Fixed: Proper file validation, error handling, Yii request usage.
     */
    public function actionSave()
    {
        $request = Yii::app()->request;
        $postData = $request->getPost('Customers', array());
        $id = isset($postData['id']) ? (int) $postData['id'] : 0;

        if ($id > 0) {
            $model = Customers::model()->findByPk($id);
            if ($model === null) {
                echo CJSON::encode(array('status' => 'error', 'message' => 'Customer not found'));
                Yii::app()->end();
            }
        } else {
            $model = new Customers();
            $model->created_by = Yii::app()->user->id;
            $model->created_datetime = date('Y-m-d H:i:s');
            $model->isActive = 'Y';
        }

        // Safe mass assignment
        $model->attributes = $postData;
        $model->updated_by = Yii::app()->user->id;
        $model->updated_datetime = date('Y-m-d H:i:s');

        // Fixed: Proper file validation for customer image
        $uploadedFile = CUploadedFile::getInstanceByName('img_upload');
        if ($uploadedFile !== null) {
            $fileError = $this->_validateCustomerImage($uploadedFile);
            if ($fileError !== null) {
                echo CJSON::encode(array('status' => 'error', 'message' => $fileError));
                Yii::app()->end();
            }

            $uploadDir = Yii::app()->basePath . '/../uploads/customers/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            // Delete old image if exists
            if (!$model->isNewRecord && !empty($model->img_upload)) {
                $oldFile = $uploadDir . $model->img_upload;
                if (is_file($oldFile)) {
                    @unlink($oldFile);
                }
            }

            $fileName = time() . '_' . preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $uploadedFile->name);
            if (!$uploadedFile->saveAs($uploadDir . $fileName)) {
                echo CJSON::encode(array('status' => 'error', 'message' => 'Image could not be saved'));
                Yii::app()->end();
            }
            $model->img_upload = $fileName;
        }

        $transaction = Yii::app()->db->beginTransaction();
        try {
            if ($model->save(false)) {
                $transaction->commit();
                echo CJSON::encode(array('status' => 'success', 'customer_id' => $model->id));
            } else {
                $transaction->rollback();
                $errors = $this->_formatModelErrors($model);
                echo CJSON::encode(array('status' => 'error', 'message' => $errors));
            }
        } catch (Exception $e) {
            $transaction->rollback();
            echo CJSON::encode(array('status' => 'error', 'message' => 'Save failed: ' . $e->getMessage()));
        }
        Yii::app()->end();
    }

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

        $model = Customers::model()->findByPk($id);
        if ($model === null) {
            echo CJSON::encode(array('status' => 'error', 'message' => 'Customer not found'));
            return;
        }

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

        if ($model->save(false)) {
            echo CJSON::encode(array('status' => 'success', 'isActive' => $model->isActive));
        } else {
            echo CJSON::encode(array('status' => 'error', 'message' => 'Status update failed'));
        }
        Yii::app()->end();
    }

    public function actionGetStates()
    {
        if (!Yii::app()->request->isAjaxRequest) {
            echo CJSON::encode(array());
            Yii::app()->end();
        }

        $countryId = (int) Yii::app()->request->getParam('country_id');
        if (!$countryId) {
            echo CJSON::encode(array());
            Yii::app()->end();
        }

        $states = States::model()->findAll(
            'country_id = :cid AND isActive = :a',
            array(':cid' => $countryId, ':a' => 'Y')
        );

        $result = array();
        foreach ($states as $s) {
            $result[] = array('id' => $s->id, 'name' => $s->state_name);
        }

        echo CJSON::encode($result);
        Yii::app()->end();
    }

    // -------------------------------------------------------------------------
    // Private Helpers
    // -------------------------------------------------------------------------

    /**
     * Validate customer image upload (jpg, png, max 2MB).
     */
    private function _validateCustomerImage(CUploadedFile $file)
    {
        $allowedImageExt = array('jpg', 'jpeg', 'png');
        $ext = strtolower($file->extensionName);
        if (!in_array($ext, $allowedImageExt, true)) {
            return 'Invalid image type. Allowed: jpg, jpeg, png.';
        }
        if ($file->size > 2097152) { // 2MB
            return 'Image exceeds 2MB limit.';
        }
        return null;
    }

    /**
     * Format model validation errors properly.
     */
    private function _formatModelErrors($model)
    {
        $errors = array();
        foreach ($model->getErrors() as $attribute => $attributeErrors) {
            $errors = array_merge($errors, $attributeErrors);
        }
        return $errors;
    }
}
