using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StekloMaster
{
    public partial class СТАТУСЫ_главная : Form
    {
        public СТАТУСЫ_главная()
        {
            InitializeComponent();
        }
        string putin = "";
        bool rab = false;

        string kod = "";
        string textstatus = "";
        string loginsms = "";
        string passwordsms = "";
        string textsms = "";

        //допы
        string loginmail = "";
        string passmail = "";
        string smtpmail = "";
        string tomail = "";
        string textdopsms = "";

        private void StatusZakaz_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void StatusZakaz_Shown(object sender, EventArgs e)
        {
            if (Application.StartupPath.IndexOf("comp") != -1)
            {
                putin = Application.StartupPath.Substring(0, Application.StartupPath.IndexOf("\\comp"));
            }
            else
            {
                putin = Application.StartupPath;
            }
            //читаем настройки
            if (Directory.Exists(Application.StartupPath + "\\scan_setting"))
            {
                if (File.Exists(Application.StartupPath + "\\scan_setting\\kod.akv"))
                {
                    StreamReader sr = new StreamReader(Application.StartupPath + "\\scan_setting\\kod.akv");
                    kod = "<"+sr.ReadToEnd()+">";
                    sr.Close();
                }
                if (File.Exists(Application.StartupPath + "\\scan_setting\\text.akv"))
                {
                    StreamReader sr = new StreamReader(Application.StartupPath + "\\scan_setting\\text.akv");
                   textstatus = sr.ReadToEnd();
                    sr.Close();
                }
                if (File.Exists(Application.StartupPath + "\\scan_setting\\sms.akv"))
                {
                    StreamReader sr = new StreamReader(Application.StartupPath + "\\scan_setting\\sms.akv");
                    string tmp = sr.ReadToEnd();
                    loginsms= tmp.Split('|')[0];
                    passwordsms = tmp.Split('|')[1];
                    sr.Close();
                }
                if (File.Exists(Application.StartupPath + "\\scan_setting\\textsms.akv"))
                {
                    StreamReader sr = new StreamReader(Application.StartupPath + "\\scan_setting\\textsms.akv");
                    textsms = sr.ReadToEnd();
                    sr.Close();
                }
                if (File.Exists(Application.StartupPath + "\\scan_setting\\textdopsms.akv"))
                {
                    StreamReader sr = new StreamReader(Application.StartupPath + "\\scan_setting\\textdopsms.akv");
                    textdopsms = sr.ReadToEnd();
                    sr.Close();
                }
                if (File.Exists(Application.StartupPath + "\\scan_setting\\mail.akv"))
                {
                    StreamReader sr = new StreamReader(Application.StartupPath + "\\scan_setting\\mail.akv");
                    string tmp = sr.ReadToEnd();
                    string[] s = tmp.Split('|');
                    loginmail = s[0];
                    passmail = s[1];
                    smtpmail = s[2];
                    tomail = s[3];
                    sr.Close();
                }
            }
            if(kod == "")
            {
                MessageBox.Show("Пожалуйста укажите в настройках данные и перезапустите программу!");
            }
            label1.Focus();

        }

        private void button3_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form17")
                {
                    MessageBox.Show("База заказов уже открыта!");
                    return;
                }
            }
            Form17 f1 = new Form17();
            f1.Owner = this;
            f1.master();
            f1.Show();
            f1.Focus();
        }
        

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "СТАТУСЫ_клавиатура_для_ввода_номера")
                {
                    MessageBox.Show("Клавиатура для номера заказа уже открыта!");
                    return;
                }
            }

            СТАТУСЫ_клавиатура_для_ввода_номера form1 = new СТАТУСЫ_клавиатура_для_ввода_номера();
            form1.Owner = this;
            form1.Show();
        }

        public void scaner(string komand)
        {
            bool naiden = true;
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "СТАТУСЫ_выдача_заказа")
                {
                    СТАТУСЫ_выдача_заказа gs = f as СТАТУСЫ_выдача_заказа;
                    gs.maskedTextBox2.Text = komand;
                    gs.button2_Click(null, null);
                    naiden = false;
                    break;
                }
            }
            if (naiden)
            {
                maskedTextBox2.Text = komand;
                button2_Click(null, null);
            }
        }

        public void button2_Click(object sender, EventArgs e)
        {
            if (maskedTextBox2.Text == "")
            {
                MessageBox.Show("Номер заказа не может быть пустым!");
                return;
            }
            if(maskedTextBox2.Text == "0000")
            {
                if (MessageBox.Show("Вы уверены, что хотите перевести программу в режим \"Просчёт\"?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    File.Delete(Application.StartupPath + "\\scaner.akv");
                    Application.Restart();
                }
                maskedTextBox2.Text = "";
                return;
            }
            if(maskedTextBox2.Text == "12345678")
            {
                maskedTextBox2.Text = "";
                foreach (Form f in Application.OpenForms)
                {
                    if (f.Name == "СТАТУСЫ_настройки")
                    {
                        MessageBox.Show("Настройки выдачи заказов уже открыты!");
                        return;
                    }
                }
                СТАТУСЫ_настройки f1 = new СТАТУСЫ_настройки();
                f1.Owner = this;
                f1.Show();
                f1.Focus();
                return;
            }
            if (rab)
            {
                MessageBox.Show("Пожалуйста подождите завершения синхронизации с сервером!");
                return;
            }
            string nomes = maskedTextBox2.Text.ToUpper().Replace("А", "A").Replace("В", "B").Replace("С", "C").Replace("Е", "E").Replace("Т", "T").Replace("О", "O").Replace("Р", "P").Replace("Н", "H").Replace("К", "K").Replace("Х", "X").Replace("М", "M");
            Thread lod = new Thread(delegate ()
            {
                otpr(nomes);
            });
            lod.IsBackground = true;
            lod.Start();
            //очистка
            maskedTextBox2.Text = "";
            maskedTextBox2.Focus();
        }

        private void otpr(string nomer)
        {
            this.Invoke(new EventHandler(delegate
            {
                label1.Text = "Отправляем заказ №" + nomer;
                pictureBox1.Image = Properties.Resources.page_loader;
            }));

            string nasite = "";
            if (File.Exists(Application.StartupPath + "\\site.akv"))
            {
                StreamReader Sr = new StreamReader(new FileStream(Application.StartupPath + "\\site.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                nasite = Sr.ReadToEnd();
                Sr.Close();
                Sr = null;
            }
            if (nasite.IndexOf("<" + nomer + ">") == -1)
            {
                File.WriteAllText(Application.StartupPath + "\\site.akv", nasite + "<" + nomer + ">", Encoding.UTF8);
                otpravka();
            }
            else
            {
                this.Invoke(new EventHandler(delegate
                {
                    label1.Text = "Заказ №" + nomer + " уже поставлен в очередь!";
                    pictureBox1.Image = Properties.Resources.unnamed;
                }));
            }
        }

        bool sendSms(string nomer, string mess, bool result = false)
        {
            bool otv = false;
            //File.WriteAllText(Application.StartupPath + "\\answer1.akv","1", Encoding.UTF8);
            if (loginsms != "" && passwordsms != "" && mess != "")
            {
                try
                {
                    //отправка смс
                    mess = WebUtility.UrlEncode(mess);
                    byte[] bytes = Encoding.Default.GetBytes(mess);
                    mess = Encoding.UTF8.GetString(bytes);

                    string times = "";
                    if(DateTime.Now.Hour < 10)
                    {
                        DateTime d1 = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 10, 00, 00);
                        DateTime d2 = d1;
                        d1 = d1.AddDays(20);
                        string time = d2.ToString().Substring(0, d2.ToString().LastIndexOf(":"));
                        time = time.Replace(DateTime.Now.Year.ToString(), ((int)DateTime.Now.Year % 100).ToString());
                        time = time.Replace(".", "").Replace(":", "").Replace(" ", "");
                        byte[] bytess = Encoding.Default.GetBytes(time);
                        time = Encoding.UTF8.GetString(bytess);

                        times = "&time=" + time;
                    }
                    HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create("http://smsc.ru/sys/send.php?login=" + loginsms + "&psw=" + passwordsms +
                "&phones=" + nomer + "&mes=" + mess +times+ "&charset=utf-8");

                    HttpWebResponse r2 = (HttpWebResponse)request2.GetResponse();
                    string answer = new StreamReader(r2.GetResponseStream(), Encoding.UTF8).ReadToEnd();
                //    File.WriteAllText(Application.StartupPath + "\\answer.akv", answer, Encoding.UTF8);
                    otv = true;
                }
                catch
                {
                    if (!result)
                    {
                        //запись и автовызов
                        string sms = "";
                        if (File.Exists(Application.StartupPath + "\\sinhronsms.akv"))
                        {
                            StreamReader sr = new StreamReader(new FileStream(Application.StartupPath + "\\sinhronsms.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                            sms = sr.ReadToEnd();
                            sr.Close();
                        }
                        sms += "<" + nomer + "|" + mess + ">";
                        File.WriteAllText(Application.StartupPath + "\\sinhronsms.akv", sms, Encoding.UTF8);
                    }
                }
            }
            else
            {
                otv = true;
            }
            return otv;
        }

        private void otpravka()
        {
            if (File.Exists(Application.StartupPath + "\\site.akv"))
            {
                rab = true;
                StreamReader sr = new StreamReader(new FileStream(Application.StartupPath + "\\site.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                string k = sr.ReadToEnd();
                sr.Close();
                string[] words = k.Split('>');
                foreach (string word in words)
                {
                    if (word == null || word == "" || word == "<") continue;
                    string wordss = word.Replace("<", "");
                    try
                    {
                        if (Directory.Exists(putin + "\\baza\\" + wordss))
                        {
                            if (!File.Exists(putin + "\\baza\\" + wordss + "\\zabran.akv"))
                            {
                                string status = "";
                                if (File.Exists(putin + "\\baza\\" + wordss + "\\status.akv"))
                                {
                                    StreamReader Sr = new StreamReader(new FileStream(putin + "\\baza\\" + wordss + "\\status.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                                    status = Sr.ReadToEnd();
                                    Sr.Close();
                                    Sr = null;
                                }
                                //проверка на уже установленность
                                if (status != "" && status.IndexOf(kod) != -1)
                                {
                                    this.Invoke(new EventHandler(delegate
                                    {
                                        label1.Text = "Заказ №" + wordss + " уже имеет текущий статус.";
                                        pictureBox1.Image = Properties.Resources.task_completed;
                                    }));
                                }
                                else
                                {
                                    status += DateTime.Now + "|" + kod + "|" + textstatus + "\r\n";
                                    File.WriteAllText(putin + "\\baza\\" + wordss + "\\status.akv", status, Encoding.UTF8);
                                    try
                                    {
                                        string klient = "";
                                        string[] masklient = null;
                                        if (File.Exists(putin + "\\baza\\" + wordss + "\\klient.akv"))
                                        {
                                            StreamReader Sr = new StreamReader(new FileStream(putin + "\\baza\\" + wordss + "\\klient.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                                            klient = Sr.ReadToEnd();
                                            Sr.Close();
                                            masklient = klient.Split('|');
                                        }

                                        if ((loginmail != "" && passmail != "" && smtpmail != "" && tomail != "") || (textdopsms != ""))
                                        {
                                            //читаем доставку
                                            if (File.Exists(putin + "\\baza\\" + wordss + "\\zakaz.akv"))
                                            {
                                                string h = "";
                                                StreamReader Sr = new StreamReader(new FileStream(putin + "\\baza\\" + wordss + "\\zakaz.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                                                h = Sr.ReadToEnd();

                                                string[] tmp = h.Split('|');
                                                if((tmp[5] != "" && tmp[6]!= "")||(tmp[7]!=""&&tmp[8]!=""&&tmp[9]!=""))
                                                {
                                                    //доставка есть
                                                    if(loginmail != "" && passmail != "" && smtpmail != "" && tomail != "" && klient != "")
                                                    {
                                                        //формируем сообщение на почту
                                                        string message = "Номер заказа: " + wordss + "\r\n\r\nДанные клиента:\r\nФИО: " + masklient[0] + " " + masklient[1] + " " + masklient[2] + "\r\nТелефон: +" + masklient[4] + "\r\n";
                                                        if (masklient[7] != "")
                                                            message += "Почта: " + masklient[7]+"\r\n";
                                                        if (masklient[8] != "")
                                                            message += "Комментарий клиента: " + masklient[8] + "\r\n";
                                                        message += "\r\n";
                                                        if(tmp[5] != "" && tmp[6] != "")
                                                        {
                                                            //доставка
                                                            message += "Доставка:\r\nАдрес доставки: " + tmp[6]+"\r\nЦена доставки: "+tmp[5]+"\r\n\r\n";
                                                        }
                                                        if(tmp[7] != "" && tmp[8] != "" && tmp[9] != "")
                                                        {
                                                            //подъем
                                                            message += "Подъем:\r\nЭтаж: " + tmp[7] + "\r\nКол-во: "+tmp[8]+"\r\nЦена: "+tmp[9]+"\r\n\r\n";
                                                        }
                                                        //оплачено и тд
                                                        string oplachen = "";
                                                        string ostatok = "";
                                                        if (File.Exists(putin + "\\baza\\" + wordss + "\\doplata.akv"))
                                                        {
                                                            string str33 = "";
                                                            double opl = 0;
                                                            using (StreamReader srr = new StreamReader(new FileStream(putin + "\\baza\\" + wordss + "\\doplata.akv", FileMode.Open, FileAccess.Read, FileShare.Read)))
                                                            {
                                                                while ((str33 = srr.ReadLine()) != null)
                                                                {
                                                                    if (str33 == "") continue;
                                                                    if (str33.Split('|')[1] != "")
                                                                        opl += Convert.ToDouble(str33.Split('|')[1]);
                                                                }
                                                            }
                                                            oplachen = (opl + Convert.ToDouble(tmp[11])).ToString();
                                                            ostatok = (Convert.ToDouble(tmp[12]) - opl).ToString();
                                                        }
                                                        else
                                                        {
                                                            oplachen = tmp[11];
                                                            ostatok = tmp[12];
                                                        }
                                                        message += "Оплата:\r\nОплачено: " + tmp[11] + "\r\nОстаток: " + tmp[12];

                                                        if(!Program.SendMail(smtpmail, loginmail, passmail, tomail, "[StekloMaster] Доставка заказа",message,null,587))
                                                        {
                                                            //запись 
                                                            string pochta = "";
                                                            if (File.Exists(Application.StartupPath + "\\sinhronpochta.akv"))
                                                            {
                                                                StreamReader srs = new StreamReader(new FileStream(Application.StartupPath + "\\sinhronpochta.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                                                                pochta = srs.ReadToEnd();
                                                                srs.Close();
                                                            }
                                                            pochta += "<" + message + ">";
                                                            File.WriteAllText(Application.StartupPath + "\\sinhronpochta.akv", pochta, Encoding.UTF8);
                                                        }
                                                    }
                                                    if(textdopsms != "")
                                                    {
                                                        //формируем смс с заменой
                                                        if (klient != "")
                                                            sendSms(masklient[4], textdopsms.Replace("{zakaz}", wordss));
                                                    }
                                                    else
                                                    {
                                                        //формируем смс как-будто доставки нет
                                                        if (klient != "")
                                                            sendSms(masklient[4], textsms.Replace("{zakaz}", wordss));
                                                    }
                                                }
                                                else
                                                {
                                                    //доставки нет
                                                    if (klient != "")
                                                        sendSms(masklient[4], textsms.Replace("{zakaz}", wordss));
                                                }
                                            }
                                            else
                                            {
                                                //доставки нет
                                                if (klient != "")
                                                    sendSms(masklient[4], textsms.Replace("{zakaz}", wordss));
                                            }
                                        }
                                        else
                                        {
                                            //доставки нет
                                            if(klient != "")
                                                sendSms(masklient[4], textsms.Replace("{zakaz}", wordss));
                                        }
                                    }
                                    catch(Exception fas)
                                    {
                                        new Thread(delegate () { MessageBox.Show(fas.Message); }).Start();
                                    }
                                    this.Invoke(new EventHandler(delegate
                                    {
                                        //устанавливаем статус
                                        label1.Text = textstatus + " №" + wordss;
                                        pictureBox1.Image = Properties.Resources.correct_vinkje;
                                    }));
                                }
                            }
                            else
                            {
                                this.Invoke(new EventHandler(delegate
                                {
                                    label1.Text = "Заказ №" + wordss + " уже забран.";
                                    pictureBox1.Image = Properties.Resources.security_pass;
                                }));
                            }
                        }
                        else
                        {
                            this.Invoke(new EventHandler(delegate
                            {
                                label1.Text = "Заказ №" + wordss + " не найден.";
                                pictureBox1.Image = Properties.Resources.icon_not_found;
                            }));
                        }
                        k = k.Replace("<" + wordss + ">", "");
                        if (k == "" || k == null)
                        {
                            File.Delete(Application.StartupPath + "\\site.akv");
                        }
                        else
                        {
                            File.WriteAllText(Application.StartupPath + "\\site.akv", k, Encoding.UTF8);
                        }

                    }
                    catch
                    {
                        this.Invoke(new EventHandler(delegate
                        {
                            label1.Text = "Заказ №" + wordss.Split('|')[0] + " будет отмечен ПОЗЖЕ.";
                            pictureBox1.Image = Properties.Resources.images;
                        }));
                    }
                }
                rab = false;
            }
        }

        public void vidacha(string nomer)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "СТАТУСЫ_выдача_заказа")
                {
                    СТАТУСЫ_выдача_заказа gs = f as СТАТУСЫ_выдача_заказа;
                    gs.maskedTextBox2.Text = nomer;
                    gs.button2_Click(null, null);
                    gs.Focus();
                    return;
                }
            }
            СТАТУСЫ_выдача_заказа f1 = new СТАТУСЫ_выдача_заказа();
            f1.Owner = this;
            f1.putin = putin;
            //f1.master();
            f1.Show();
            f1.maskedTextBox2.Text = nomer;
            f1.button2_Click(null, null);
            f1.Focus();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "СТАТУСЫ_выдача_заказа")
                {
                    MessageBox.Show("Выдача заказа уже открыта!");
                    return;
                }
            }
            СТАТУСЫ_выдача_заказа f1 = new СТАТУСЫ_выдача_заказа();
            f1.Owner = this;
            f1.putin = putin;
            //f1.master();
            f1.Show();
            f1.Focus();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Thread lod = new Thread(delegate ()
            {
                if (File.Exists(Application.StartupPath + "\\sinhronsms.akv"))
                {
                    //требует досинхрон смс
                    StreamReader sr = new StreamReader(new FileStream(Application.StartupPath + "\\sinhronsms.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                    string k = sr.ReadToEnd();
                    sr.Close();
                    string[] words = k.Split('>');
                    foreach (string word in words)
                    {
                        if (word == null || word == "" || word == "<") continue;
                        string wordss = word.Replace("<", "");
                        try
                        {
                            if(sendSms(wordss.Split('|')[0], wordss.Split('|')[1],true))
                            {
                                //удаляем
                                k = k.Replace("<" + wordss + ">", "");
                                if (k == "" || k == null)
                                {
                                    File.Delete(Application.StartupPath + "\\sinhronsms.akv");
                                }
                                else
                                {
                                    File.WriteAllText(Application.StartupPath + "\\sinhronsms.akv", k, Encoding.UTF8);
                                }
                            }
                        }
                        catch
                        {

                        }
                    }
                }
                
                if (File.Exists(Application.StartupPath + "\\sinhronpochta.akv"))
                {
                    //досинхрон почты
                    StreamReader sr = new StreamReader(new FileStream(Application.StartupPath + "\\sinhronpochta.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                    string k = sr.ReadToEnd();
                    sr.Close();
                    string[] words = k.Split('>');
                    foreach (string word in words)
                    {
                        if (word == null || word == "" || word == "<") continue;
                        string wordss = word.Replace("<", "");
                        try
                        {
                            if (Program.SendMail(smtpmail, loginmail, passmail, tomail, "[StekloMaster] Доставка заказа", wordss, null, 587))
                            {
                                //удаляем
                                k = k.Replace("<" + wordss + ">", "");
                                if (k == "" || k == null)
                                {
                                    File.Delete(Application.StartupPath + "\\sinhronpochta.akv");
                                }
                                else
                                {
                                    File.WriteAllText(Application.StartupPath + "\\sinhronpochta.akv", k, Encoding.UTF8);
                                }
                            }
                        }
                        catch
                        {

                        }
                    }
                }
            });
            lod.IsBackground = true;
            lod.Start();
        }
    }
}
