<?php
// Database connection ($con) আগে তৈরি থাকবে

$madrasa_code = $madrasa_code ?? 1;

// সার্চ ফাংশন
if (isset($_POST['search'])) {
  $tea_id_seacrh = mysqli_real_escape_string($con, $_POST['tea_id_seacrh']);
  $sql_search = "SELECT * FROM teacher WHERE teacher_id = '$tea_id_seacrh'  AND madrasa_code='$madrasa_code'";
  $result_search = $con->query($sql_search);

  if ($result_search->num_rows > 0) {
    $row = $result_search->fetch_assoc();
    foreach ($row as $key => $val) {
      $$key = $val;
    }
  } else {
    echo '<div class="alert alert-warning">No data found!</div>';
  }
}

// ইনসার্ট ফাংশন
if (isset($_POST['submit'])) {
  $index_id = mysqli_real_escape_string($con, $_POST['index_id']);
  $admissiondate = mysqli_real_escape_string($con, $_POST['admissiondate']);
  $name = mysqli_real_escape_string($con, $_POST['name']);
  $name_en = mysqli_real_escape_string($con, $_POST['name_en']);
  $brday = mysqli_real_escape_string($con, $_POST['brday']);
  $mobile = mysqli_real_escape_string($con, $_POST['mobile']);
  $nid_bid = mysqli_real_escape_string($con, $_POST['nid_bid']);
  $father = mysqli_real_escape_string($con, $_POST['father']);
  $father_en = mysqli_real_escape_string($con, $_POST['father_en']);
  $mother = mysqli_real_escape_string($con, $_POST['mother']);
  $salary = mysqli_real_escape_string($con, $_POST['salary']);
  $gender = mysqli_real_escape_string($con, $_POST['gender']);
  $blood = mysqli_real_escape_string($con, $_POST['blood']);
  $staff_division_idf = mysqli_real_escape_string($con, $_POST['staff_division_idf']);
  $title = mysqli_real_escape_string($con, $_POST['title']);
  $district_idf = mysqli_real_escape_string($con, $_POST['district_id']);
  $thana_idf = mysqli_real_escape_string($con, $_POST['thana_id']);
  $post = mysqli_real_escape_string($con, $_POST['post']);
  $post_en = mysqli_real_escape_string($con, $_POST['post_en']);
  $village = mysqli_real_escape_string($con, $_POST['village']);
  $village_en = mysqli_real_escape_string($con, $_POST['village_en']);
  $p_district_idf = mysqli_real_escape_string($con, $_POST['p_district_id']);
  $p_thana_idf = mysqli_real_escape_string($con, $_POST['p_thana_id']);
  $p_post = mysqli_real_escape_string($con, $_POST['p_post']);
  $p_village = mysqli_real_escape_string($con, $_POST['p_village']);
  $branch = mysqli_real_escape_string($con, $_POST['branch']);
  $teacher_punch_id = (int) mysqli_real_escape_string($con, $_POST['teacher_punch_id']);
  $tc_comment = mysqli_real_escape_string($con, $_POST['tc_comment']);
  $status = mysqli_real_escape_string($con, $_POST['status']);
  $teacher_sr = mysqli_real_escape_string($con, $_POST['teacher_sr']);
  $marital = mysqli_real_escape_string($con, $_POST['marital']);
  $mobile2 = mysqli_real_escape_string($con, $_POST['mobile2']);
  $tc_date = date('Y-m-d', strtotime($_POST['tc_date']));
  $joining_date = date('Y-m-d', strtotime($_POST['joining_date']));
  $educational_qualification = mysqli_real_escape_string($con, $_POST['educational_qualification']);

  // ---------- START: Safe unique teacher_id generation per madrasa ----------
  $con->begin_transaction();

  // lock rows for this madrasa_code
  $sql_last_id = "SELECT MAX(teacher_id) AS last_id FROM teacher WHERE madrasa_code='$madrasa_code' FOR UPDATE";
  $result_last = $con->query($sql_last_id);
  $row_last = $result_last->fetch_assoc();
  $new_teacher_id = ($row_last['last_id'] ?? 0) + 1;

  // ---------- END: Safe ID generation ----------

  $sql_insert = "INSERT INTO teacher (
        teacher_id,
        madrasa_code,
        index_id,
        admissiondate,
        name,
        name_en,
        brday,
        mobile,
        nid_bid,
        father,
        father_en,
        mother,
        salary,
        gender,
        blood,
        staff_division_idf,
        title,
        district_idf,
        thana_idf,
        post,
        post_en,
        village,
        village_en,
        p_district_idf,
        p_thana_idf,
        p_post,
        p_village,
        branch,
        teacher_punch_id,
        status,
        teacher_sr,
        joining_date,
        marital,
        mobile2,
        tc_comment,
        tc_date,
        educational_qualification
    ) VALUES (
        '$new_teacher_id',
        '$madrasa_code',
        '$index_id',
        '$admissiondate',
        '$name',
        '$name_en',
        '$brday',
        '$mobile',
        '$nid_bid',
        '$father',
        '$father_en',
        '$mother',
        '$salary',
        '$gender',
        '$blood',
        '$staff_division_idf',
        '$title',
        '$district_idf',
        '$thana_idf',
        '$post',
        '$post_en',
        '$village',
        '$village_en',
        '$p_district_idf',
        '$p_thana_idf',
        '$p_post',
        '$p_village',
        '$branch',
        '$teacher_punch_id',
        '$status',
        '$teacher_sr',
        '$joining_date',
        '$marital',
        '$mobile2',
        '$tc_comment',
        '$tc_date',
        '$educational_qualification'
    )";

  if ($con->query($sql_insert) === TRUE) {
    $con->commit();
    echo '<div class="alert alert-success">Data inserted successfully! (Teacher ID: ' . $new_teacher_id . ')</div>';
    echo '<meta http-equiv="refresh" content="2">';
  } else {
    $con->rollback();
    echo '<div class="alert alert-danger">Error inserting data: ' . $con->error . '</div>';
  }
}

