using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web;
using System.Text.RegularExpressions;

namespace Baza_Reklam
{
    public partial class SMSform : Form
    {
        private int customerId;

        public SMSform(string nrTel, int custID)
        {
            InitializeComponent();
            ntTelTextBox.Text = nrTel;
            this.customerId = custID;

            this.kontaktyTableAdapter1.Connection.ConnectionString = ConnString.getConnString().Value;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (ntTelTextBox.Text == "")
            {
                MessageBox.Show("Podaj nr telefonu");
                return;
            }

            if (trescTextBox.Text == "")
            {
                MessageBox.Show("Podaj treść sms-a");
                return;
            }
            
            ASCIIEncoding encoding = new ASCIIEncoding();

            string postData = "login=" + HttpUtility.UrlEncode("CT_CTRAVEL") + "&pass=" + HttpUtility.UrlEncode("jacek@ct.") +
                "&MSISDN=" + HttpUtility.UrlEncode(ntTelTextBox.Text) + "&body="
                + HttpUtility.UrlEncode(trescTextBox.Text);
            byte[] pom1 = encoding.GetBytes(postData);

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.wapster.pl/smssender.asp");
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = pom1.Length;
            
            Stream reqStream = req.GetRequestStream();
            reqStream.Write(pom1, 0, pom1.Length);
            reqStream.Close();
            
            Stream stream = req.GetResponse().GetResponseStream();
            StreamReader sr = new StreamReader(stream);
            string stronka = sr.ReadToEnd();
            if (stronka.Contains("<response><value>1</value></response>"))
            {            
                MessageBox.Show("Wiadomość została wysłana.");
                dodajDoKontaktow();
            }
            else
            {
                MessageBox.Show("Wystąpił błąd. Wiadomość nie została wysłana.");
            }

            sr.Close();
            stream.Close();
            this.Close();
        }

        private void dodajDoKontaktow()
        {
            kontaktyTableAdapter1.Insert(this.customerId, User.getUser().Login, DateTime.Now, "SMS", ntTelTextBox.Text + " \n " + trescTextBox.Text);
        }

        private void SMSform_Load(object sender, EventArgs e)
        {

        }
    }
}