<?php

namespace backend\controllers;

use backend\models\Jenjang;
use backend\models\JenjangSearch;
use backend\models\Fakultas; // Tambahkan ini
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;

/**
 * JenjangController implements the CRUD actions for Jenjang model.
 */
class JenjangController extends Controller
{
    public function behaviors()
    {
        return array_merge(
            parent::behaviors(),
            [
                'verbs' => [
                    'class' => VerbFilter::className(),
                    'actions' => [
                        'delete' => ['POST'],
                    ],
                ],
            ]
        );
    }

    public function actionIndex()
    {
        $searchModel = new JenjangSearch();
        $dataProvider = $searchModel->search($this->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function actionCreate()
{
    $model = new Jenjang();

    // Ambil list fakultas id dan nama, untuk dropdown
    $fakultasList = ArrayHelper::map(Fakultas::find()->all(), 'id', 'nama');

    if ($this->request->isPost) {
        if ($model->load($this->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }
    } else {
        $model->loadDefaultValues();
    }

    return $this->render('create', [
        'model' => $model,
        'fakultasList' => $fakultasList,
    ]);
}

public function actionUpdate($id)
{
    $model = $this->findModel($id);

    $fakultasList = ArrayHelper::map(Fakultas::find()->all(), 'id', 'nama');

    if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->id]);
    }

    return $this->render('update', [
        'model' => $model,
        'fakultasList' => $fakultasList,
    ]);
}
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    protected function findModel($id)
    {
        if (($model = Jenjang::findOne(['id' => $id])) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