// আপডেট ফাংশন
if (isset($_POST['update'])) {
  $tea_id_seacrh = mysqli_real_escape_string($con, $_POST['tea_id_seacrh']);
  $teacher_punch_id = (int) $_POST['teacher_punch_id'];
  $admissiondate = mysqli_real_escape_string($con, $_POST['admissiondate']);
  $name = mysqli_real_escape_string($con, $_POST['name']);
  $name_en = mysqli_real_escape_string($con, $_POST['name_en']);
  $brday = mysqli_real_escape_string($con, $_POST['brday']);
  $mobile = mysqli_real_escape_string($con, $_POST['mobile']);
  $nid_bid = mysqli_real_escape_string($con, $_POST['nid_bid']);
  $father = mysqli_real_escape_string($con, $_POST['father']);
  $father_en = mysqli_real_escape_string($con, $_POST['father_en']);
  $mother = mysqli_real_escape_string($con, $_POST['mother']);
  $salary = mysqli_real_escape_string($con, $_POST['salary']);
  $gender = mysqli_real_escape_string($con, $_POST['gender']);
  $blood = mysqli_real_escape_string($con, $_POST['blood']);
  $staff_division_idf = mysqli_real_escape_string($con, $_POST['staff_division_idf']);
  $title = mysqli_real_escape_string($con, $_POST['title']);
  $district_idf = mysqli_real_escape_string($con, $_POST['district_id']);
  $thana_idf = mysqli_real_escape_string($con, $_POST['thana_id']);
  $post = mysqli_real_escape_string($con, $_POST['post']);
  $post_en = mysqli_real_escape_string($con, $_POST['post_en']);
  $village = mysqli_real_escape_string($con, $_POST['village']);
  $village_en = mysqli_real_escape_string($con, $_POST['village_en']);
  $p_district_idf = mysqli_real_escape_string($con, $_POST['p_district_id']);
  $p_thana_idf = mysqli_real_escape_string($con, $_POST['p_thana_id']);
  $p_post = mysqli_real_escape_string($con, $_POST['p_post']);
  $p_village = mysqli_real_escape_string($con, $_POST['p_village']);
  $branch = mysqli_real_escape_string($con, $_POST['branch']);
  $tc_comment = mysqli_real_escape_string($con, $_POST['tc_comment']);
  $tc_date = date('Y-m-d', strtotime($_POST['tc_date']));
  $status = mysqli_real_escape_string($con, $_POST['status']);
  $teacher_sr = mysqli_real_escape_string($con, $_POST['teacher_sr']);
  $marital = mysqli_real_escape_string($con, $_POST['marital']);
  $mobile2 = mysqli_real_escape_string($con, $_POST['mobile2']);
  $joining_date = date("Y-m-d", strtotime($_POST['joining_date']));
  $educational_qualification = mysqli_real_escape_string($con, $_POST['educational_qualification']);

  $sql_update = "UPDATE teacher SET 
        admissiondate='$admissiondate',
        name='$name',
        name_en='$name_en',
        brday='$brday',
        mobile='$mobile',
        nid_bid='$nid_bid',
        father='$father',
        father_en='$father_en',
        mother='$mother',
        salary='$salary',
        gender='$gender',
        blood='$blood',
        staff_division_idf='$staff_division_idf',
        title='$title',
        district_idf='$district_idf',
        thana_idf='$thana_idf',
        post='$post',
        post_en='$post_en',
        village='$village',
        village_en='$village_en',
        p_district_idf='$p_district_idf',
        p_thana_idf='$p_thana_idf',
        p_post='$p_post',
        p_village='$p_village',
        tc_comment='$tc_comment',
        tc_date='$tc_date',
        status='$status',
        teacher_sr='$teacher_sr',
        joining_date='$joining_date',
        marital='$marital',
        mobile2='$mobile2',
        teacher_punch_id='$teacher_punch_id',
        educational_qualification='$educational_qualification'
    WHERE teacher_id='$tea_id_seacrh' AND madrasa_code='$madrasa_code'";

  if ($con->query($sql_update) === TRUE) {
    echo '<div class="alert alert-success">Data updated successfully!</div>';
    echo '<meta http-equiv="refresh" content="2">';
  } else {
    echo '<div class="alert alert-danger">Error updating data: ' . $con->error . '</div>';
  }
}
?>

