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.Collections.Generic;


public partial class rl_admins_pg_ClassDefine : System.Web.UI.Page
{
    //*************************************
    SqlConnection con;
    SqlTransaction tr;
    static string lastQuery = "", lastStudentQuery = "";
    static DataTable dt;
    static bool courseSelected = false;
    //*************************************
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!Page.IsPostBack)
            {
                C_myClass.MenueItemsCreate(User, panelMenues);
                Label lblTitle = (Label)this.Master.FindControl("lblTitle");
                lblTitle.Text = "تعریف کلاس";
                lastQuery = "SELECT * FROM [t_Courses] ORDER BY [courseId]";
                dt = new DataTable();
                dt.Columns.Add("studentId");
                dt.Columns.Add("fullName");
                dt.Columns.Add("tahsilat");
                dt.Columns.Add("dateOfBirth");
                dt.Columns.Add("userName");
                courseSelected = false;
            }
        }
        catch
        {
        }
        finally
        {
        }
    }

    protected void btnAddCourse_Click(object sender, EventArgs e)
    {
        try
        {
            lastQuery = "SELECT * FROM [t_Courses] ORDER BY [courseId]";
            SqlDataSource1.SelectCommand = lastQuery;
            GridView1.DataBind();
            tbSearch.Text = "";
            ModalPopupExtender1.Show();
        }
        catch
        {
        }
    }
    
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "SelectPress")
            {
                int courseId = Int32.Parse(e.CommandArgument.ToString());
                string conSt = RamanConnectionString.LocalConnectionString();
                con = new SqlConnection(conSt);
                SqlCommand cmd = con.CreateCommand();
                try
                {
                    con.Open();
                    string courseName = _UseFull.C_Usefull.FindStringWithIntegerShart(con, cmd, "t_Courses", "courseName", "courseId", courseId);
                    tbCourseId.Text = courseId.ToString();
                    tbCourseName.Text = courseName;
                    lastStudentQuery = "SELECT t_Students.studentId, t_Students.fullName, t_Students.gender, t_Students.tahsilat, t_Students.dateOfBirth, t_Students.melliCode, t_Students.studentPhotoUrl, t_Students.userName, t_Students.userCreater, t_Registers.courseId FROM t_Students INNER JOIN t_Registers ON t_Students.studentId = t_Registers.studentId WHERE (t_Registers.courseId = " + courseId + " AND t_Registers.regStatus = N'تأیید'" + ")";
                    courseSelected = true;
                    ModalPopupExtender1.Hide();
                }
                catch
                {
                }
                finally
                {
                    if (con.State != ConnectionState.Closed)
                        con.Close();
                }
            }
        }
        catch
        {
        }
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            GridView1.PageIndex = e.NewPageIndex;
            SqlDataSource1.SelectCommand = lastQuery;
            GridView1.DataBind();
            tbSearch.Text = "";
            ModalPopupExtender1.Show();
        }
        catch
        {
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        try
        {
            ModalPopupExtender1.Hide();
        }
        catch
        {
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            string courseName = tbSearch.Text;
            courseName = courseName.Replace(",", "");
            lastQuery = "SELECT * FROM [t_Courses] Where courseName LIKE N'%" + courseName + "%' ORDER BY [courseId]";
            SqlDataSource1.SelectCommand = lastQuery;
            GridView1.DataBind();
            ModalPopupExtender1.Show();
        }
        catch(Exception ex)
        {
            ModalPopupExtender1.Show();
        }
    }
    protected void btnAllShow_Click(object sender, EventArgs e)
    {
        try
        {
            lastQuery = "SELECT * FROM [t_Courses] ORDER BY [courseId]";
            SqlDataSource1.SelectCommand = lastQuery;
            GridView1.DataBind();
            tbSearch.Text = "";
            ModalPopupExtender1.Show();
        }
        catch
        {
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        try
        {
            string returnUrl = Request.QueryString["returnUrl"].ToString();
            Response.Redirect(returnUrl);
        }
        catch
        {
        }
    }

    protected void btnAddStudent_Click(object sender, EventArgs e)
    {
        try
        {
            if (courseSelected)
            {
                SqlDataSource2.SelectCommand = (lastStudentQuery.Length > 0 ? lastStudentQuery : SqlDataSource2.SelectCommand);
                GridStudents.DataBind();
                mpeStudents.Show();
            }
        }
        catch
        {
        }
    }
    protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            GridView2.PageIndex = e.NewPageIndex;
            GridView2.DataSource = dt;
            GridView2.DataBind();
        }
        catch
        {
        }
    }
    protected void btnOk_Click(object sender, EventArgs e)
    {
        try
        {
            if ((tbClassTitle.Text.Length > 0) && (tbCourseId.Text.Length > 0) && (tbTeacherId.Text.Length > 0))
            {
                courseSelected = false;
                string conString = RamanConnectionString.LocalConnectionString();
                con = new SqlConnection(conString);
                SqlCommand cmd = con.CreateCommand();
                try
                {
                    con.Open();
                    tr = con.BeginTransaction();
                    cmd.Transaction = tr;
                    int classId = 0;
                    string status = (chackStatus.Checked ? "جاری" : "گذشته");
                    string classTitle = tbClassTitle.Text;
                    int courseId = Int32.Parse(tbCourseId.Text);
                    int teacherId = Int32.Parse(tbTeacherId.Text);
                    cmd.CommandText = "insert into t_Classes (courseId, teacherId, classTitle, status) values(" +
                        courseId + " , " +
                        teacherId + " , N'" +
                        classTitle + "', N'" +
                        status + "') " +
                        "SELECT SCOPE_IDENTITY() AS Last_Id";
                    classId = Int32.Parse(cmd.ExecuteScalar().ToString());

                    for (int i = 0; i < GridView2.Rows.Count; i++)
                    {
                        DropDownList cmbOp = (DropDownList)GridView2.Rows[i].FindControl("cmbOp");
                        string op = cmbOp.SelectedItem.ToString();
                        if (op == "ثبت")
                        {
                            int studentId = Int32.Parse(GridView2.Rows[i].Cells[1].Text);
                            cmd.CommandText = "insert into t_ClassStudents (classId, studentId) values(" +
                                classId + " , " +
                                studentId + " )";
                            cmd.ExecuteNonQuery();
                        }
                    }
                    tr.Commit();
                    lblMessage.ForeColor = System.Drawing.Color.Green;
                    lblMessage.Text = "با موفقیت ذخیره شد.";
                }
                catch (Exception exc)
                {
                    tr.Rollback();
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    lblMessage.Text = exc.Message;
                }
                finally
                {
                    con.Close();
                }
            }
            else
            {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "عنوان کلاس ، دوره و مدرس الزامی می باشند.";
            }
        }
        catch(Exception ex)
        {
            lblMessage.ForeColor = System.Drawing.Color.Red;
            lblMessage.Text = ex.Message;
        }
    }
    protected void GridStudents_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "SelectStudentPress")
            {
                int studentId = Int32.Parse(e.CommandArgument.ToString());
                if (!IsInList(studentId))
                {
                    Hashtable studentInfo = FindStudentInfo(studentId);
                    DataRow dr = dt.NewRow();
                    dr["studentId"] = studentInfo["studentId"].ToString();
                    dr["fullName"] = studentInfo["fullName"].ToString();
                    dr["tahsilat"] = studentInfo["tahsilat"].ToString();
                    dr["dateOfBirth"] = studentInfo["dateOfBirth"].ToString();
                    dr["userName"] = studentInfo["userName"].ToString();
                    dt.Rows.Add(dr);
                    GridView2.DataSource = dt;
                    int rowCount = dt.Rows.Count;
                    if (rowCount > 10)
                    {
                        int mod = rowCount % 10;
                        if (mod == 0)
                        {
                            GridView2.PageIndex = rowCount / 10;
                        }
                        else if (mod > 0)
                        {
                            GridView2.PageIndex = (rowCount / 10) + 1;
                        }
                    }
                    GridView2.DataBind();
                    UpdatePanel2.Update();
                }
                mpeStudents.Hide();
            }
        }
        catch
        {
        }
    }

    private bool IsInList(int StudentId)
    {
        bool res = false;
        try
        {
            for (int i = 0; i < GridView2.Rows.Count; i++)
            {
                int stuId = Int32.Parse(GridView2.Rows[i].Cells[1].Text);
                if (StudentId == stuId)
                    res = true;
            }
        }
        catch
        {
        }
        return res;
    }

    private Hashtable FindStudentInfo(int StudentId)
    {
        Hashtable info = new Hashtable();
        string conStrin = RamanConnectionString.LocalConnectionString();
        con = new SqlConnection(conStrin);
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandText = "select studentId, fullName, tahsilat, dateOfBirth, userName FROM t_Students Where studentId = " + StudentId;
        try
        {
            con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            if (rdr.HasRows)
            {
                while (rdr.Read())
                {
                    int studentId = (rdr.GetValue(0) != DBNull.Value ? rdr.GetInt32(0) : 0 );
                    string fullName = (rdr.GetValue(1) != DBNull.Value ? rdr.GetString(1) : "");
                    string tahsilat = (rdr.GetValue(2) != DBNull.Value ? rdr.GetString(2) : "");
                    string dateOfBirth = (rdr.GetValue(3) != DBNull.Value ? rdr.GetString(3) : "");
                    string userName = (rdr.GetValue(4) != DBNull.Value ? rdr.GetString(4) : "");
                    info["studentId"] = studentId;
                    info["fullName"] = fullName;
                    info["tahsilat"] = tahsilat;
                    info["dateOfBirth"] = dateOfBirth;
                    info["userName"] = userName;
                }
            }
            rdr.Close();
        }
        catch
        {
        }
        finally
        {
            if (con.State != ConnectionState.Closed)
                con.Close();
        }
        return info;
    }

    protected void btnStudentsCancel_Click(object sender, EventArgs e)
    {
        try
        {
            mpeStudents.Hide();
        }
        catch
        {
        }
    }
    protected void GridStudents_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            GridStudents.PageIndex = e.NewPageIndex;
            SqlDataSource2.SelectCommand = lastStudentQuery;
            GridStudents.DataBind();
        }
        catch
        {
        }
    }
    protected void GridTeachers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "SelectTeacher")
            {
                int teacherId = Int32.Parse(e.CommandArgument.ToString());
                string conSt = RamanConnectionString.LocalConnectionString();
                con = new SqlConnection(conSt);
                SqlCommand cmd = con.CreateCommand();
                try
                {
                    con.Open();
                    string fullName = _UseFull.C_Usefull.FindStringWithIntegerShart(con, cmd, "t_Teachers", "fullName", "teacherId", teacherId);
                    tbTeacherId.Text = teacherId.ToString();
                    tbTeacherName.Text = fullName;
                    mpeTeachers.Hide();
                }
                catch
                {
                }
                finally
                {
                    if (con.State != ConnectionState.Closed)
                        con.Close();
                }
            }
        }
        catch
        {
        }
    }
    protected void GridTeachers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            GridTeachers.PageIndex = e.NewPageIndex;
            GridTeachers.DataBind();
        }
        catch
        {
        }
    }
    protected void btnTeacherSelect_Click(object sender, EventArgs e)
    {
        try
        {
            GridTeachers.DataBind();
            mpeTeachers.Show();
        }
        catch
        {
        }
    }
    protected void btnOk_Command(object sender, CommandEventArgs e)
    {

    }
}
