<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UssdQuestion extends Model
{


    /**
     * Service Questions constants
     * NB: These ids are the same values stored in the database for column 'is_multiple_choice' 1 for true, 0 for false (open ended).
     */
    const  MULTIPLE_CHOICE = 1;
    const  NO_RESPONSE = 2;
    const  OPEN_ENDED = 0;

    /**
     * @var array
     */
    protected $fillable = [
        'ussd_service_id',
        'is_multiple_choice',
        'question',
        'question_number',
        'sms_message', //if the question is not multiple choice, and the ussd service requires payment, store amount
        'amount', //and sms message on this table. if the question has multiple choice and requires payment, store the
        //amount and message on the answers table
    ];

    /**
     * @var array
     */
    protected $casts = [
        'is_multiple_choice' => 'boolean'
    ];

    /**
     * A service question is related to the Ussd Service
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function ussd_service() {
        return $this->belongsTo(UssdService::class);
    }

    /**
     * A question has many answers if it is a multiple choice question
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function ussd_answer() {
        return $this->hasMany(UssdAnswer::class);
    }

    /**
     * A ussd question will have many responses from the users ofthe service
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function ussd_responses() {
        return $this->hasMany(UssdResponse::class, 'question_id');
    }

    /**
     * Determines whether a question is multiple choice
     * @return mixed
     */
    public function isMultipleChoice() {
        return $this->is_multiple_choice;
    }

    /*
     * Returns the question type.
     * @return String
     */
    public function getQuestionType() {
        return $this->isMultipleChoice() ? "Multiple Choice" : "Open Ended";
    }

    /**
     * Returns the question with the numbering pre-pended ie 1. When was Npontu established?
     * @return string
     */
    public function getQuestionWithNumber() {
        return $this->question_number . ". " . $this->question;
    }

    /**
     * Generate new answer's number
     * @param $id
     * @return int
     */
    static public function getNewAnswerNumber($id) {
        //automatically assign numbering to answer
        //get the count of answers in the database for the specific ussd service question
        $count = self::find($id)->ussd_answer()->count();

        //increment count as it will be assigned as the new answer's number
        $count++;

        return $count;
    }
}