<br>
<div class="row">
  <div class="col-md-8 offset-md-2">
    <form action="" method="post">
      <div class="input-group">
        <input type="text" class="form-control" name="tea_id_seacrh"
          value="<?php echo isset($tea_id_seacrh) ? $tea_id_seacrh : ''; ?>" placeholder="আইডি">
        <div class="input-group-append">
          <button type="submit" name="search" class="btn btn-sm btn-warning">
            <i class="fa fa-search">খোজ করুন</i>
          </button>
        </div>
      </div>
    </form>
  </div>
</div> <br>


<!DOCTYPE html>
<html lang="bn">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ফরম</title>
  <!-- Bootstrap 4 CSS -->
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

  <script>


    $(document).ready(function () {
      $('#stu_roll').focus(); // সরাসরি ক্লাস রোল ইনপুটে ফোকাস দিন
    });

  </script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    $(document).ready(function () {
      $('[tabindex]').on('keydown', function (e) {
        if (e.which == 13) { // Enter key
          e.preventDefault(); // ডিফল্ট বিহেভিয়ার বন্ধ করুন

          // যদি বর্তমান ইনপুট ফিল্ড ভ্যালিড না হয়, ফোকাস রাখুন
          if (!this.checkValidity()) {
            this.reportValidity(); // ভ্যালিডেশন মেসেজ দেখান
            return;
          }

          // tabindex সহ সমস্ত ইনপুট ফিল্ড খুঁজুন এবং tabindex অনুযায়ী সাজান
          var fields = $('[tabindex]').sort(function (a, b) {
            return $(a).attr('tabindex') - $(b).attr('tabindex');
          });

          var currentIndex = fields.index(this);

          // পরবর্তী ফিল্ডে যাওয়া (tabindex অনুযায়ী)
          for (var i = currentIndex + 1; i < fields.length; i++) {
            var nextField = fields.eq(i);

            // Radio বা Checkbox চেক করার জন্য শর্ত
            if (nextField.is(':radio, :checkbox')) {
              if (!nextField.is(':checked')) { // যদি Radio বা Checkbox চেক না থাকে
                nextField.focus();
                return;
              }
            }
            // Select ফিল্ড চেক করা
            else if (nextField.is('select')) {
              if (!nextField.val() || nextField.val() === '') { // যদি কোনো অপশন সিলেক্ট না থাকে
                nextField.focus();
                return;
              }
            }
            // Text, Textarea, এবং অন্যান্য ফিল্ড চেক
            else if ((nextField.prop('required') && !nextField.val()) || nextField.val() === '') {
              nextField.focus(); // ফাঁকা ফিল্ডে ফোকাস
              return;
            }
          }

          // যদি সমস্ত ফিল্ড পূর্ণ থাকে, তখন কিছু না করে থেমে থাকবে
        }
      });
    });
  </script>





  <?php $sql_last = $con->query("SELECT name, teacher_id FROM teacher where madrasa_code='$madrasa_code' order by teacher_id desc limit 1 ");
  $last_student = mysqli_fetch_assoc($sql_last);
  echo '<h3 style="text-align: center; min-height: 35px; background-color: #ddd; padding: 5px; font-family: bangla; "><span style="color: blue;" >সর্বশেষ: ' . $last_student['teacher_id'] . '- ' . $last_student['name'] . ' </span></h3>';
  ?>




  <style>
    .red_color {
      color: red;
    }
  </style>


  <form method="POST" action="" id="myForm"
    style="border: 3px solid #f40404; border-radius: 10px; padding: 20px; box-sizing: border-box;">
    <div style="border: 2px solid #23af7f; border-radius: 10px; padding: 20px; margin-bottom: 20px;">
      <div class="row">
        <!-- ক্লাস রোল -->

        <div class="form-group col-md-4">
          <label for="classRoll">পাঞ্চ আইডি</label>
          <input type="number" id="index_id" name="teacher_punch_id" class="form-control" autocomplete="off"
            placeholder="পাঞ্চ আইডি" value="<?php echo isset($teacher_punch_id) ? $teacher_punch_id : ''; ?>" autofocus>
        </div>

        <!-- সিরিয়াল-->
        <div class="col-md-4">
          <div class="form-group">
            <label for="class_id">সিরিয়াল</label>
            <input type="number" id="teacher_sr" name="teacher_sr" class="form-control"
              value="<?php echo isset($teacher_sr) ? $teacher_sr : ''; ?>">
            <input type="hidden" id="admissiondate" name="admissiondate" class="form-control"
              value="<?php echo date("Y-d-m"); ?>">
          </div>
        </div>
        <?php
        // সর্বশেষ `teacher_id` বের করার SQL কোয়েরি
        $sql_id = mysqli_query($con, "SELECT teacher_punch_id FROM teacher ORDER BY teacher_punch_id DESC LIMIT 1");

        // সর্বশেষ `id` থেকে মান বের করা
        if (mysqli_num_rows($sql_id) > 0) {
          $row = mysqli_fetch_assoc($sql_id);
          $last_id = $row['teacher_punch_id'] + 1; // সর্বশেষ id-এর পরবর্তী মান
        } else {
          $last_id = 100001; // যদি ডাটা না থাকে, তাহলে 100001 থেকে শুরু হবে
        }
        ?>

        <!-- আইডি ইনপুট ফিল্ড -->
        <div class="col-md-4">
          <div class="form-group">
            <label for="section_id">আইডি</label>
            <input type="text" id="id_admission" name="id_admission" class="form-control"
              value="<?php echo $last_id; ?>" readonly>
          </div>
        </div>



      </div>
      <div class="row" style="display: flex; flex-wrap: wrap;">
        <!-- প্রথম কলাম -->
        <div class="col-md-4"
          style="background-color: #e6dfeb; border-radius: 5px; padding: 15px; box-sizing: border-box; margin-bottom: 15px;">

          <div class="form-group">
            <label for="name">নাম (বাংলা) <span style="color: red;">*</span></label>
            <input type="text" class="form-control" id="name" name="name" tabindex="2" placeholder="নাম বাংলা" required
              value="<?php echo isset($name) ? $name : ''; ?>">

          </div>




          <div class="form-group">
            <label for="brday">জন্ম তারিখ</label>
            <input type="date" class="form-control" id="brday" name="brday" tabindex="3"
              value="<?php echo isset($brday) ? $brday : ''; ?>">
          </div>


          <div class="form-group">
            <label for="nid_bid">NID/BID</label>
            <input type="text" class="form-control" id="nid_bid" name="nid_bid" placeholder="NID" tabindex="4"
              value="<?php echo isset($nid_bid) ? $nid_bid : ''; ?>">

          </div>


          <div class="form-group">
            <label for="brday">মোবাইল</label>
            <input type="number" class="form-control" id="mobile" name="mobile" tabindex="3"
              value="<?php echo isset($mobile) ? $mobile : ''; ?>">
          </div>
        </div>



        <!-- দ্বিতীয় কলাম -->
        <div class="col-md-4"
          style="background-color: #dfebdf; border-radius: 5px; padding: 15px; box-sizing: border-box; margin-bottom: 15px;">


          <div class="form-group">
            <label for="father">পিতার নাম (বাংলা)</label>
            <input type="text" class="form-control" id="father" name="father" placeholder="পিতার নাম বাংলা" tabindex="5"
              value="<?php echo isset($father) ? $father : ''; ?>">
          </div>




          <div class="form-group">
            <label for="mother">মাতার নাম (বাংলা)</label>
            <input type="text" class="form-control" id="mother" name="mother" placeholder="মাতার নাম বাংলা"
              tabindex="20" value="<?php echo isset($mother) ? $mother : ''; ?>">
          </div>


          <div class="form-group">
            <label for="mother">বেতন</label>
            <input type="text" class="form-control" id="salary" name="salary" placeholder="বেতন" tabindex="20"
              value="<?php echo isset($salary) ? $salary : ''; ?>">
          </div>


          <div class="form-group">
            <label for="gender">জেন্ডার <span style="color: red;"></span></label>
            <div style="margin-top: 10px; display: flex; align-items: center; gap: 20px;">
              <div class="icheck-primary d-inline">
                <input type="radio" id="male" name="gender" value="1" required tabindex="25" <?php echo (isset($gender) && $gender == 1) ? 'checked' : ''; ?>>
                <label for="male">পুরুষ</label>
              </div>
              <div class="icheck-primary d-inline">
                <input type="radio" id="female" name="gender" value="0" required <?php echo (isset($gender) && $gender == 0) ? 'checked' : ''; ?>>
                <label for="female">মহিলা</label>
              </div>
            </div>
          </div>


          <!-- Blood Group Section -->




        </div>

        <!-- তৃতীয় কলাম -->
        <div class="col-md-4"
          style="background-color: #ebdfdf; border-radius: 5px; padding: 15px; box-sizing: border-box; margin-bottom: 15px;">
          <div class="form-group">
            <label for="teacher_img">ছবি</label>
            <input type="file" class="form-control" id="teacher_img" name="teacher_img" accept="image/*"
              capture="environment" tabindex="20">
          </div>

          <div class="form-group">
            <label for="staff_division_idf">বিভাগ (শাখা)</label>
            <select class="form-control" id="staff_division_idf" name="staff_division_idf" data-parsley-trigger="keyup"
              tabindex="80">
              <option value="">সিলেক্ট করুন</option>
              <?php
              $result = mysqli_query($con, "SELECT `cid_no`, `system_subject_name` FROM system_setup WHERE system_id = 21 AND madrasa_code='$madrasa_code' ORDER BY sl2 ASC");
              while ($row = mysqli_fetch_array($result)) {
                $selected = (isset($staff_division_idf) && $row['cid_no'] == $staff_division_idf) ? 'selected' : '';
                ?>
                <option value="<?php echo $row['cid_no']; ?>" <?php echo $selected; ?>>
                  <?php echo $row["system_subject_name"]; ?>
                </option>
              <?php } ?>
            </select>
          </div>


          <div class="form-group">
            <label for="teacher_img">পদবী</label>
            <select class="form-control" id="title" name="title" data-parsley-trigger="keyup" tabindex="80">
              <option value="">সিলেক্ট করুন</option>
              <?php
              $result = mysqli_query($con, "SELECT `cid_no`, `system_subject_name`  FROM system_setup WHERE system_id = 13 AND madrasa_code='$madrasa_code' ORDER BY sl2 ASC");
              while ($row = mysqli_fetch_array($result)) {
                $selected = ($row['cid_no'] == $title) ? 'selected' : '';
                ?>
                <option value="<?php echo $row['cid_no']; ?>" <?php echo $selected; ?>>
                  <?php echo $row["system_subject_name"]; ?>
                </option>
              <?php } ?>
            </select>
          </div>

          <div class="form-group">
            <label for="bloodGroup">ব্লাড গ্রুপ</label>
            <select id="blood" name="blood" class="form-control" tabindex="26">
              <option value="">ব্লাড গ্রুপ নির্বাচন করুন</option>
              <option value="A+" <?php echo ($blood == 'A+') ? 'selected' : ''; ?>>A+</option>
              <option value="A-" <?php echo ($blood == 'A-') ? 'selected' : ''; ?>>A-</option>
              <option value="B+" <?php echo ($blood == 'B+') ? 'selected' : ''; ?>>B+</option>
              <option value="B-" <?php echo ($blood == 'B-') ? 'selected' : ''; ?>>B-</option>
              <option value="AB+" <?php echo ($blood == 'AB+') ? 'selected' : ''; ?>>AB+</option>
              <option value="AB-" <?php echo ($blood == 'AB-') ? 'selected' : ''; ?>>AB-</option>
              <option value="O+" <?php echo ($blood == 'O+') ? 'selected' : ''; ?>>O+</option>
              <option value="O-" <?php echo ($blood == 'O-') ? 'selected' : ''; ?>>O-</option>
            </select>
          </div>
        </div>

        <div class="col-md-4">
          <div class="form-group">
            <label for="marital_status">বৈবাহিক অবস্থা</label>
            <select class="form-control" id="marital" name="marital">
              <option value="">-- নির্বাচন করুন --</option>
              <option value="বিবাহিত" <?php echo (isset($marital) && $marital == 'বিবাহিত') ? 'selected' : ''; ?>>বিবাহিত
              </option>
              <option value="অবিবাহিত" <?php echo (isset($marital) && $marital == 'অবিবাহিত') ? 'selected' : ''; ?>>
                অবিবাহিত</option>
            </select>
          </div>
        </div>

        <div class="col-md-4">
          <div class="form-group">
            <label for="tc_date">যোগদান তারিখ</label>
            <input type="date" class="form-control" id="joining_date" name="joining_date"
              value="<?php echo isset($joining_date) ? $joining_date : ''; ?>">
          </div>
        </div>

        <div class="col-md-4">
          <div class="form-group">
            <label for="guardian_mobile">অভিভাবকের মোবাইল নম্বর</label>
            <input type="number" class="form-control" id="mobile2" name="mobile2"
              placeholder="অভিভাবকের মোবাইল নম্বর লিখুন" value="<?php echo isset($mobile2) ? $mobile2 : ''; ?>">
          </div>
        </div>

        <div class="col-md-4">
          <div class="form-group">
            <label for="educational_qualification">শিক্ষাগত যোগ্যতা</label>
            <input type="text" class="form-control" id="educational_qualification" name="educational_qualification"
              placeholder="শিক্ষাগত যোগ্যতা লিখুন"
              value="<?php echo isset($educational_qualification) ? $educational_qualification : ''; ?>">
          </div>
        </div>
      </div>
    </div>

    <!-- Permanent Address Section -->
    <div style="border: 2px solid #23af7f; border-radius: 10px; padding: 20px; margin-bottom: 20px;">
      <!-- Permanent Address Header -->
      <div class="bg-success clearfix" style="text-align: center; padding: 2px; font-size: 20px;">স্থায়ী ঠিকানা</div>

      <!-- Permanent Address Form -->
      <div class="row">
        <div class="col-md-3">
          <div class="form-group">
            <label for="district_idf">জেলা <span style="color: red;">*</span></label>
            <select class="form-control" name="district_id" id="district_id" tabindex="30" required>
              <option value="">জেলা সিলেক্ট করুন</option>
              <?php
              $result = mysqli_query($con, "SELECT * FROM `district` ORDER BY sl2 ASC");
              while ($row_district = mysqli_fetch_assoc($result)) {
                $selected = ($row_district['district_id'] == $district_idf) ? 'selected' : '';
                ?>
                <option value="<?php echo $row_district['district_id']; ?>" <?php echo $selected; ?>>
                  <?php echo $row_district['district_name']; ?>
                </option>
              <?php } ?>
            </select>
          </div>
        </div>

        <div class="col-md-3">
          <div class="form-group">
            <label for="thana_idf">থানা <span style="color: red;">*</span></label>
            <select name="thana_id" class="form-control" id="thana_id" tabindex="31" required>
              <option value="">থানা সিলেক্ট করুন</option>
              <?php
              $result = mysqli_query($con, "SELECT * FROM `thana` ORDER BY thana_name ASC");
              while ($row_thana = mysqli_fetch_assoc($result)) {
                $selected = ($row_thana['thana_id'] == $thana_idf) ? 'selected' : '';
                ?>
                <option value="<?php echo $row_thana['thana_id']; ?>" <?php echo $selected; ?>>
                  <?php echo $row_thana['thana_name']; ?>
                </option>
              <?php } ?>
            </select>
          </div>
        </div>

        <div class="col-md-3">
          <div class="form-group">
            <label for="post">পোস্ট <span style="color: red;">*</span></label>
            <input type="text" class="form-control" id="post" name="post" placeholder="পোস্ট" tabindex="32"
              value="<?php echo isset($post) ? $post : ''; ?>" required>
          </div>
        </div>

        <div class="col-md-3">
          <div class="form-group">
            <label for="village">গ্রাম <span style="color: red;">*</span></label>
            <input type="text" class="form-control" id="village" name="village" placeholder="গ্রাম" tabindex="33"
              value="<?php echo isset($village) ? $village : ''; ?>" required>
          </div>
        </div>
      </div>

      <!-- Current Address Header -->
      <h3 style="text-align: center; background-color: #1c656096; color:red; font-family:bangla; padding: 5px;">
        বর্তমান ঠিকানা
        <div style="display: inline-block; margin-right: 10px;">
          <div class="icheck-primary d-inline">
            <input type="checkbox" id="checkboxPrimary1" tabindex="34">
            <label for="checkboxPrimary1">একই ঠিকানা</label>
          </div>
        </div>
      </h3>

      <!-- Current Address Form -->
      <div class="row">
        <div class="col-md-3">
          <div class="form-group">
            <label for="p_district_idf">জেলা</label>
            <select class="form-control" name="p_district_id" id="p_district_idf" tabindex="50">
              <option value="">জেলা সিলেক্ট করুন</option>
              <?php
              $result = mysqli_query($con, "SELECT * FROM `district` ORDER BY sl2 ASC");
              while ($row_district = mysqli_fetch_assoc($result)) {
                $selected = ($row_district['district_id'] == $p_district_idf) ? 'selected' : '';
                ?>
                <option value="<?php echo $row_district['district_id']; ?>" <?php echo $selected; ?>>
                  <?php echo $row_district['district_name']; ?>
                </option>
              <?php } ?>
            </select>
          </div>
        </div>

        <div class="col-md-3">
          <div class="form-group">
            <label for="p_thana_idf">থানা</label>
            <select name="p_thana_id" class="form-control" id="p_thana_id" tabindex="51">
              <option value="">থানা সিলেক্ট করুন</option>
              <?php
              $result = mysqli_query($con, "SELECT * FROM `thana` ORDER BY thana_name ASC");
              while ($row_thana = mysqli_fetch_assoc($result)) {
                $selected = ($row_thana['thana_id'] == $p_thana_idf) ? 'selected' : '';
                ?>
                <option value="<?php echo $row_thana['thana_id']; ?>" <?php echo $selected; ?>>
                  <?php echo $row_thana['thana_name']; ?>
                </option>
              <?php } ?>
            </select>
          </div>
        </div>

        <div class="col-md-3">
          <div class="form-group">
            <label for="p_post">পোস্ট</label>
            <input type="text" class="form-control" id="p_post" name="p_post" placeholder="পোস্ট"
              value="<?php echo isset($p_post) ? $p_post : ''; ?>">
          </div>
        </div>

        <div class="col-md-3">
          <div class="form-group">
            <label for="p_village">গ্রাম</label>
            <input type="text" class="form-control" id="p_village" name="p_village" placeholder="গ্রাম"
              value="<?php echo isset($p_village) ? $p_village : ''; ?>">
          </div>
        </div>
      </div>
    </div>

    <!-- Comments and Status Section -->
    <div style="border: 2px solid #6c757d; border-radius: 10px; padding: 20px; margin-bottom: 20px;">
      <div class="row">
        <div class="col-md-4">
          <div class="form-group">
            <label for="leave_reason">বিদায়ের কারণ</label>
            <textarea class="form-control" id="tc_comment" name="tc_comment" rows="2"
              placeholder="বিদায়ের কারণ লিখুন..."><?php echo isset($tc_comment) ? $tc_comment : ''; ?></textarea>
          </div>
        </div>

        <div class="col-md-4">
          <div class="form-group">
            <label for="leave_date">বিদায়ের তারিখ</label>
            <input type="date" class="form-control" id="tc_date" name="tc_date"
              value="<?php echo isset($tc_date) ? $tc_date : ''; ?>">
          </div>
        </div>

        <div class="col-md-4">
          <div class="form-group">
            <label>স্ট্যাটাস</label>
            <div class="form-check">
              <input class="form-check-input" type="radio" name="status" id="status_active" value="0" <?php echo (isset($status) && $status == 0) ? 'checked' : ''; ?>>
              <label class="form-check-label" for="status_active">বন্ধ</label>
            </div>

            <div class="form-check">
              <input class="form-check-input" type="radio" name="status" id="status_inactive" value="1" <?php echo (!isset($status) || $status == 1) ? 'checked' : ''; ?>>
              <label class="form-check-label" for="status_inactive">চালু</label>
            </div>


          </div>
        </div>
      </div>
    </div>


    <br>



    <div class="text-center">
      <?php if (isset($tea_id_seacrh)) { ?>
        <input type="hidden" name="tea_id_seacrh" value="<?php echo $tea_id_seacrh; ?>">
        <button type="submit" name="update" class="btn btn-primary"><i class="fas fa-save"></i> আপডেট করুন</button>
      <?php } else { ?>
        <button type="submit" name="submit" class="btn btn-primary" tabindex="86"><i class="fas fa-save"></i> সংরক্ষণ
          করুন</button>
      <?php } ?>
    </div>

    <script>
      $(document).ready(function () {
        $('#tea_id_seacrh').focus(); // সরাসরি আইডি ইনপুটে ফোকাস দিন
      });
    </script>


    <?php
    // সর্বশেষ ইনসার্ট হওয়া student id পেতে SQL কোয়েরি
    $sql = "SELECT id FROM student ORDER BY id DESC LIMIT 1";
    $result = $con->query($sql);

    $last_id = 0;
    $encoded_last_id = '';
    if ($result->num_rows > 0) {
      $row = $result->fetch_assoc();
      $last_id = $row['id'];
      $encoded_last_id = base64_encode($last_id); // id এনকোড করা হচ্ছে
    }

    // ডাটাবেজ সংযোগ বন্ধ করুন
    $con->close();
    ?>



    <div class="container mt-5">
      <div class="row">
        <div class="col text-center">
          <!-- ইনপুট ফিল্ড -->
          <label for="studentId">ফরম প্রিন্ট আইডি:</label>
          <input type="number" id="studentId" class="form-control w-25 d-inline" placeholder="ID লিখুন">

          <!-- "ফরম প্রিণ্ট" বাটন -->
          <a href="#" id="printFormBtn" class="btn btn-primary btn-lg mx-2">ফরম প্রিণ্ট</a>

          <!-- "রশিদ প্রিণ্ট" বাটন -->
          <a href="receipt_print.php" class="btn btn-success btn-lg mx-2">রশিদ প্রিণ্ট</a>
        </div>
      </div>
    </div>

    <script>
      // ফর্ম প্রিণ্ট বাটনে ক্লিক করা হলে
      document.getElementById('printFormBtn').addEventListener('click', function () {
        var studentId = document.getElementById('studentId').value;

        if (studentId) {
          // ইউজার যদি আইডি দেয়, তা এনকোড করে পাঠানো হবে
          var encodedId = btoa(studentId); // JavaScript-এর btoa() দিয়ে Base64 encode
          window.open("male/admission/admission_form_print.php?id=" + encodedId, "_blank");
        } else {
          // যদি আইডি না থাকে, সর্বশেষ এনকোড করা আইডি পাঠানো হবে
          window.open("male/admission/admission_form_bhorti_print.php?id=<?php echo $encoded_last_id; ?>", "_blank");
        }
      });
    </script>

    <script>
      document.getElementById("myForm").addEventListener("submit", function (event) {
        const motherMobile = document.getElementById("mother_mobile");
        const motherError = document.getElementById("mother_error");
        const mobileValue = motherMobile.value.trim();
        let isValid = true;

        // চেক করুন মোবাইল নম্বর ১১ ডিজিট কিনা
        if (mobileValue && (mobileValue.length !== 11 || isNaN(mobileValue))) {
          motherError.style.display = "block";
          motherMobile.style.borderColor = "red";
          isValid = false;
        } else {
          motherError.style.display = "none";
          motherMobile.style.borderColor = "";
        }

        // যদি বৈধ না হয় তাহলে সাবমিট বন্ধ করুন
        if (!isValid) {
          event.preventDefault();
        }
      });
    </script>



    <!-- Bootstrap 4 JS, Popper.js, and jQuery -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>


