<?php
$tt_page_info = array(
  'Page_Info' =>   array(
    'Title' => 'ব্যাক্তিগত তথ্য সম্পাদনা',
    'Description' => '',
    'Keyword' => '',
  ),
  'Social_og' => array(
    'Image' => '',
    'Type' => 'website',
    'URL' => 'account/personal-info/',
  ),
);

if ($the_writer['UpdateProfile'] == 'active') {
  $noPermissionHtml = '';

  $error = false;

  // Update Information
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {

      // Check if CSRF token is valid
      $csrf_token = $_POST['csrf_token'] ?? '';

      if (!verifyCSRFToken($csrf_token)) {
        $error = true;
      } else {

        $target_dir = "uploads/public_files/";

        // Initialize variables with old file names
        $photo_file = $the_writer['PhotoFile'];
        $nid_file = $the_writer['NidFile'];
        $cv_file = $the_writer['CvFile'];

        // Initialize error array
        $upload_errors = [];

        // Set max file size (2MB = 2 * 1024 * 1024 bytes)
        $max_file_size = 2 * 1024 * 1024;

        // Handle PhotoFile (only image)
        if (isset($_FILES['PhotoFile']) && $_FILES['PhotoFile']['error'] == 0) {
            if ($_FILES['PhotoFile']['size'] > $max_file_size) {
                $upload_errors[] = "Photo file is too large. Maximum size allowed is 2MB.";
            } else {
                $imageFileType = strtolower(pathinfo($_FILES["PhotoFile"]["name"], PATHINFO_EXTENSION));
                $allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

                $check = getimagesize($_FILES["PhotoFile"]["tmp_name"]);
                if ($check !== false && in_array($imageFileType, $allowed_types)) {
                    // Delete old file if exists
                    if (!empty($photo_file) && file_exists($target_dir . $photo_file)) {
                        unlink($target_dir . $photo_file);
                    }

                    // Upload new file
                    $newPhotoName = uniqid('photo_') . '.' . $imageFileType;
                    $target_file = $target_dir . $newPhotoName;
                    if (move_uploaded_file($_FILES["PhotoFile"]["tmp_name"], $target_file)) {
                        $photo_file = $newPhotoName;
                    } else {
                        $upload_errors[] = "Failed to upload photo file.";
                    }
                } else {
                    $upload_errors[] = "Invalid photo file type.";
                }
            }
        }

        // Handle NidFile (image or pdf)
        if (isset($_FILES['NidFile']) && $_FILES['NidFile']['error'] == 0) {
            if ($_FILES['NidFile']['size'] > $max_file_size) {
                $upload_errors[] = "NID file is too large. Maximum size allowed is 2MB.";
            } else {
                $nidFileType = strtolower(pathinfo($_FILES["NidFile"]["name"], PATHINFO_EXTENSION));
                $allowed_types = ['jpg', 'jpeg', 'png', 'pdf'];

                if (in_array($nidFileType, $allowed_types)) {
                    // Delete old file if exists
                    if (!empty($nid_file) && file_exists($target_dir . $nid_file)) {
                        unlink($target_dir . $nid_file);
                    }

                    // Upload new file
                    $newNidName = uniqid('nid_') . '.' . $nidFileType;
                    $target_file = $target_dir . $newNidName;
                    if (move_uploaded_file($_FILES["NidFile"]["tmp_name"], $target_file)) {
                        $nid_file = $newNidName;
                    } else {
                        $upload_errors[] = "Failed to upload NID file.";
                    }
                } else {
                    $upload_errors[] = "Invalid NID file type.";
                }
            }
        }

        // Handle CvFile (image or pdf)
        if (isset($_FILES['CvFile']) && $_FILES['CvFile']['error'] == 0) {
            if ($_FILES['CvFile']['size'] > $max_file_size) {
                $upload_errors[] = "CV file is too large. Maximum size allowed is 2MB.";
            } else {
                $cvFileType = strtolower(pathinfo($_FILES["CvFile"]["name"], PATHINFO_EXTENSION));
                $allowed_types = ['jpg', 'jpeg', 'png', 'pdf'];

                if (in_array($cvFileType, $allowed_types)) {
                    // Delete old file if exists
                    if (!empty($cv_file) && file_exists($target_dir . $cv_file)) {
                        unlink($target_dir . $cv_file);
                    }

                    // Upload new file
                    $newCvName = uniqid('cv_') . '.' . $cvFileType;
                    $target_file = $target_dir . $newCvName;
                    if (move_uploaded_file($_FILES["CvFile"]["tmp_name"], $target_file)) {
                        $cv_file = $newCvName;
                    } else {
                        $upload_errors[] = "Failed to upload CV file.";
                    }
                } else {
                    $upload_errors[] = "Invalid CV file type.";
                }
            }
        }

        $update_info = UpdateData('tt_accounts', 'UserID', $the_writer_id, array(
          "UserNameEN" => htmlentities($_POST['UserNameEN'], ENT_QUOTES, 'utf-8'),
          "UserFather" => htmlentities($_POST['UserFather'], ENT_QUOTES, 'utf-8'),
          "UserMother" => htmlentities($_POST['UserMother'], ENT_QUOTES, 'utf-8'),
          "UserNID" => htmlentities($_POST['UserNID'], ENT_QUOTES, 'utf-8'),
          "UserGender" => htmlentities($_POST['UserGender'], ENT_QUOTES, 'utf-8'),
          "UserDOB" => htmlentities($_POST['UserDOB'], ENT_QUOTES, 'utf-8'),
          "UserProfession" => htmlentities($_POST['UserProfession'], ENT_QUOTES, 'utf-8'),
          "UserExperience" => htmlentities($_POST['UserExperience'], ENT_QUOTES, 'utf-8'),
          "UserTshirtSize" => htmlentities($_POST['UserTshirtSize'], ENT_QUOTES, 'utf-8'),

          "CvFile" => $cv_file,
          "NidFile" => $nid_file,
          "PhotoFile" => $photo_file,
          "UserLastUpdate" => $the_time,
        ));


        $updates_changes = ""; // Initialize variable to store changes

        // Check each field and store changes
        if ($cv_file != $the_writer['CvFile']) {
            $updates_changes .= "User CV Updated <br>";
        }

        if ($nid_file != $the_writer['NidFile']) {
            $updates_changes .= "User NID Updated <br>";
        }


        if ($photo_file != $the_writer['PhotoFile']) {
            $updates_changes .= "User Photo Updated <br>";
        }

        if (htmlentities($_POST['UserNameEN'], ENT_QUOTES, 'utf-8') != $the_writer['UserNameEN']) {
            $updates_changes .= "User Name:<b> " . htmlentities($the_writer['UserNameEN'], ENT_QUOTES, 'utf-8') .
                                "</b> <i class='bi bi-arrow-right'></i> <b>" . htmlentities($_POST['UserNameEN'], ENT_QUOTES, 'utf-8') . "</b><br>";
        }

        if (htmlentities($_POST['UserFather'], ENT_QUOTES, 'utf-8') != $the_writer['UserFather']) {
            $updates_changes .= "Father's Name: <b>" . htmlentities($the_writer['UserFather'], ENT_QUOTES, 'utf-8') .
                                "</b> <i class='bi bi-arrow-right'></i> <b> " . htmlentities($_POST['UserFather'], ENT_QUOTES, 'utf-8') . "</b><br>";
        }

        if (htmlentities($_POST['UserMother'], ENT_QUOTES, 'utf-8') != $the_writer['UserMother']) {
            $updates_changes .= "Mother's Name:<b> " . htmlentities($the_writer['UserMother'], ENT_QUOTES, 'utf-8') .
                                "</b> <i class='bi bi-arrow-right'></i> <b>" . htmlentities($_POST['UserMother'], ENT_QUOTES, 'utf-8') . "</b><br>";
        }

        if (htmlentities($_POST['UserNID'], ENT_QUOTES, 'utf-8') != $the_writer['UserNID']) {
            $updates_changes .= "NID: <b>" . htmlentities($the_writer['UserNID'], ENT_QUOTES, 'utf-8') .
                                "</b> <i class='bi bi-arrow-right'></i> <b>" . htmlentities($_POST['UserNID'], ENT_QUOTES, 'utf-8') . "</b><br>";
        }

        if (htmlentities($_POST['UserGender'], ENT_QUOTES, 'utf-8') != $the_writer['UserGender']) {
            $updates_changes .= "Gender:<b> " . htmlentities($the_writer['UserGender'], ENT_QUOTES, 'utf-8') .
                                " </b> <i class='bi bi-arrow-right'></i> <b>" . htmlentities($_POST['UserGender'], ENT_QUOTES, 'utf-8') . "</b><br>";
        }

        if (htmlentities($_POST['UserDOB'], ENT_QUOTES, 'utf-8') != $the_writer['UserDOB']) {
            $updates_changes .= "Date of Birth: <b>" . htmlentities($the_writer['UserDOB'], ENT_QUOTES, 'utf-8') .
                                "</b> <i class='bi bi-arrow-right'></i> <b>" . htmlentities($_POST['UserDOB'], ENT_QUOTES, 'utf-8') . "</b><br>";
        }

        if (htmlentities($_POST['UserProfession'], ENT_QUOTES, 'utf-8') != $the_writer['UserProfession']) {
            $updates_changes .= "User Profession: <b>" . htmlentities($the_writer['UserProfession'], ENT_QUOTES, 'utf-8') .
                                "</b> <i class='bi bi-arrow-right'></i> <b>" . htmlentities($_POST['UserProfession'], ENT_QUOTES, 'utf-8') . "</b><br>";
        }

        if (htmlentities($_POST['UserExperience'], ENT_QUOTES, 'utf-8') != $the_writer['UserExperience']) {
            $updates_changes .= "User Experience: <b>" . htmlentities($the_writer['UserExperience'], ENT_QUOTES, 'utf-8') .
                                "</b> <i class='bi bi-arrow-right'></i> <b>" . htmlentities($_POST['UserExperience'], ENT_QUOTES, 'utf-8') . "</b><br>";
        }

        if (htmlentities($_POST['UserTshirtSize'], ENT_QUOTES, 'utf-8') != $the_writer['UserTshirtSize']) {
            $updates_changes .= "User tShirt Size: <b>" . htmlentities($the_writer['UserTshirtSize'], ENT_QUOTES, 'utf-8') .
                                "</b> <i class='bi bi-arrow-right'></i> <b>" . htmlentities($_POST['UserTshirtSize'], ENT_QUOTES, 'utf-8') . "</b><br>";
        }

        if ($update_info) {

          if ($updates_changes !='') {
            userActivity($the_writer_id, "Account", "Account Information changed by User", $updates_changes);
          }
          if (empty($upload_errors)) {
            header("Location:".$site_domain.$tt_page_info['Social_og']['URL']);
            exit;
          }

        }else {
          $error = true;
        }
      }
  }


}else {
    $noPermissionHtml = '
    <div class="col-12 mt-4">
      <div class="border-0 rounded-2 alert alert-danger alert-dismissible fade show" role="alert">
        তথ্য পরিবর্তনের অনুমতি নেই !
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
      </div>
    </div>
    <script type="text/javascript">
    $(document).ready(function() {
      $("#editInfoMahamudfutureit").find("input, select, textarea, button").attr("disabled", true);
    });
    </script>
    ';

}


