<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use app\models\Courier;
use app\models\Delivery;
use app\models\Order;

class CourierController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * Получение текущего курьера пользователя
     */
    private function getCourier()
    {
        return Courier::find()
            ->where(['user_id' => Yii::$app->user->id])
            ->andWhere(['in', 'status', [Courier::STATUS_FREE, Courier::STATUS_BUSY]])
            ->one();
    }

    /**
     * Список всех доставок курьера
     */
    public function actionIndex()
    {
        $courier = $this->getCourier();
        if (!$courier) {
            return $this->redirect(['/site/courier']);
        }

        $deliveries = Delivery::find()
            ->where(['courier_id' => $courier->id])
            ->andWhere(['!=', 'status', Delivery::STATUS_DELIVERED])
            ->with(['order.restaurant'])
            ->orderBy(['updated_at' => SORT_DESC])
            ->all();

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

    /**
     * Просмотр конкретной доставки
     */
    public function actionView($id)
    {
        $courier = $this->getCourier();
        if (!$courier) {
            return $this->redirect(['/site/courier']);
        }

        $delivery = Delivery::find()
            ->where(['id' => $id, 'courier_id' => $courier->id])
            ->with(['order.restaurant'])
            ->one();

        if (!$delivery) {
            throw new \yii\web\NotFoundHttpException('Доставка не найдена');
        }

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

    /**
     * Обновление статуса доставки
     */
    public function actionUpdateStatus($id, $status)
    {
        $delivery = Delivery::findOne($id);
        if (!$delivery) {
            return $this->redirect(['index']);
        }

        $order = $delivery->order;
        $courier = $this->getCourier();

        switch ($status) {
            case 'picked_up':
                // Используем существующую константу STATUS_ON_THE_WAY
                $delivery->status = Delivery::STATUS_ON_THE_WAY;
                $delivery->updated_at = time();
                $delivery->save(false);

                if ($courier) {
                    $courier->status = Courier::STATUS_BUSY;
                    $courier->save(false);
                }
                break;

            case 'delivered':
                $delivery->status = Delivery::STATUS_DELIVERED;
                $delivery->updated_at = time();
                $delivery->save(false);

                $order->status = Order::STATUS_COMPLETED; // проверь, что константа есть в модели Order
                $order->save(false);

                if ($courier) {
                    $courier->status = Courier::STATUS_FREE;
                    $courier->save(false);
                }
                break;
        }

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

    /**
     * Список доступных доставок
     */
    public function actionAvailable()
    {
        $courier = $this->getCourier();
        if (!$courier) {
            return $this->redirect(['/site/courier']);
        }

        $deliveries = Delivery::find()
            ->where([
                'courier_id' => null,
                'delivery_type' => Delivery::TYPE_DELIVERY,
            ])
            ->andWhere(['in', 'status', [
                Delivery::STATUS_PENDING,
                Delivery::STATUS_ASSIGNED,
            ]])
            ->with(['order.restaurant'])
            ->all();

        return $this->render('available', [
            'deliveries' => $deliveries,
        ]);
    }

    /**
     * Взять заказ в работу
     */
    public function actionTake($id)
    {
        $courier = $this->getCourier();
        if (!$courier) {
            return $this->redirect(['/site/courier']);
        }

        $delivery = Delivery::findOne($id);
        if (!$delivery || $delivery->courier_id) {
            return $this->redirect(['available']);
        }

        $delivery->courier_id = $courier->id;
        $delivery->status = Delivery::STATUS_ON_THE_WAY;
        $delivery->updated_at = time();
        $delivery->save(false);

        $courier->status = Courier::STATUS_BUSY;
        $courier->save(false);

        // Обновляем статус заказа
        $order = $delivery->order;
        $order->status = Order::STATUS_PICKED_UP;
        $order->save(false);

        // Отправляем email клиенту
        Yii::$app->mailer->compose('orderPickedUp', ['order' => $order])
            ->setTo($order->user->email)
            ->setSubject('Ваш заказ забран курьером')
            ->send();

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

    /**
     * Активные доставки курьера
     */
    public function actionActive()
    {
        $courier = $this->getCourier();
        if (!$courier) {
            return $this->redirect(['/site/courier']);
        }

        $deliveries = Delivery::find()
            ->where(['courier_id' => $courier->id, 'status' => Delivery::STATUS_ON_THE_WAY]) // исправлено
            ->with(['order.restaurant'])
            ->all();

        return $this->render('active', [
            'deliveries' => $deliveries,
        ]);
    }

    /**
     * Завершение доставки
     */
    public function actionComplete($id)
    {
        $courier = $this->getCourier();
        if (!$courier) {
            return $this->redirect(['/site/courier']);
        }

        $delivery = Delivery::findOne([
            'id' => $id,
            'courier_id' => $courier->id,
        ]);

        if ($delivery) {
            $delivery->status = Delivery::STATUS_DELIVERED;
            $delivery->updated_at = time();
            $delivery->save(false);

            $order = $delivery->order;
            $order->status = Order::STATUS_COMPLETED;
            $order->save(false);

            $courier->status = Courier::STATUS_FREE;
            $courier->save(false);

            // Отправка email клиенту
            Yii::$app->mailer->compose('orderCompleted', ['order' => $order])
                ->setTo($order->user->email)
                ->setSubject('Ваш заказ доставлен')
                ->send();
        }

        return $this->redirect(['active']);
    }
    public function sendOrderCompletedEmail(Order $order)
    {
        if (!$order || !$order->user || !$order->user->email) {
            return false;
        }

        try {
            return Yii::$app->mailer->compose('orderCompleted', [
                'order' => $order,  // передаем заказ в шаблон письма
            ])
                ->setFrom(['nikitapaharkov2@gmail.com' => 'FoodExpress']) // ОБЯЗАТЕЛЬНО указываем отправителя
                ->setTo($order->user->email)
                ->setSubject('Ваш заказ #' . $order->id . ' доставлен')
                ->send();
        } catch (\Throwable $e) {
            Yii::error('Ошибка при отправке email о завершении заказа: ' . $e->getMessage());
            return false;
        }
    }
    public function actionStatus($id)
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $order = Order::findOne($id);
        if (!$order) {
            return ['success' => false];
        }

        // Генерация HTML блока статусов (можно использовать renderPartial)
        $trackingStatuses = $order->getTrackingStatuses(); // Ваш метод, который формирует массив статусов
        $html = $this->renderPartial('_trackingStatuses', [
            'trackingStatuses' => $trackingStatuses
        ]);

        return [
            'success' => true,
            'html' => $html
        ];
    }
}