</body>

</html>



<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
  // বিভাগ নির্বাচন পরিবর্তন হলে ক্লাস লোড হবে
  $("#division_idf").change(function () {
    var division_id = $(this).val();
    if (division_id) {
      $.ajax({
        url: "ajax/fetch_classes.php", // PHP ফাইল যেটি ক্লাসের ডেটা ফেরত দেবে
        method: "GET",
        data: { division_id: division_id },
        success: function (data) {
          // ক্লাস ড্রপডাউন আপডেট করা হবে
          $("#state-dropdown").html('<option value="">সিলেক্ট করুন</option>' + data);
        }
      });
    } else {
      $("#state-dropdown").html('<option value="">সিলেক্ট করুন</option>');
    }

    // গ্রুপ ড্রপডাউন আপডেট
    $("#section-dropdown").html('<option value="">সিলেক্ট করুন</option>');
  });

  // ক্লাস নির্বাচন পরিবর্তন হলে গ্রুপ লোড হবে
  $("#state-dropdown").change(function () {
    var class_id = $(this).val();
    var division_id = $("#division_idf").val();
    if (class_id) {
      $.ajax({
        url: "ajax/fetch_sections.php", // PHP ফাইল যেটি গ্রুপের ডেটা ফেরত দেবে
        method: "GET",
        data: { class_id: class_id, division_id: division_id },
        success: function (data) {
          // গ্রুপ ড্রপডাউন আপডেট করা হবে
          $("#section-dropdown").html('<option value="">সিলেক্ট করুন</option>' + data);
        }
      });
    } else {
      $("#section-dropdown").html('<option value="">সিলেক্ট করুন</option>');
    }
  });





  // ক্লাস নির্বাচন পরিবর্তন হলে গ্রুপ লোড হবে এবং ভর্তি ফি, মাসিক বেতন, বিদ্যুৎ বিল অটো ফিল হবে
  $("#state-dropdown").change(function () {
    var class_id = $(this).val();
    var division_id = $("#division_idf").val();
    if (class_id) {
      $.ajax({
        url: "ajax/fetch_class_details.php", // PHP ফাইল যেটি ক্লাসের বিস্তারিত ডেটা ফেরত দেবে
        method: "GET",
        data: { class_id: class_id },
        success: function (data) {
          var result = JSON.parse(data); // JSON ডাটা পার্স করা
          if (result.status == 'success') {
            // ভর্তি ফি, মাসিক বেতন এবং বিদ্যুৎ বিল অটো ফিল
            $("#admission_fee").val(result.admission_fee);
            $("#monthly_salary").val(result.m_salary);
            $("#electricity_bill").val(result.electricity_bill);
          } else {
            alert("ক্লাসের তথ্য পাওয়া যায়নি!");
          }
        }
      });
    } else {
      // ক্লাস সিলেক্ট না হলে ইনপুট ফিল্ডগুলো খালি রাখুন
      $("#admission_fee").val('');
      $("#monthly_salary").val('');
      $("#electricity_bill").val('');
    }

    // গ্রুপ ড্রপডাউন আপডেট
    $("#section-dropdown").html('<option value="">সিলেক্ট করুন</option>');
  });
