<?php

class StateController 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'),
                'expression' => '$user->isMember()',
            ),

            array('deny',
                'users' => array('*'),
            ),
        );
    }

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

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

        $criteria = new CDbCriteria();
        $criteria->with = array('country'); // 👈 JOIN COUNTRY TABLE
        $criteria->together = true;
        $criteria->limit  = $limit;
        $criteria->offset = $offset;
        $criteria->order  = 't.id ASC';

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

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

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

        foreach ($models as $row) {

            $status = ($row->isActive === 'Y')
    ? '<span class="label label-success">Active</span>'
    : '<span class="label label-danger">Inactive</span>';

    $rowData[] = [
        ++$m,
        $row->state_name,
        $row->country ? $row->country->country_name : '-',
        $status,
        array(
            'id' => $row->id,
            'status' => $row->isActive
        )
    ];
        }

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

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

    if ($id > 0) {

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

        if ($model === null) {
            throw new CHttpException(404, 'State not found');
        }

        $stateModels = array($model);

    } else {

        $stateModels = array(new States());
    }

    $countryList = CHtml::listData(
        Country::model()->findAll(array('order' => 'country_name ASC')),
        'id',
        'country_name'
    );

    Yii::app()->clientScript->scriptMap = array(
        '*jquery.js' => false,
        '*jquery.min.js' => false,
        'jquery.min.js' => false,
    );

    $this->render(
        'create',
        array(
            'model' => $model,
            'countryList' => $countryList,
            'stateModels' => $stateModels  
        ),
        false,
        true
    );
}

    // =======================
    // SAVE STATE
    // =======================
public function actionSave()
{
    if (!isset($_POST['States'])) {
        throw new CHttpException(400, 'Invalid request.');
    }

    $post = $_POST['States'];

    foreach ($post as $key => $row) {

        if (!is_numeric($key)) continue;

        // Validate empty fields and return error
        if (empty($row['country_id']) || empty($row['state_name'])) {
            echo CJSON::encode([
                'status'  => 'error',
                'message' => 'Country and State Name are required.'
            ]);
            Yii::app()->end();
        }

        if (!empty($row['id'])) {
            $model = States::model()->findByPk((int)$row['id']);
            if (!$model) continue;
            $model->updated_by       = Yii::app()->user->id;
            $model->updated_datetime = date('Y-m-d H:i:s');
        } else {
            $model                   = new States();
            $model->created_by       = Yii::app()->user->id;
            $model->created_datetime = date('Y-m-d H:i:s');
            $model->isActive         = 'Y';
        }

        $model->country_id = $row['country_id'];
        $model->state_name = $row['state_name'];

        if (!$model->save()) {
            echo CJSON::encode([
                'status'  => 'error',
                'message' => print_r($model->getErrors(), true)
            ]);
            Yii::app()->end();
        }
    }

    echo CJSON::encode(['status' => 'success']);
    Yii::app()->end();
}
    public function actionDisable()
{
    $id = Yii::app()->request->getParam('id');

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

    if ($model === null) {
        echo CJSON::encode(array(
            'status' => 'error',
            'message' => 'State not found'
        ));
        Yii::app()->end();
    }

    if ($model->isActive == 'Y') {
        $model->isActive = 'N';
    } else {
        $model->isActive = 'Y';
    }

    if ($model->save(false)) {
        echo CJSON::encode(array(
            'status' => 'success'
        ));
    } else {
        echo CJSON::encode(array(
            'status' => 'error'
        ));
    }

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