<?php
namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\web\UploadedFile;
use app\models\User;
use app\models\Appointment;

class ProfileController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'], // Только авторизованные
                        'matchCallback' => function ($rule, $action) {
                            // Только клиенты (is_admin = 0)
                            return Yii::$app->user->identity->is_admin == 0;
                        }
                    ],
                ],
            ],
        ];
    }

    /**
     * Главная страница профиля
     */
    public function actionIndex()
    {
        $user = Yii::$app->user->identity;

        // Получаем историю заявок клиента
        $appointments = Appointment::find()
            ->where(['client_id' => $user->id])
            ->with(['masterInfo.user', 'service'])
            ->orderBy(['start_time' => SORT_DESC])
            ->all();

        // Статистика
        $stats = [
            'total' => count($appointments),
            'pending' => Appointment::find()->where(['client_id' => $user->id, 'status' => 0])->count(),
            'confirmed' => Appointment::find()->where(['client_id' => $user->id, 'status' => 1])->count(),
            'completed' => Appointment::find()->where(['client_id' => $user->id, 'status' => 2])->count(),
            'cancelled' => Appointment::find()->where(['client_id' => $user->id, 'status' => 3])->count(),
        ];

        // Ближайшая запись
        $nextAppointment = Appointment::find()
            ->where(['client_id' => $user->id])
            ->andWhere(['>=', 'start_time', date('Y-m-d H:i:s')])
            ->andWhere(['status' => [0, 1]])
            ->orderBy(['start_time' => SORT_ASC])
            ->one();

        return $this->render('index', [
            'user' => $user,
            'appointments' => $appointments,
            'stats' => $stats,
            'nextAppointment' => $nextAppointment,
        ]);
    }

    /**
     * Редактирование профиля
     */
    public function actionEdit()
    {
        $user = Yii::$app->user->identity;

        if ($user->load(Yii::$app->request->post())) {
            // Если меняется пароль
            $newPassword = Yii::$app->request->post('new_password');
            if ($newPassword) {
                $user->password = Yii::$app->security->generatePasswordHash($newPassword);
            }

            if ($user->save()) {
                Yii::$app->session->setFlash('success', 'Профиль успешно обновлен');
                return $this->redirect(['index']);
            } else {
                Yii::$app->session->setFlash('error', 'Ошибка при сохранении');
            }
        }

        return $this->render('edit', [
            'user' => $user,
        ]);
    }

    /**
     * История заявок
     */
    public function actionHistory()
    {
        $user = Yii::$app->user->identity;

        $appointments = Appointment::find()
            ->where(['client_id' => $user->id])
            ->with(['masterInfo.user', 'service'])
            ->orderBy(['start_time' => SORT_DESC])
            ->all();

        return $this->render('history', [
            'user' => $user,
            'appointments' => $appointments,
        ]);
    }

    /**
     * Детали заявки
     */
    public function actionViewAppointment($id)
    {
        $user = Yii::$app->user->identity;

        $appointment = Appointment::find()
            ->where(['id' => $id, 'client_id' => $user->id])
            ->with(['masterInfo.user', 'service'])
            ->one();

        if (!$appointment) {
            throw new \yii\web\NotFoundHttpException('Запись не найдена');
        }

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

    /**
     * Отмена заявки клиентом
     */
    public function actionCancelAppointment()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $id = Yii::$app->request->post('id');
        $user = Yii::$app->user->identity;

        $appointment = Appointment::find()
            ->where(['id' => $id, 'client_id' => $user->id])
            ->one();

        if (!$appointment) {
            return ['success' => false, 'message' => 'Запись не найдена'];
        }

        if (!in_array($appointment->status, [0, 1])) {
            return ['success' => false, 'message' => 'Эту запись нельзя отменить'];
        }

        $appointment->status = 2;
        if ($appointment->save()) {
            return ['success' => true, 'message' => 'Запись отменена'];
        }

        return ['success' => false, 'message' => 'Ошибка при отмене'];
    }
}