</script>



<script>
  function updateGuardianInfo() {
    const relationId = document.getElementById('relationship').value;

    // পিতা এবং মাতা সম্পর্কের আইডি (আপনার ডাটাবেস থেকে প্রাপ্ত)
    const fatherId = 1; // পিতার আইডি
    const motherId = 2; // মাতার আইডি

    // গার্ডিয়ান ফিল্ডগুলোকে রিসেট করা প্রথমে
    document.getElementById('guardianName').value = '';
    document.getElementById('guardian_id').value = '';
    document.getElementById('guardian_mobile').value = '';

    if (relationId == fatherId) {
      // পিতার তথ্য গার্ডিয়ানের ক্ষেত্রে পূর্ণ করা
      document.getElementById('guardianName').value = document.getElementById('father').value;
      document.getElementById('guardian_id').value = document.getElementById('father_nid').value;
      document.getElementById('guardian_mobile').value = document.getElementById('father_mobile').value;
    } else if (relationId == motherId) {
      // মাতার তথ্য গার্ডিয়ানের ক্ষেত্রে পূর্ণ করা
      document.getElementById('guardianName').value = document.getElementById('mother').value;
      document.getElementById('guardian_id').value = document.getElementById('mother_nid').value;
      document.getElementById('guardian_mobile').value = document.getElementById('mother_mobile').value;
    }
  }

