<?php
/**
 * Copyright (C) Baluart.COM - All Rights Reserved
 *
 * @since 1.0
 * @author Baluart E.I.R.L.
 * @copyright Copyright (c) 2015 - 2021 Baluart E.I.R.L.
 * @license http://codecanyon.net/licenses/faq Envato marketplace licenses
 * @link https://easyforms.dev/ Easy Forms
 */
namespace app\modules\subscription\controllers;

use app\modules\subscription\models\search\SubscriptionProductSearch;
use app\modules\subscription\models\SubscriptionPrice;
use app\modules\subscription\models\SubscriptionProduct;
use app\modules\subscription\models\SubscriptionProductUserRole;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;

/**
 * AdminController implements the CRUD actions for SubscriptionProduct model.
 */
class AdminController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => [
                            'index',
                            'view',
                            'create',
                            'update',
                            'update-status',
                            'delete',
                            'settings',
                        ],
                        'matchCallback' => function () {
                            return Yii::$app->user->can('manageSite');
                        }
                    ],
                ],
            ],
        ];
    }

    /**
     * Lists all SubscriptionProduct models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SubscriptionProductSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

    /**
     * Displays a single SubscriptionProduct model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new SubscriptionProduct model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new SubscriptionProduct();
        $itemModel = new SubscriptionPrice();
        $postData = Yii::$app->request->post();

        if ($model->load($postData) && $model->validate()) {

            $items = Yii::$app->request->post('SubscriptionPrice',[]);
            $model->items = $items;

            if ($model->save(false)) {
                // Remove old subscription product user roles
                SubscriptionProductUserRole::deleteAll(['product_id' => $model->id]);
                // Save subscription product user roles
                if (isset($postData['SubscriptionProduct']['roles'])) {
                    $roles = $postData['SubscriptionProduct']['roles'];
                    if (is_array($roles)) {
                        foreach ($roles as $role_id) {
                            $subscriptionProductRole = new SubscriptionProductUserRole();
                            $subscriptionProductRole->product_id = $model->id;
                            $subscriptionProductRole->role_id = $role_id;
                            $subscriptionProductRole->save();
                        }
                    }
                }
            }

            Yii::$app->getSession()->setFlash(
                'success',
                Yii::t('app', 'The subscription product has been successfully configured.')
            );

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

        // Select name & description of all user roles
        $roles = Yii::$app->authManager->getRoles();
        $roles = ArrayHelper::map($roles, 'name', 'description');
        // Select role_id of subscription product roles
        $subscriptionProductRoles = ArrayHelper::getColumn($model->subscriptionProductRoles, 'role_id');

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

    /**
     * Updates an existing SubscriptionProduct model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $itemModel = new SubscriptionPrice();
        $request = Yii::$app->request;
        $postData = Yii::$app->request->post();

        if ($model->load($postData) && $model->validate()) {

            $items = $request->post('SubscriptionPrice',[]);

            if (!empty($items)) {
                $model->items = $items;
            }

            if ($model->save(false)) {
                // Remove old subscription product user roles
                SubscriptionProductUserRole::deleteAll(['product_id' => $model->id]);
                // Save subscription product user roles
                if (isset($postData['SubscriptionProduct']['roles'])) {
                    $roles = $postData['SubscriptionProduct']['roles'];
                    if (is_array($roles)) {
                        foreach ($roles as $role_id) {
                            $subscriptionProductRole = new SubscriptionProductUserRole();
                            $subscriptionProductRole->product_id = $model->id;
                            $subscriptionProductRole->role_id = $role_id;
                            $subscriptionProductRole->save();
                        }
                    }
                }

                Yii::$app->getSession()->setFlash(
                    'success',
                    Yii::t('app', 'The subscription product has been successfully configured.')
                );

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

        // Select name & description of all user roles
        $roles = Yii::$app->authManager->getRoles();
        $roles = ArrayHelper::map($roles, 'name', 'description');
        // Select role_id of subscription product roles
        $subscriptionProductRoles = ArrayHelper::getColumn($model->subscriptionProductRoles, 'role_id');

        return $this->render('update', [
            'model' => $model,
            'itemModel' => $itemModel,
            'roles' => $roles,
            'subscriptionProductRoles' => $subscriptionProductRoles,
        ]);
    }

    /**
     * Enable / Disable multiple SubscriptionProduct models
     *
     * @param $status
     * @return \yii\web\Response
     * @throws NotFoundHttpException
     * @throws \Exception
     */
    public function actionUpdateStatus($status)
    {
        $models = SubscriptionProduct::findAll(['id' => Yii::$app->getRequest()->post('ids')]);

        if (!empty($models)) {
            foreach ($models as $model) {
                $model->status = $status;
                $model->update();
            }

            Yii::$app->getSession()->setFlash(
                'success',
                Yii::t('app', 'The selected items have been successfully updated.')
            );

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

        throw new NotFoundHttpException(Yii::t('app', 'Page not found.'));
    }

    /**
     * Deletes an existing SubscriptionProduct model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

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

    /**
     * Global settings for Subscriptions
     *
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionSettings()
    {
        $this->layout = '/admin';

        $request = Yii::$app->request;
        $settings = Yii::$app->settings;

        if ($request->post()) {
            if ($request->post('action') === 'global-settings') {
                $settings->set('subscription.environment', strip_tags($request->post('subscription_environment', $settings->get('subscription.environment'))));
                $settings->set('subscription.paypalLiveWebhookId', strip_tags($request->post('subscription_paypalLiveWebhookId', $settings->get('subscription.paypalLiveWebhookId'))));
                $settings->set('subscription.paypalSandboxWebhookId', strip_tags($request->post('subscription_paypalSandboxWebhookId', $settings->get('subscription.paypalSandboxWebhookId'))));

                // Show success alert
                Yii::$app->getSession()->setFlash(
                    'success',
                    Yii::t('app', 'Global Settings have been successfully updated.')
                );
            } elseif ($request->post('action') === 'default-user-limits') {
                $settings->set('subscription.formLimit', strip_tags($request->post('subscription_formLimit', $settings->get('subscription.formLimit'))));
                $settings->set('subscription.submissionLimit', strip_tags($request->post('subscription_submissionLimit', $settings->get('subscription.submissionLimit'))));
                $settings->set('subscription.trialDays', strip_tags($request->post('subscription_trialDays', $settings->get('subscription.trialDays'))));

                // Show success alert
                Yii::$app->getSession()->setFlash(
                    'success',
                    Yii::t('app', 'Default User Limits have been successfully updated.')
                );
            } elseif ($request->post('action') === 'payment-gateways') {
                $settings->set('subscription.paypalLiveClientID', strip_tags($request->post('subscription_paypalLiveClientID', $settings->get('subscription.paypalLiveClientID'))));
                $settings->set('subscription.paypalLiveClientSecret', strip_tags($request->post('subscription_paypalLiveClientSecret', $settings->get('subscription.paypalLiveClientSecret'))));
                $settings->set('subscription.paypalSandboxClientID', strip_tags($request->post('subscription_paypalSandboxClientID', $settings->get('subscription.paypalSandboxClientID'))));
                $settings->set('subscription.paypalSandboxClientSecret', strip_tags($request->post('subscription_paypalSandboxClientSecret', $settings->get('subscription.paypalSandboxClientSecret'))));
                $settings->set('subscription.stripeLivePublishableKey', strip_tags($request->post('subscription_stripeLivePublishableKey', $settings->get('subscription.stripeLivePublishableKey'))));
                $settings->set('subscription.stripeLiveSecretKey', strip_tags($request->post('subscription_stripeLiveSecretKey', $settings->get('subscription.stripeLiveSecretKey'))));
                $settings->set('subscription.stripeSandboxPublishableKey', strip_tags($request->post('subscription_stripeSandboxPublishableKey', $settings->get('subscription.stripeSandboxPublishableKey'))));
                $settings->set('subscription.stripeSandboxSecretKey', strip_tags($request->post('subscription_stripeSandboxSecretKey', $settings->get('subscription.stripeSandboxSecretKey'))));

                // Show success alert
                Yii::$app->getSession()->setFlash(
                    'success',
                    Yii::t('app', 'Payment Gateways have been successfully updated.')
                );
            } elseif ($request->post('action') === 'billing-information') {
                $settings->set('subscription.firstName', strip_tags($request->post('subscription_firstName', $settings->get('subscription.firstName'))));
                $settings->set('subscription.lastName', strip_tags($request->post('subscription_lastName', $settings->get('subscription.lastName'))));
                $settings->set('subscription.email', strip_tags($request->post('subscription_email', $settings->get('subscription.email'))));
                $settings->set('subscription.phone', strip_tags($request->post('subscription_phone', $settings->get('subscription.phone'))));
                $settings->set('subscription.organization', strip_tags($request->post('subscription_organization', $settings->get('subscription.organization'))));
                $settings->set('subscription.address', strip_tags($request->post('subscription_address', $settings->get('subscription.address'))));
                $settings->set('subscription.addressLine2', strip_tags($request->post('subscription_addressLine2', $settings->get('subscription.addressLine2'))));
                $settings->set('subscription.country', strip_tags($request->post('subscription_country', $settings->get('subscription.country'))));
                $settings->set('subscription.city', strip_tags($request->post('subscription_city', $settings->get('subscription.city'))));
                $settings->set('subscription.zip', strip_tags($request->post('subscription_zip', $settings->get('subscription.zip'))));
                $settings->set('subscription.state', strip_tags($request->post('subscription_state', $settings->get('subscription.state'))));
                $settings->set('subscription.taxId', strip_tags($request->post('subscription_taxId', $settings->get('subscription.taxId'))));

                // Show success alert
                Yii::$app->getSession()->setFlash(
                    'success',
                    Yii::t('app', 'Company Information have been successfully updated.')
                );
            }
        }

        return $this->render('settings');
    }

    /**
     * Finds the SubscriptionProduct model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return SubscriptionProduct the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = SubscriptionProduct::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }
}
