<?php
/**
 * Created by IntelliJ IDEA.
 * User: rocho
 * Date: 2018.08.29.
 * Time: 21:58
 */

namespace rest\controllers;


use common\components\Helper;
use common\models\Card;
use common\models\Ticket;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;

class CustomerController extends RestController
{

    /**
     * @param $number
     * @param int $lastXDays default 0. Search for valid tickets also in the last x days.
     * @return array
     * @throws \Exception
     */
    public function actionDiscountStatus($number, $lastXDays = null)
    {
        $number = Helper::fixAsciiChars($number);
        $query = Card::find();
        $query->andWhere(['or',
            ['and', ['in', 'card.number', [$number]], "trim(coalesce(card.number, '')) <>'' "],
            ['and', ['in', 'card.rfid_key', [$number]], "trim(coalesce(card.rfid_key, '')) <>'' "],

        ]);
        /** @var \common\models\Card $card */
        $card = $query->one();
        if (!isset($card)) {
            throw new NotFoundHttpException("Kártya nem található");
        }
        $customer = $card->customer;
        if (!isset($customer)) {
            throw new NotFoundHttpException("Vendég nem található");
        }
        if (isset($lastXDays)) {
            if (!is_numeric($lastXDays)) {
                throw new BadRequestHttpException("lastXDays paraméter hibás");
            }
            if ($lastXDays > 6 || $lastXDays < 1) {
                throw new BadRequestHttpException("lastXDays paraméter érték hibás");
            }
        }
        // check if has valid ticket today
        /** @var \common\models\Card $card */
        $tickets = Ticket::readActive($card);
        $hasValidTicket = count($tickets) > 0;
        if (isset($lastXDays)) {
            // try to find any valid ticket in the lastXDays
            $minusDay = 1;
            while (!$hasValidTicket && $minusDay <= $lastXDays) {
                /** @var integer $minusDay */
                $day = $this->getDateMinusDays($minusDay);
                $tickets = Ticket::readActive($card, $day);
                $hasValidTicket = count($tickets) > 0;
                $minusDay = $minusDay + 1;
            }
        }
        $result = [
            'discount' => $hasValidTicket
        ];
        if (isset($customer)) {
            $result['card_number'] = $card->number;
            $result['name'] = $customer->name;
            $result['provider'] = \Yii::$app->id;
        }
        return $result;
    }

    /**
     * @param $minusDays
     * @return \DateTime
     * @throws \Exception
     */
    private function getDateMinusDays($minusDays)
    {
        $date = new \DateTime('now');
        $date->sub(new \DateInterval('P' . $minusDays . 'D'));
        $date->setTime(0, 0, 0);
        return $date;
    }

}