<?php

namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use frontend\models\FormData;
use frontend\models\Fakultas;
use frontend\models\Jenjang;
use frontend\models\Prodi;
use yii\web\Response;
use yii\web\UploadedFile;
use yii\helpers\ArrayHelper;
use yii\filters\AccessControl;
use yii\web\ForbiddenHttpException;

class FormController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'only' => ['index', 'get-jenjang', 'get-prodi', 'status', 'update'],
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'], // Hanya user yang login
                    ],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $email = Yii::$app->user->identity->email;
        $existingModel = FormData::findOne(['email' => $email]);

        // Jika sudah ada pengajuan dan status bukan "revisi", redirect ke status
        if ($existingModel && $existingModel->status !== 'revisi') {
            return $this->redirect(['status']);
        }

        $model = $existingModel ?: new FormData();
        $model->email = $email;

        if ($model->load(Yii::$app->request->post())) {
            $model->unggah_lembar_persetujuan_file = UploadedFile::getInstance($model, 'unggah_lembar_persetujuan_file');
            if ($model->save()) {
                Yii::$app->session->setFlash('success', 'Pengajuan Anda berhasil dikirim dan sedang diproses.');
                return $this->redirect(['status']);
            }
        }

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

        return $this->render('index', [
            'model' => $model,
            'fakultas' => $fakultas,
            'jenjang' => [],
            'prodi' => [],
        ]);
    }

    public function actionUpdate($id)
    {
        $email = Yii::$app->user->identity->email;
        $model = FormData::findOne(['id' => $id, 'email' => $email]);
    
        if (!$model || $model->status !== 'revisi') {
            throw new ForbiddenHttpException('Pengajuan tidak dapat diedit.');
        }
    
        // tandai ini update dari frontend
        $model->isFrontend = true;
    
        if ($model->load(Yii::$app->request->post())) {
            $model->unggah_lembar_persetujuan_file = UploadedFile::getInstance($model, 'unggah_lembar_persetujuan_file');
            if ($model->save()) {
                Yii::$app->session->setFlash('success', 'Pengajuan Anda berhasil diperbarui dan sedang diproses ulang.');
                return $this->redirect(['status']);
            } else {
                Yii::$app->session->setFlash('error', 'Gagal menyimpan pengajuan: ' . implode(', ', $model->getFirstErrors()));
            }
        }
    
        $fakultas = ArrayHelper::map(Fakultas::find()->all(), 'id', 'nama');
        $jenjang = $model->fakultas_id ? ArrayHelper::map(Jenjang::find()->where(['fakultas_id' => $model->fakultas_id])->all(), 'id', 'nama') : [];
        $prodi = ($model->fakultas_id && $model->jenjang_id) ? ArrayHelper::map(Prodi::find()->where(['fakultas_id' => $model->fakultas_id, 'jenjang_id' => $model->jenjang_id])->all(), 'id', 'nama') : [];
    
        return $this->render('index', [
            'model' => $model,
            'fakultas' => $fakultas,
            'jenjang' => $jenjang,
            'prodi' => $prodi,
        ]);
    }
    

public function actionDownload($id)
{
    $email = Yii::$app->user->identity->email;
    $model = FormData::findOne(['id' => $id, 'email' => $email]);

    if (!$model || !$model->file_path) {
        throw new \yii\web\NotFoundHttpException('File tidak ditemukan.');
    }

    $filePath = Yii::getAlias('@frontend/web/') . $model->file_path;
    if (file_exists($filePath)) {
        return Yii::$app->response->sendFile($filePath, basename($model->file_path));
    }

    throw new \yii\web\NotFoundHttpException('File tidak ditemukan.');
}

    public function actionGetJenjang($fakultas_id)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $jenjang = Jenjang::find()->where(['fakultas_id' => $fakultas_id])->all();
        return ArrayHelper::map($jenjang, 'id', 'nama');
    }

    public function actionGetProdi($fakultas_id, $jenjang_id)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $prodi = Prodi::find()
            ->where(['fakultas_id' => $fakultas_id, 'jenjang_id' => $jenjang_id])
            ->all();
        return ArrayHelper::map($prodi, 'id', 'nama');
    }

    public function actionStatus()
    {
        $email = Yii::$app->user->identity->email;
        $models = FormData::find()
            ->where(['email' => $email])
            ->orderBy(['id' => SORT_DESC])
            ->all();

        return $this->render('status', [
            'models' => $models,
        ]);
    }
}