<?php
namespace app\modules\admin\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\web\NotFoundHttpException;
use app\models\MasterInfo;
use app\models\Service;
use app\models\MasterService;
use app\models\User;

class MasterServiceController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                        'matchCallback' => function ($rule, $action) {
                            return Yii::$app->user->identity->is_admin == 2;
                        }
                    ],
                ],
            ],
        ];
    }

    /**
     * Список всех мастеров с их услугами
     */
    public function actionIndex()
    {
        $masters = User::find()
            ->where(['is_admin' => 1])
            ->all();

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

    /**
     * Управление услугами конкретного мастера
     */
    public function actionManage($id)
    {
        $master = User::findOne($id);
        if (!$master || $master->is_admin != 1) {
            throw new NotFoundHttpException('Мастер не найден');
        }

        $masterInfo = MasterInfo::find()->where(['user_id' => $master->id])->one();
        if (!$masterInfo) {
            $masterInfo = new MasterInfo();
            $masterInfo->user_id = $master->id;
            $masterInfo->is_active = 1;
            $masterInfo->save();
        }

        // Все услуги
        $allServices = Service::find()->all();

        // Услуги, которые уже привязаны к мастеру
        $masterServices = MasterService::find()
            ->where(['master_info_id' => $masterInfo->id])
            ->indexBy('service_id')
            ->all();

        if (Yii::$app->request->isPost) {
            $services = Yii::$app->request->post('services', []);

            // Удаляем старые связи
            MasterService::deleteAll(['master_info_id' => $masterInfo->id]);

            // Добавляем новые
            $savedCount = 0;
            foreach ($services as $serviceId => $data) {
                if (isset($data['selected']) && $data['selected']) {
                    $ms = new MasterService();
                    $ms->master_info_id = $masterInfo->id;
                    $ms->service_id = $serviceId;
                    $ms->price_modifier = !empty($data['price_modifier']) ? $data['price_modifier'] : 0;

                    if ($ms->save()) {
                        $savedCount++;
                    }
                }
            }

            Yii::$app->session->setFlash('success', "Сохранено услуг: $savedCount");
            return $this->redirect(['manage', 'id' => $master->id]);
        }

        return $this->render('manage', [
            'master' => $master,
            'masterInfo' => $masterInfo,
            'allServices' => $allServices,
            'masterServices' => $masterServices,
        ]);
    }

    /**
     * Пакетная привязка (выбор услуг для всех мастеров)
     */
    public function actionBatch()
    {
        $masters = User::find()->where(['is_admin' => 1])->all();
        $services = Service::find()->all();

        if (Yii::$app->request->isPost) {
            $batchData = Yii::$app->request->post('batch', []);

            $savedCount = 0;
            foreach ($batchData as $masterId => $serviceIds) {
                $masterInfo = MasterInfo::find()->where(['user_id' => $masterId])->one();
                if (!$masterInfo) continue;

                // Удаляем старые
                MasterService::deleteAll(['master_info_id' => $masterInfo->id]);

                // Добавляем новые
                foreach ($serviceIds as $serviceId) {
                    $ms = new MasterService();
                    $ms->master_info_id = $masterInfo->id;
                    $ms->service_id = $serviceId;
                    $ms->price_modifier = 0;
                    if ($ms->save()) {
                        $savedCount++;
                    }
                }
            }

            Yii::$app->session->setFlash('success', "Сохранено $savedCount связей");
            return $this->redirect(['batch']);
        }

        return $this->render('batch', [
            'masters' => $masters,
            'services' => $services,
        ]);
    }
}