<template>
    <form @submit.prevent="sentSms()">
        <div class="card form">
            <div class="card-header">
                <div class="row">
                    <div class="col-md-8">
                        <h2>Quick SMS</h2>
                    </div>
                    <div class="col-md-4 d-flex flex-row-reverse hstack gap-3 fs-15">
                        <router-link to="/admin/quick_sms" class="btn btn-primary">
                            <i class="fa-solid fa-arrow-left"></i> SMS List Page
                        </router-link>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="row mb-2">
                    <div class="col-md-2">
                        <span><label>SMS Type :</label></span>
                    </div>
                    <div class="col-md-8">
                        <div class="input-group hstack gap-3 fs-15">
                            <select @change="setMaskingName()" v-model="formObject.sender_id_type" v-validate="'required'" name="sender_id_type" class="form-control">
                                <option value="">Select</option>
                                <template v-for="(type, index) in requiredData.sender_types">
                                    <option :value="type.value">{{type.name}}</option>
                                </template>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-md-2">
                        <label>SMS content and Schedule :</label>
                    </div>
                    <div class="col-md-4">
                        <select v-validate="'required'" class="form-control" v-model="formObject.schedule">
                            <option value="0">Send Now</option>
                            <option value="1">Send Later</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <select v-validate="'required'" @change="setCharactersLimit()" class="form-control" v-model="formObject.content_type">
                            <template v-for="(data, index) in contentType">
                                <option :value="data.value">{{ data.name }}</option>
                            </template>
                        </select>
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-md-2">
                        <span><label>Recipients Number :</label></span>
                    </div>
                    <div class="col-md-8">
                        <textarea v-validate="'required'" name="phone" v-model="formObject.phone" class="form-control" placeholder="Type or Copy past your number" rows="2"></textarea>
                    </div>

                </div>
                <div class="row mb-2">
                    <div class="col-md-2">
                        <span><label>Select From Draft Messages (optional) :</label></span>
                    </div>
                    <div class="col-md-8">
                        <div class="row">
                            <div class="col-10">
                                <div class="input-group hstack gap-3 fs-15">
                                    <select class="form-control" v-model="selectedDraftId">
                                        <option value="">Select draft</option>
                                        <template v-for="(data, index) in getData">
                                            <option :value="data.id">{{ data.body }}</option>
                                        </template>
                                    </select>
                                </div>
                            </div>
                            <div class="col-2">
                                <a @click="deleteDraft(selectedDraftId)" class="btn btn-outline-danger"><i class="fa fa-trash"></i></a>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-md-2"><label>Masking Name :</label></div>
                    <div class="col-md-8">
                        <div class="input-group hstack gap-3 fs-15">
                            <select v-model="formObject.masking_name" name="sender_id_type" class="form-control">
                                <option value="">Select</option>
                                <template v-for="(masking, index) in requiredData.maskings">
                                    <option :value="masking.key">{{masking.name}}</option>
                                </template>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-md-2">
                        <span><label>Message :</label></span>
                    </div>
                    <div class="col-md-5">
                        <div>
                            <textarea class="form-control" placeholder="Type or Copy past your Message" rows="7" v-model="formObject.body" v-validate="`required|max:${totalLimit}`" name="body" :maxlength="totalLimit"></textarea>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <character-limit-count :character-max="maxCharacters" :limit-total="totalLimit" :sms-body="formObject.body"></character-limit-count>
                    </div>
                </div>
                <div class="row mb-2" v-if="parseInt(formObject.schedule) === 1">
                    <div class="col-md-2">
                        <label>Schedule Date & Time :</label>
                    </div>
                    <div class="col-9 row">
                        <div class="col-md-2">
                            <datepicker input_class="form-control" v-model="formObject.date" name="date"></datepicker>
                        </div>
                        <div class="col-md-2">
                            <input type="time" name="time" class="form-control" v-model="formObject.time">
                        </div>
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-md-2">
                    </div>
                    <div class="col-md-8">
                        <a type="draft" @click="draftMessage()" class="btn btn-success "><i class="fa fa-pencil"></i>Save Draft</a>
                        <button type="submit" name="submit" class="btn btn-primary "><i class="fa fa-paper-plane"></i>Send SMS</button>
                    </div>
                </div>
                </div>
        </div>
        <invalid-numbers-model :invalid-numbers="invalidNumbers"></invalid-numbers-model>
    </form>
