using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.IO;

public partial class rl_admins_pg_EditTeacher : System.Web.UI.Page
{
    //********************
    SqlConnection con;
    SqlCommand cmd;
    SqlTransaction tr;
    static string defUrl = "";
    //********************
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            ScriptManager sm = ScriptManager.GetCurrent(this.Page);
            sm.RegisterPostBackControl(btnOk);
            string conString = RamanConnectionString.LocalConnectionString();
            con = new SqlConnection(conString);
            C_myClass.MenueItemsCreate(User, panelMenues);
            Label lblTitle = (Label)this.Master.FindControl("lblTitle");
            lblTitle.Text = "ویرایش مدرس";
            if (!Page.IsPostBack)
            {
                string fullName = "", gender = "", tahsilat = "", teacherBio = "";
                int teacherId = Int32.Parse(Session["iden"].ToString());
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = "select fullName, gender, tahsilat, history, teacherPhotoUrl FROM t_Teachers Where teacherId = " + teacherId;
                SqlDataReader rdr = cmd.ExecuteReader();
                if (rdr.HasRows)
                {
                    while (rdr.Read())
                    {
                        fullName = (rdr.GetValue(0) != DBNull.Value ? rdr.GetString(0) : "");
                        gender = (rdr.GetValue(1) != DBNull.Value ? rdr.GetString(1) : "");
                        tahsilat = (rdr.GetValue(2) != DBNull.Value ? rdr.GetString(2) : "");
                        teacherBio = (rdr.GetValue(3) != DBNull.Value ? rdr.GetString(3) : "");
                        defUrl = (rdr.GetValue(4) != DBNull.Value ? rdr.GetString(4) : "");
                    }
                }
                rdr.Close();
                //////////////////////////////////// set page controls :
                tbFullName.Text = fullName;
                tbBio.Text = teacherBio;
                ListItem tahsilatItem = new ListItem(tahsilat);
                cmbTahsilat.SelectedIndex = cmbTahsilat.Items.IndexOf(tahsilatItem);
                rbMale.Checked = (gender == "مرد" ? true : false);
                rbFemale.Checked = (gender == "زن" ? true : false);
                string photoesFolderPath = Request.PhysicalApplicationPath + @"photoes\";
                if (File.Exists(photoesFolderPath + defUrl))
                {
                    imgPhoto.ImageUrl = "~/photoes/" + defUrl;
                }
                else
                {
                    imgPhoto.BorderStyle = BorderStyle.None;
                    imgPhoto.ImageUrl = "~/photoes/noPersonalPhoto.gif";
                }
            }
        }
        catch
        {
        }
        finally
        {
            con.Close();
        }
    }
    protected void btnOk_Click(object sender, EventArgs e)
    {
        try
        {
            int teacherId = Int32.Parse(Session["iden"].ToString());
            bool isValid = false;
            string fileName = "", fullName = "", gender = "", tahsilat = "", history = "", photoUrl = defUrl;
            fullName = tbFullName.Text;
            gender = (rbMale.Checked ? "مرد" : (rbFemale.Checked ? "زن" : ""));
            tahsilat = (cmbTahsilat.SelectedIndex > 0 ? cmbTahsilat.SelectedItem.ToString() : "");
            history = tbBio.Text;
            string conString = RamanConnectionString.LocalConnectionString();
            con = new SqlConnection(conString);
            con.Open();
            tr = con.BeginTransaction();
            SqlCommand cmd = con.CreateCommand();
            cmd.Transaction = tr;
            cmd.CommandText = t_TeachersUpdateCommand(teacherId, fullName, gender, tahsilat, history);
            cmd.ExecuteNonQuery();
            tr.Commit();
            lblMessage.ForeColor = System.Drawing.Color.Green;
            lblMessage.Text = "با موفقیت ذخیره شد.";
        }
        catch (Exception ex)
        {
            try
            {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "عملیات ذخیره سازی با شکست مواجه شد ، لطفاً مجدداً سعی نمایید.";
                tr.Rollback();
            }
            catch
            {
            }
        }
        finally
        {
            con.Close();
        }
    }

    private string t_TeachersUpdateCommand(int TeacherId, string FullName, string Gender, string Tahsilat, string History)
    {
        string comm = "update t_Teachers SET " +
            "fullName = N'" + FullName + "' , " +
            "gender = N'" + Gender + "' , " +
            "tahsilat = N'" + Tahsilat + "' , " +
            "history = N'" + History + "' " +
            "WHERE teacherId = " + TeacherId;
        return comm;
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        try
        {
            string returnUrl = Request.QueryString["returnUrl"].ToString();
            Response.Redirect(returnUrl);
        }
        catch
        {
        }
    }
    protected void btnRecieved_Click(object sender, EventArgs e)
    {
        string userPhotoUrl = "";
        try
        {
            if (fuUserPhoto.HasFile)
            {
                System.Threading.Thread.Sleep(2000);
                string fileName = fuUserPhoto.PostedFile.FileName;
                bool isValid = C_myClass.IsValidFileType(fileName);
                if (isValid)
                {
                    string ext = C_myClass.FileExtenssion(fileName);
                    string photoesPath = Request.PhysicalApplicationPath + @"photoes\";
                    if (File.Exists(photoesPath + _UseFull.C_Usefull.Serialize(fileName, 7).Trim() + @"." + ext))
                    {
                        Random rnd = new Random();
                        int randomNum = rnd.Next(1, 9999999);
                        fileName += randomNum.ToString();
                    }
                    fileName = _UseFull.C_Usefull.Serialize(fileName, 7).Trim();
                    userPhotoUrl = fileName + @"." + ext;
                    //FileUpload1.SaveAs(Request.PhysicalApplicationPath + @"photoes\" + photoUrl);
                    fuUserPhoto.SaveAs(Request.PhysicalApplicationPath + @"photoes\" + userPhotoUrl);
                    int teacherId = Int32.Parse(Session["iden"].ToString());
                    string conString = RamanConnectionString.LocalConnectionString();
                    con = new SqlConnection(conString);
                    cmd = con.CreateCommand();
                    try
                    {
                        con.Open();
                        string currentUrl = _UseFull.C_Usefull.FindStringWithStringShart(con, cmd, "t_Teachers", "teacherPhotoUrl", "userName", User.Identity.Name);
                        if (File.Exists(Request.PhysicalApplicationPath + @"photoes\" + currentUrl))
                            File.Delete(Request.PhysicalApplicationPath + @"photoes\" + currentUrl);
                        cmd.CommandText = "update t_Teachers SET teacherPhotoUrl = N'" + userPhotoUrl + "' Where teacherId = " + teacherId;
                        cmd.ExecuteNonQuery();
                        imgPhoto.ImageUrl = "~/photoes/" + userPhotoUrl;
                    }
                    catch
                    {
                        File.Delete(Request.PhysicalApplicationPath + @"photoes\" + userPhotoUrl);
                    }
                    finally
                    {
                        con.Close();
                    }
                }
            }
        }
        catch
        {
            if (File.Exists(Request.PhysicalApplicationPath + @"photoes\" + userPhotoUrl))
                File.Delete(Request.PhysicalApplicationPath + @"photoes\" + userPhotoUrl);
        }
    }
}