</script>


<script>
  $(document).ready(function () {
    $('#checkboxPrimary1').change(function () {
      if ($(this).is(':checked')) {
        $('#p_village').val($('#village').val());
        $('#p_post').val($('#post').val());
        $('#p_thana_id').html($('#thana_id').html()).val($('#thana_id').val());
        $('#p_district_idf').val($('#district_id').val());
      } else {
        $('#p_village').val('');
        $('#p_post').val('');
        $('#p_thana_id').html('<option value="">থানা সিলেক্ট করুন</option>');
        $('#p_district_idf').val('');
      }
    });

    // Load Thana dynamically when District changes
    $('#district_id').change(function () {
      const districtId = $(this).val();
      if (districtId) {
        $.ajax({
          url: 'get_thana.php',
          type: 'POST',
          data: { district_id: districtId },
          success: function (response) {
            $('#thana_id').html(response);
          }
        });
      } else {
        $('#thana_id').html('<option value="">থানা সিলেক্ট করুন</option>');
      }
    });

    $('#p_district_idf').change(function () {
      const districtId = $(this).val();
      if (districtId) {
        $.ajax({
          url: 'get_thana.php',
          type: 'POST',
          data: { district_id: districtId },
          success: function (response) {
            $('#p_thana_id').html(response);
          }
        });
      } else {
        $('#p_thana_id').html('<option value="">থানা সিলেক্ট করুন</option>');
      }
    });
  });

</script>