require_once('./header.php'); // Include Footer
?>
<section id="account_mahamudfutureit" class="sectionbg pt-4 pb-5">
      <div class="container">
          <div class="row mt-4 justify-content-center">
            <div class="col-md-8">
              <div class="acc-info-head round-15 mahamudfutureit-shadow border-0 card p-3 p-md-4">
                  <h1 class="m-0 fs-4"><img height="35px" src="<?php echo $site_domain ?>assets/image/icons/user-application.png"> <?php echo $tt_page_info['Page_Info']['Title'] ?></h1>
                  <hr>
                  <nav style="--s-breadcrumb-divider: '/';" aria-label="breadcrumb">
                      <ol class="breadcrumb m-0">
                        <li class="breadcrumb-item"><a href="<?php echo $site_domain ?>account/">অ্যাকাউন্ট</a></li>
                        <li class="breadcrumb-item"><a href="#"> <?php echo $tt_page_info['Page_Info']['Title'] ?></a></li>
                      </ol>
                  </nav>
              </div>

              <?php
              echo $noPermissionHtml;
              if ($error == true) {
                ?>
                <div class="col-12 mt-4">
                  <div class="border-0 rounded-4 alert alert-danger alert-dismissible fade show" role="alert">
                    সংরক্ষন করা সম্ভব হয়নি ! আবার চেষ্টা করুন ।
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                  </div>
                </div>
                <?php
              }

              // Display errors if any
              if (!empty($upload_errors)) {
                  foreach ($upload_errors as $error) {
                    ?>
                    <div class="col-12 mt-4">
                      <div class="border-0 rounded-4 alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($error) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                      </div>
                    </div>
                    <?php
                  }
              }


              ?>

              <div class="personal_info  round-15 mahamudfutureit-shadow border-0 card mt-3 p-3 p-md-4">
                <form enctype="multipart/form-data" id="editInfoMahamudfutureit" action="" method="post" class="row g-3 needs-validation" novalidate>
                  <div class="col-md-6">
                    <label for="uName" class="form-label">নাম (বাংলা)</label>
                    <input type="text" class="form-control" id="UserName" value="<?php echo $the_writer['UserName'] ?>" disabled>
                    <div class="text-danger">
                      নাম পরিবর্তনের জন্য কতৃপক্ষের সাথে যোগাযোগ করুন !
                    </div>
                  </div>
                  <div class="col-md-6">
                    <label for="uNameen" class="form-label">নাম (English)</label>
                    <input type="text" class="form-control" pattern="[a-zA-Z ]{4,25}" id="uNameen" name="UserNameEN" value="<?php echo $the_writer['UserNameEN'] ?>">
                    <div class="invalid-feedback">
                      ইংরেজি অক্ষরে নাম লিখুন !
                    </div>
                  </div>

                  <div class="col-md-6">
                    <label for="upName" class="form-label">পিতার নাম </label>
                    <input type="text" class="form-control"  id="upName" name="UserFather" value="<?php echo $the_writer['UserFather'] ?>">
                    <div class="invalid-feedback">
                      সঠিক ভাবে নাম লিখুন !
                    </div>
                  </div>

                  <div class="col-md-6">
                    <label for="umName" class="form-label">মাতার নাম </label>
                    <input type="text" class="form-control"  id="umName" name="UserMother" value="<?php echo $the_writer['UserMother'] ?>">
                    <div class="invalid-feedback">
                      সঠিক ভাবে নাম লিখুন !
                    </div>
                  </div>

                  <div class="col-md-6">
                    <label for="uNid" class="form-label">জাতীয় পরিচয়পত্র/জন্ম সনদ </label>
                    <input inputmode="numeric" type="text"  pattern="\d*" minlength="8" maxlength="22" class="form-control" id="nNid" name="UserNID" value="<?php echo $the_writer['UserNID'] ?>">
                    <div class="invalid-feedback">
                      জাতীয় পরিচয়পত্র/জন্ম সনদ নাম্বার দিন !
                    </div>
                  </div>

                  <div class="col-md-6">
                    <label for="uNid" class="form-label">জন্ম তারিখ </label>
                    <input  type="date"   class="form-control" id="nNid" name="UserDOB" value="<?php echo $the_writer['UserDOB'] ?>">
                  </div>

                  <div class="col-md-6">
                    <label for="UserBlood" class="form-label"> রক্তের গ্রুপ  </label>
                    <select class="form-control" id="UserBlood" name="UserBlood">
                       <option value="" disabled="" selected>রক্তের গ্রুপ</option>
                       <option value="A+" <?php echo ($the_writer['UserBlood'] == 'A+') ? 'selected' : '' ?>>A+</option>
                       <option value="B+" <?php echo ($the_writer['UserBlood'] == 'B+') ? 'selected' : '' ?>>B+</option>
                       <option value="O+" <?php echo ($the_writer['UserBlood'] == 'O+') ? 'selected' : '' ?>>O+</option>
                       <option value="AB+" <?php echo ($the_writer['UserBlood'] == 'AB+') ? 'selected' : '' ?>>AB+</option>
                       <option value="A-" <?php echo ($the_writer['UserBlood'] == 'A-') ? 'selected' : '' ?>>A-</option>
                       <option value="B-" <?php echo ($the_writer['UserBlood'] == 'B-') ? 'selected' : '' ?>>B-</option>
                       <option value="O-" <?php echo ($the_writer['UserBlood'] == 'O-') ? 'selected' : '' ?>>O-</option>
                       <option value="AB-" <?php echo ($the_writer['UserBlood'] == 'AB-') ? 'selected' : '' ?>>AB-</option>
                     </select>
                  </div>

                  <div class="col-md-6">
                    <label for="UserGender" class="form-label"> জেন্ডার  </label>
                    <select class="form-control" id="UserGender" name="UserGender">
                       <option value="" disabled="" selected>জেন্ডার নির্বাচন করুন</option>
                       <option value="male" <?php echo ($the_writer['UserGender'] == 'male') ? 'selected' : '' ?>>Male</option>
                       <option value="female" <?php echo ($the_writer['UserGender'] == 'female') ? 'selected' : '' ?>>Female</option>
                     </select>
                  </div>

                  <div class="col-md-6">
                    <label for="uProfession" class="form-label">পেশা</label>
                    <input  type="text"   class="form-control" id="uProfession" name="UserProfession" value="<?php echo $the_writer['UserProfession'] ?>">
                  </div>

                  <div class="col-md-6">
                    <label for="UserExperience" class="form-label">সাংবাদিকতার অভিজ্ঞতা আছে? </label>
                    <select class="form-control" id="UserExperience" name="UserExperience">
                       <option value="" disabled="" <?php echo ($the_writer['UserExperience'] == '') ? 'selected' : ''; ?>>সাংবাদিকতার অভিজ্ঞতা নির্বাচন করুন</option>
                       <option value="Yes" <?php echo ($the_writer['UserExperience'] == 'Yes') ? 'selected' : ''; ?>>হ্যা</option>
                       <option value="No" <?php echo ($the_writer['UserExperience'] == 'No') ? 'selected' : ''; ?>>না</option>
                     </select>
                  </div>

                  <div class="col-md-6">
                    <label for="UserTshirtSize" class="form-label">টি-শার্ট সাইজ </label>
                    <select class="form-control" id="UserTshirtSize" name="UserTshirtSize">
                       <option value="" disabled="" <?php echo ($the_writer['UserTshirtSize'] == '') ? 'selected' : ''; ?>>টি-শার্ট সাইজ নির্বাচন করুন</option>
                       <option value="S" <?php echo ($the_writer['UserTshirtSize'] == 'S') ? 'selected' : ''; ?>>S</option>
                       <option value="M" <?php echo ($the_writer['UserTshirtSize'] == 'M') ? 'selected' : ''; ?>>M</option>
                       <option value="L" <?php echo ($the_writer['UserTshirtSize'] == 'L') ? 'selected' : ''; ?>>L</option>
                       <option value="XL" <?php echo ($the_writer['UserTshirtSize'] == 'XL') ? 'selected' : ''; ?>>XL</option>
                       <option value="XXL" <?php echo ($the_writer['UserTshirtSize'] == 'XXL') ? 'selected' : ''; ?>>XXL</option>
                     </select>
                  </div>

                  <div class="col-md-6">
                    <label for="PhotoFile" class="form-label">ছবি আপলোড করুন  <small class="text-danger">(560x650px)</small> </label>
                    <?php if (!empty($the_writer['PhotoFile'])): ?>
                        <a download href="<?php echo $site_domain . 'uploads/public_files/' . $the_writer['PhotoFile']; ?>"> <small class="text-primary">(পূর্বের ছবি)</small> </a>
                    <?php endif; ?>
                    <input  type="file"   class="form-control" id="PhotoFile" name="PhotoFile" value="<?php echo $the_writer['PhotoFile'] ?>" accept="image/*">
                  </div>

                  <div class="col-md-6">
                    <label for="NidFile" class="form-label">জাতীয় পরিচয় পত্র আপলোড করুন</label>
                    <?php if (!empty($the_writer['NidFile'])): ?>
                        <a download href="<?php echo $site_domain . 'uploads/public_files/' . $the_writer['NidFile']; ?>"> <small class="text-primary">(পূর্বের জাতীয় পরিচয় পত্র)</small> </a>
                    <?php endif; ?>
                    <input  type="file"   class="form-control" id="NidFile" name="NidFile" value="<?php echo $the_writer['NidFile'] ?>" accept="application/pdf,image/*">
                  </div>

                  <div class="col-md-6">
                    <label for="CvFile" class="form-label">সিভি জমা দিন </label>
                    <?php if (!empty($the_writer['CvFile'])): ?>
                        <a download href="<?php echo $site_domain . 'uploads/public_files/' . $the_writer['CvFile']; ?>"> <small class="text-primary">(পূর্বের সিভি)</small> </a>
                    <?php endif; ?>
                    <input  type="file"   class="form-control" id="CvFile" name="CvFile"  accept="application/pdf,image/*">
                  </div>


                  <div class="col-12 text-end">
                    <?php echo csrfField() ?>
                    <button class="btn btn-primary" type="submit"> সংরক্ষন করুন </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
      </div>
  </section>
<?php
require_once('./footer.php'); // Include Footer
?>
