<?php /** @noinspection PhpUnused */

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

namespace rest\controllers;


use common\models\Customer;
use common\models\Fingerprint;
use common\models\Ticket;
use Yii;
use yii\web\BadRequestHttpException;
use yii\web\HttpException;

class FingerprintController extends RestController
{

    /**
     * @param $idCustomer
     * @param $fingerPrint
     * @throws HttpException
     */
    public function actionAdd($idCustomer,$fingerPrint)
    {
        $customer = Customer::findOne($idCustomer);

        if ( null === $customer) {
            throw new HttpException(404, 'Not Found');
        }

        $fingerPrintModel = new Fingerprint();
        $fingerPrintModel->id_customer = $customer->id_customer;
        $fingerPrintModel->fingerprint = $fingerPrint;
        $fingerPrintModel->save(false);
    }

    /**
     * @param string the sha string of the fingerprint $fingerPrint
     * @return array    the response
     * @throws HttpException    on any error
     */
    public function actionEnter($fingerPrint)
    {

        if ( !Yii::$app->request->isPost){
            throw new BadRequestHttpException();
        }

        /** @var Fingerprint $fingerPrint */
        $fingerPrint = Fingerprint::find()->andWhere(['fingerPrint' => $fingerPrint])->one();

        if ( null === $fingerPrint) {
            throw new HttpException(404, 'Not Found');
        }

        $customer = Customer::findOne($fingerPrint->id_customer);


        if ( null === $customer) {
            throw new HttpException(404, 'Not Found');
        }

        $card = $customer->card;

        $tickets = Ticket::readActive($card);

        $id_ticket = null;
        if ( isset($tickets) && count($tickets) > 0){
            $ticket = $tickets[0];
            $id_ticket = $ticket->id_ticket;
        }

        return
        [
            'id_card' =>  $card->id_card,
            'id_ticket' => $id_ticket,
            'id_customer' => $customer->id_customer
        ];

    }

}