</template>
<script>
    import formModal from "../../../components/formModal";
    import SenderRequestForm from "../../settings/senders/SenderRequestForm";
    import axios from 'axios'
    import InvalidNumbersModel from "../../../components/invalidNumbersModel";
    import CharacterLimitCount from "../characterLimitCount";

    export default {
        name: "quick_sms_add",
        components: {CharacterLimitCount, InvalidNumbersModel, formModal, SenderRequestForm},
        data() {
            return {
                selectedDraftId: '',
                invalidNumbers: {},
            }
        },
        watch: {
            selectedDraftId(newValue) {
                const selectedDraft = this.getData.find(data => data.id === newValue);
                if (selectedDraft) {
                    this.formObject.body = selectedDraft.body;
                } else {
                    this.formObject.body = '';
                }
            },
        },
        methods: {
            sentSms : function(){
                const _this = this;
                _this.submitForm(_this.formObject, false, function(retData) {
                    if (parseInt(retData.status) === 3000){
                        _this.invalidNumbers = retData.result;
                        _this.openModal("invalidNumberModal");
                    }
                }, true, false, {}, '/admin/quick_sms');
            },
            draftMessage() {
                const _this = this;
                const draftContent = _this.formObject.body;
                axios.post('/api/draft_message', {body: draftContent})
                    .then(response => {
                        _this.$toastr('success', response.data.message, 'Success');
                    })
                    .catch(error => {
                        console.error('Error saving draft:', error);
                        _this.$toastr('error', 'Whoops..!! something went wrong', 'Error');
                    });
            },
            getDraftMessage() {
                const _this = this;
                axios.get('/api/draft_message').then(response => {
                    _this.getData = response.data.result;
                })
                    .catch(error => {
                        console.error('Error saving draft:', error);
                    });
            },
            deleteDraft(draftId) {
                const _this = this;
                axios.delete(`/api/draft_message/${draftId}`)
                    .then(response => {
                        _this.$toastr('success', response.data.message, 'Success');
                        _this.selectedDraftId = '';
                    }).catch(error => {
                    _this.$toastr('error', 'Whoops..!! something went wrong', 'Error');
                });
            },
            setMaskingName : function () {
                const _this = this;
                let selectedType = _this.requiredData.sender_types.find((each) => {
                    return _this.formObject.sender_id_type == each.value;
                });

                _this.$set(_this.formObject, 'masking_name', '');
                _this.$set(_this.formObject, 'isMasking', 'no');

                if (selectedType && selectedType.name === 'Masking') {
                    _this.$set(_this.formObject, 'isMasking', 'yes');

                    if (_this.requiredData.maskings !== undefined && _this.requiredData.maskings.length === 1) {
                        let masking = _this.requiredData.maskings[0];
                        _this.$set(_this.formObject, 'masking_name', masking.key);
                    }
                }
            }
        },
        mounted() {
            const _this = this;
            _this.getDraftMessage();
            _this.$set(this.formObject, 'sender_id_type', '');
            _this.$set(this.formObject, 'phone',[]);
            _this.$set(this.formObject, 'body', '');
            _this.$set(this.formObject, 'schedule', '0');
            _this.$set(this.formObject, 'date', '');
            _this.$set(this.formObject, 'content_type', 1);
            _this.$set(this.formObject, 'masking_name', '');
            _this.$set(this.formObject, 'isMasking', 'no');

            _this.getGeneralData(['SenderId', 'sender_types', 'characters', 'maskings'], function (retData) {
                _this.setCharactersLimit();
                _this.setMaskingName();
            });
        }
    }
</script>
<style>

</style>
