<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\UploadedFile;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use app\models\Tenant;
use app\models\TenantBanner;
use app\models\ColourScheme;

class TenantController extends Controller
{
    public $layout = 'main';

    public function behaviors(): array
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [[
                    'allow' => true,
                    'roles' => ['@'],
                ]],
            ],
            'verbs' => [
                'class'   => VerbFilter::class,
                'actions' => [
                    'delete'        => ['post'],
                    'toggle'        => ['post'],
                    'add-banner'    => ['post'],
                    'delete-banner' => ['post'],
                    'add-colour'    => ['post'],
                    'delete-colour' => ['post'],
                    'update-colour' => ['post'],
                ],
            ],
        ];
    }

    // ================================================================
    // INDEX
    // ================================================================
    public function actionIndex(): string
    {
        $filter  = Yii::$app->request->get('status', '');
        $query   = Tenant::find()->orderBy(['tenant_name' => SORT_ASC]);

        if ($filter === 'Y' || $filter === 'N') {
            $query->where(['isActive' => $filter]);
        }

        $tenants = $query->all();

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

    // ================================================================
    // VIEW — read-only info page
    // ================================================================
    public function actionView(int $id): string
    {
        $tenant = $this->findModel($id);

        return $this->render('view', [
            'tenant' => $tenant,
        ]);
    }

    // ================================================================
    // CREATE
    // ================================================================
    public function actionCreate()
    {
        $model           = new Tenant();
        $model->isActive = 'Y';

        if ($model->load(Yii::$app->request->post())) {
            $model->logoFile = UploadedFile::getInstance($model, 'logoFile');

            if ($model->validate()) {
                $userId = Yii::$app->user->id;
                $model->created_by         = $userId;
                $model->updated_by         = $userId;
                $model->created_date_time  = date('Y-m-d H:i:s');
                $model->updated_date_time  = date('Y-m-d H:i:s');
                $model->tenant_logo        = '';
                $model->tenant_logo_name   = '';

                if ($model->save(false)) {
                    if ($model->logoFile && !$model->uploadLogo()) {
                        return $this->render('create', ['model' => $model]);
                    }
                    if ($model->logoFile) {
                        $model->save(false);
                    }
                    Yii::$app->session->setFlash('success', "Tenant '{$model->tenant_name}' created.");
                    return $this->redirect(['tenant/update', 'id' => $model->id]);
                }
            }
        }

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

    // ================================================================
    // UPDATE — tabbed edit page
    // ================================================================
    public function actionUpdate(int $id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            $model->logoFile = UploadedFile::getInstance($model, 'logoFile');

            if ($model->validate()) {
                $model->updated_by        = Yii::$app->user->id;
                $model->updated_date_time = date('Y-m-d H:i:s');

                if ($model->logoFile && !$model->uploadLogo()) {
                    return $this->renderUpdate($model, 'details');
                }

                if ($model->save(false)) {
                    Yii::$app->session->setFlash('success', "Tenant '{$model->tenant_name}' updated.");
                    return $this->redirect(['tenant/update', 'id' => $model->id, 'tab' => 'details']);
                }
            }
        }

        return $this->renderUpdate($model, Yii::$app->request->get('tab', 'details'));
    }

    /** Shared render helper for update action */
    private function renderUpdate(Tenant $model, string $activeTab): string
    {
        $id = $model->id;

        $banners = TenantBanner::find()
            ->where(['tenant_id' => $id])
            ->orderBy(['id' => SORT_ASC])
            ->all();

        $colours = ColourScheme::find()
            ->where(['type' => 'TE'])
            ->orderBy(['item' => SORT_ASC])
            ->all();

        $courses = Yii::$app->db->createCommand(
            'SELECT id, course_name, leads_by, start_date, end_date, isActive
               FROM {{%course}}
              WHERE tenant_id = :tid
              ORDER BY course_name ASC',
            [':tid' => $id]
        )->queryAll();

        $newBanner            = new TenantBanner();
        $newBanner->tenant_id = $id;

        $newColour            = new ColourScheme();
        $newColour->type      = 'TE';
        $newColour->colour    = '#3498db';

        return $this->render('update', [
            'model'     => $model,
            'banners'   => $banners,
            'colours'   => $colours,
            'courses'   => $courses,
            'newBanner' => $newBanner,
            'newColour' => $newColour,
            'activeTab' => $activeTab,
        ]);
    }

    // ================================================================
    // DELETE
    // ================================================================
    public function actionDelete(int $id)
    {
        $model = $this->findModel($id);
        $name  = $model->tenant_name;

        if ($model->tenant_logo) {
            $path = Yii::getAlias(Tenant::UPLOAD_PATH) . $model->tenant_logo;
            if (is_file($path)) {
                @unlink($path);
            }
        }

        $model->delete();
        Yii::$app->session->setFlash('success', "Tenant '{$name}' deleted.");
        return $this->redirect(['tenant/index']);
    }

    // ================================================================
    // TOGGLE STATUS
    // ================================================================
    public function actionToggle(int $id)
    {
        $model           = $this->findModel($id);
        $model->isActive = $model->isActive === 'Y' ? 'N' : 'Y';
        $model->updated_by        = Yii::$app->user->id;
        $model->updated_date_time = date('Y-m-d H:i:s');
        $model->save(false);

        $state = $model->isActive === 'Y' ? 'activated' : 'deactivated';
        Yii::$app->session->setFlash('success', "Tenant '{$model->tenant_name}' {$state}.");
        return $this->redirect(['tenant/index']);
    }

    // ================================================================
    // ADD BANNER
    // ================================================================
    public function actionAddBanner(int $tenantId)
    {
        $this->findModel($tenantId);

        $banner            = new TenantBanner();
        $banner->tenant_id = $tenantId;
        $banner->isActive  = 'Y';

        if ($banner->load(Yii::$app->request->post())) {
            $banner->bannerFile = UploadedFile::getInstance($banner, 'bannerFile');

            if ($banner->validate()) {
                $banner->tenant_banner_image = '';

                if ($banner->save(false)) {
                    if ($banner->bannerFile) {
                        $banner->uploadBanner();
                        $banner->save(false);
                    }
                    Yii::$app->session->setFlash('success', 'Banner added.');
                }
            } else {
                Yii::$app->session->setFlash('error', implode(' ', array_merge(...array_values($banner->errors))));
            }
        }

        return $this->redirect(['tenant/update', 'id' => $tenantId, 'tab' => 'banners']);
    }

    // ================================================================
    // DELETE BANNER
    // ================================================================
    public function actionDeleteBanner(int $id)
    {
        $banner = TenantBanner::findOne($id);
        if ($banner) {
            $tenantId = $banner->tenant_id;
            if ($banner->tenant_banner_image) {
                $path = Yii::getAlias(TenantBanner::UPLOAD_PATH) . $banner->tenant_banner_image;
                if (is_file($path)) {
                    @unlink($path);
                }
            }
            $banner->delete();
            Yii::$app->session->setFlash('success', 'Banner deleted.');
            return $this->redirect(['tenant/update', 'id' => $tenantId, 'tab' => 'banners']);
        }
        return $this->redirect(['tenant/index']);
    }

    // ================================================================
    // ADD COLOUR (TE)
    // ================================================================
    public function actionAddColour(int $tenantId)
    {
        $this->findModel($tenantId);

        $colour            = new ColourScheme();
        $colour->type      = 'TE';
        $colour->tenant_id = $tenantId;

        if ($colour->load(Yii::$app->request->post())) {
            $colour->type      = 'TE';
            $colour->tenant_id = $tenantId;

            if ($colour->validate()) {
                $userId = Yii::$app->user->id;
                $colour->created_by = $userId;
                $colour->updated_by = $userId;
                $colour->created_at = date('Y-m-d H:i:s');
                $colour->updated_at = date('Y-m-d H:i:s');

                if ($colour->save(false)) {
                    Yii::$app->session->setFlash('success', "Colour '{$colour->item}' added.");
                }
            } else {
                Yii::$app->session->setFlash('error', implode(' ', array_merge(...array_values($colour->errors))));
            }
        }

        return $this->redirect(['tenant/update', 'id' => $tenantId, 'tab' => 'colours']);
    }

    // ================================================================
    // UPDATE COLOUR
    // ================================================================
    public function actionUpdateColour(int $id)
    {
        $colour = ColourScheme::findOne(['id' => $id, 'type' => 'TE']);
        if (!$colour || !$colour->tenant_id) {
            throw new NotFoundHttpException('Colour entry not found.');
        }
        $tenantId = $colour->tenant_id;

        if ($colour->load(Yii::$app->request->post())) {
            $colour->type       = 'TE';
            $colour->tenant_id  = $tenantId;
            $colour->updated_by = Yii::$app->user->id;
            $colour->updated_at = date('Y-m-d H:i:s');
            $colour->save();
        }

        return $this->redirect(['tenant/update', 'id' => $tenantId, 'tab' => 'colours']);
    }

    // ================================================================
    // DELETE COLOUR
    // ================================================================
    public function actionDeleteColour(int $id)
    {
        $colour = ColourScheme::findOne(['id' => $id, 'type' => 'TE']);
        if ($colour && $colour->tenant_id) {
            $tenantId = $colour->tenant_id;
            $colour->delete();
            Yii::$app->session->setFlash('success', 'Colour deleted.');
            return $this->redirect(['tenant/update', 'id' => $tenantId, 'tab' => 'colours']);
        }
        return $this->redirect(['tenant/index']);
    }

    // ================================================================
    // Helper
    // ================================================================
    protected function findModel(int $id): Tenant
    {
        $model = Tenant::findOne($id);
        if ($model === null) {
            throw new NotFoundHttpException('Tenant not found.');
        }
        return $model;
    }
}
