<?php
$tt_page_info = array(
  'Page_Info' =>   array(
    'Title' => 'সম্পাদনা করুণ ',
    'Description' => '',
    'Keyword' => '',
  ),
  'Social_og' => array(
    'Image' => '',
    'Type' => 'website',
    'URL' => 'account/article/edit/'.$edit_post['PostId'].'/',
  ),
);


if ($edit_post['PostStatus'] == 'pending') {
  $edit_access = true;
  $field_attribute = '';
}else {
  $edit_access = false;
  $field_attribute = 'disabled';
}

$error = [];

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

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

      if (!verifyCSRFToken($csrf_token)) {
        $error[] = 'দুঃখিত ! আবার চেষ্টা করুণ ।';
      } else {

        // Validate Post Titile
        if ($_POST['post_title'] !='') {
          $post_title =   htmlentities(preg_replace('/[@#$%^*\(\)_=+\\\\|\[\]{};><]/', '', $_POST['post_title']), ENT_QUOTES, 'utf-8');
        }else {
          $error[] = 'সঠিক ভাবে সংবাদ শিরোনাম লিখুন !';
        }

        // Validate Post Content
        if ($_POST['post_content'] !='') {
          $post_contents =  $_POST['post_content'];
        }else {
          $error[] = 'সঠিক ভাবে সংবাদ লিখুন !';
        }

        // Validate Post Image Caption
        $featured_image_caption =   htmlentities(preg_replace('/[@#$%^*\(\)_=+\\\\|\[\]{};><]/', '', $_POST['featured_image_caption']), ENT_QUOTES, 'utf-8');

        // Validate Post Content
        if ($_POST['post_category'] !='') {
          $post_category =  htmlentities($_POST['post_category'], ENT_QUOTES, 'utf-8');
        }else {
          $error[] = 'সংবাদের ক্যাটাগরি নির্বাচন করুণ !';
        }

        if (empty($error)) {
          // Upload And Crop Image
          if(isset($_FILES["featured_image"]) && $_FILES["featured_image"]["error"] =='0' && extension_loaded('gd')) {


            // The Post Year and Month
            $date_offpost = new DateTime($edit_post['PostDate']);
            $year_offpost = $date_offpost->format('Y');
            $month_offpost = $date_offpost->format('m');

            // Define the base uploads directory
            $uploads_dir =  'uploads'; // Adjust path as needed

            // Check if the year folder exists
            $year_dir = $uploads_dir . '/' . $year_offpost;
            if (!is_dir($year_dir)) {
                mkdir($year_dir, 0755, true); // Create year directory
            }
            // Check if the month folder exists
            $month_dir = $year_dir . '/' . $month_offpost;
            if (!is_dir($month_dir)) {
                mkdir($month_dir, 0755, true); // Create month directory
            }

            // Final directory
            $final_directory = $month_dir;

            //get the uploaded image
            $source_image = $_FILES['featured_image']['tmp_name'];
            $post_ttamp = time().generateOTP();

            // Create Featured Image
            $featured_imagename = 'Mahamudfutureit.com_'.$post_ttamp.'.jpg';
            $destination = $final_directory.'/'.$featured_imagename;
            $tn_w = 1280;
            $tn_h = 720;
            $quality = 80;
            if ($advancenews['Article_fImage'] == '') {
              $wmsource = 'assets/img/blank_image.png';
            }else {
              $wmsource = 'uploads/'.basename($advancenews['Article_fImage']);
            }
            $success_featured_img = image_handler($source_image,$destination,$tn_w,$tn_h,$quality,$wmsource);
            if($success_featured_img) {
              $advancenews_featured_img = $featured_imagename;
            }else {
              // Featured image  Upload failed
              $advancenews_featured_img = $edit_post['PostImage'];
            }

            // Create Social OG
            if ($advancenews['Article_fImage_OG'] !='') {
              $name_share = 'Mahamudfutureit.com_1200x630_'.$post_ttamp.'_social.jpg';
              $destination_share = $final_directory.'/'.$name_share;
              $share_w = 1200;
              $share_h = 630;
              $wm_share = 'uploads/'.basename($advancenews['Article_fImage_OG']);
              $success_share = image_handler($source_image,$destination_share,$share_w,$share_h,$quality,$wm_share);
              if($success_share) {
                $advancenews_og_img = $name_share;
              }else {
                $advancenews_og_img = $edit_post['PostImageOG'];
              }
            }else {
              $advancenews_og_img = $edit_post['PostImageOG'];
            }

            // Delete Old File if Uploaded New File
            $post_images_fd = array(
                                "uploads/".$year_offpost."/".$month_offpost."/".$edit_post['PostImage'],
                                "uploads/".$year_offpost."/".$month_offpost."/".$edit_post['PostImageOG'],
                              );
            foreach ($post_images_fd as $file_oftpost) {
                if (file_exists($file_oftpost)) {
                    unlink($file_oftpost);
                }
            }

          }else {
            // Image Upload failed
            $advancenews_featured_img = $edit_post['PostImage'];
            $advancenews_og_img = $edit_post['PostImageOG'];
          }
        }

        if (empty($error)) {
          $post_form_data = array(
            "PostTitle"             => $post_title,
            "PostContent"           => $post_contents,
            "PostImage"             => $advancenews_featured_img,
            "PostImageOG"           => $advancenews_og_img,
            "PostDivision"          => $_POST['post_division'],
            "PostDistrict"          => $_POST['post_district'],
            "PostUpazila"           => $_POST['post_upazila'],
            "PostCategory"          => $post_category,
            "PostImageCaption"      => $featured_image_caption,
            "PostModified"          => $the_time,
          );
           // Insert Database
           $insert_now = UpdateData('mahamudfutureit_article', 'PostId', $edit_post['PostId'], $post_form_data);
          if ($insert_now) {
              header("Location:".$site_domain."account/article/edit/".$edit_post['PostId']."/");
              exit;
           }else {
             $error[] = 'সংবাদ সংরক্ষন হয়নি ! আবার চেষ্টা করুণ ।';
           }

        }
      }
  }
}

// Get All District
$get_all_district = showAllttdata("mahamudfutureit_loc_districts");

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-12">
          <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="28px" src="<?php echo $site_domain ?>assets/image/icons/hand-with-pen.png">
              <?php echo $tt_page_info['Page_Info']['Title'] ?>
              <?php
              if ($edit_post['PostStatus'] == 'pending') {
                ?>
                <span class="rounded-3 ms-2 fs-6 border d-inline-block px-4 py-2 border-warning bg-warning-subtle"> অপেক্ষামান রয়েছে  </span>
                <?php
              }elseif ($edit_post['PostStatus'] == 'draft') {
                ?>
                <span class="rounded-3 ms-2 fs-6 border d-inline-block px-4 py-2 border-warning bg-warning-subtle"> পর্যালোচনাধীন রয়েছে  </span>
                <?php
              }elseif ($edit_post['PostStatus'] == 'published') {
                ?>
                <span class="rounded-3 ms-2 fs-6 border d-inline-block px-4 py-2 border-success bg-success-subtle"> প্রকাশিত  </span>
                <?php
              }elseif ($edit_post['PostStatus'] == 'rejected') {
                ?>
                <span class="rounded-3 ms-2 fs-6 border d-inline-block px-4 py-2 border-danger bg-danger-subtle"> বাতিল করা হয়েছে   </span>
                <?php
              }
              ?>
            </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>
                <li class="breadcrumb-item">
                  <a href="#"><?php echo $edit_post['PostTitle'] ?></a>
                </li>
              </ol>
            </nav>
          </div>

          <form class="row pofst-validation" action="" method="post" enctype="multipart/form-data"  novalidate>
            <?php

            if (!empty($error)) {
              foreach ($error as $the_error) {
                ?>
                <div class="col-12 mt-2">
                  <div class="border-0 rounded-4 alert alert-danger alert-dismissible fade show" role="alert">
                    <?php echo $the_error ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                  </div>
                </div>
                <?php
              }
            }
             ?>
            <div class="col-md-8">
              <div class="round-15 mahamudfutureit-shadow border-0 card mt-3 p-3 p-md-4">
                <div class="form-group mb-3">
                  <label for="postTitle" class="form-label fw-bold">সংবাদ শিরোনাম <span class="text-danger">*</span> <small class="text-muted">(সর্বোচ্চ ১৬ শব্দের মধ্যে লিখতে হবে)</small> </label>
                  <input value="<?php echo htmlentities($edit_post['PostTitle'], ENT_QUOTES, 'utf-8'); ?>" type="text" id="postTitle" name="post_title" class="form-control form-control-lg" placeholder="সংবাদ শিরোনাম" required <?php echo $field_attribute ?>>
                  <div class="invalid-feedback">
                    সর্বোচ্চ ১৬ শব্দের মধ্যে সংবাদ শিরোনাম লিখুন !
                  </div>
                </div>
                <div class="form-group">
                  <label for="newsBox" class="form-label fw-bold">সংবাদ লিখুন <span class="text-danger">*</span> <small class="text-muted">(প্রতিনিধির নাম, পদবি লেখার প্রয়োজন নেই)</small> </label>
                  <div class="border overflow-hidden form-control p-0">

                    <div class="position-relative mahamudfutureit-edit-post">
                      <textarea name="post_content" id="newsBox" class="news-box" required <?php echo $field_attribute ?>><?php echo $edit_post['PostContent'] ?></textarea>
                    </div>
                    <div class="invalid-feedback">
                      সংবাদ লিখুন ।
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="col-md-4">
              <div class="round-15 mahamudfutureit-shadow border-0 card mt-3 p-3 p-md-4">
                <label class="form-label mb-1 fw-bold" for="imageInput">ছবি আপলোড করুণ <span class="text-danger">*</span> <small class="text-muted">(সর্বোচ্চ 2MB এর মধ্যে ছবি নির্বাচন করুণ)</small> </label>
                <div class="image_upload_div">
                  <div class="featured_image_article_selector" id="fileInputContainer">
                    <div class="image_preview">
                      <img class="w-100" id="previewImage" src="<?php echo $advancenews['ArticlePreloader'] ?>"  data-src="<?php echo articleImg($edit_post['PostId'], 'featured') ?>" alt="Featured Image">
                    </div>
                    <input value="<?php echo articleImg($edit_post['PostId'], 'featured') ?>" name="featured_image" type="file" id="imageInput" accept=".jpg, .jpeg, .png" required <?php echo $field_attribute ?>>
                    <div class="invalid-feedback">
                      <i class="bi bi-info-circle"></i> ছবি নির্বাচন করুণ !
                    </div>
                    <span class="align-middle">ছবি নির্বাচন করুণ</span>
                  </div>
                </div>

                <div class="form-group mt-2 mb-3">
                  <input value="<?php echo $edit_post['PostImageCaption'] ?>" class="form-control" type="text" name="featured_image_caption" placeholder="ছবির ক্যাপশন" <?php echo $field_attribute ?>>
                </div>

                <div class="form-group mb-3">
                  <label for="postCategory" class="form-label fw-bold">ক্যাটাগরি নির্বাচন করুণ <span class="text-danger">*</span></label>
                  <select class="form-select" id="postCategory" name="post_category" required <?php echo $field_attribute ?>>
                    <option value="" selected disabled>ক্যাটাগরি নির্বাচন করুণ</option>
                    <?php
                    $data_all_cat = showAllttdata("mahamudfutureit_category", "WHERE CategoryPermission = 'Public' AND CategorySataus = 'Published' ORDER BY CategoryID DESC");
                    foreach ($data_all_cat as $this_public_category) {
                      ?>
                      <option value="<?php echo $this_public_category['CategoryID'] ?>" <?php echo ($edit_post['PostCategory'] == $this_public_category['CategoryID']) ? 'selected' : ''; ?>>
                        <?php echo htmlentities($this_public_category['CategoryName'], ENT_QUOTES, 'utf-8'); ?>
                      </option>
                    <?php } ?>
                  </select>
                  <div class="invalid-feedback">
                    সংবাদ ক্যাটাগরি/বিভাগ নির্বাচন করুণ !
                  </div>
                </div>

                <div class="form-group mb-3">
                  <label for="ttDivision" class="form-label fw-bold">সংবাদের স্থান </label>
                  <select  id="ttDivision" name="post_division" class="form-select form-select-sm" onchange="changeDistrict()" <?php echo $field_attribute ?>>
                    <option selected="">বিভাগ</option>
                    <?php
                    $division_list = showAllttdata("mahamudfutureit_loc_divisions");
                    foreach ($division_list as $this_division) {
                      ?>
                      <option value="<?php echo $this_division['id'] ?>" <?php echo ($edit_post['PostDivision'] ==  $this_division['id'] ) ? 'selected' : ''; ?>>
                        <?php echo $this_division['bn_name'] ?>
                      </option>
                    <?php } ?>
                  </select>
                  <select id="ttDistrict" name="post_district" class="form-select  form-select-sm mt-2" onchange="changeUpazilla()" <?php echo $field_attribute ?>>
                    <?php
                    $division_id  = $edit_post['PostDivision'];
                    $district_list = showAllttdata("mahamudfutureit_loc_districts","WHERE division_id = '$division_id'");
                    if (!empty($district_list)) {
                      foreach ($district_list as $this_district) {
                        ?>
                        <option value="<?php echo $this_district['id'] ?>" <?php echo ($edit_post['PostDistrict'] ==  $this_district['id'] ) ? 'selected' : ''; ?>>
                          <?php echo $this_district['bn_name'] ?>
                        </option>
                      <?php }
                    }else {
                      ?>
                      <option selected="">জেলা</option>
                      <?php
                    }
                    ?>
                  </select>
                  <select id="ttUpazila" name="post_upazila" class="form-select  form-select-sm mt-2"   <?php echo $field_attribute ?>>
                    <?php
                      $district_id = $edit_post['PostDistrict'];
                      $upazila_list = showAllttdata("mahamudfutureit_loc_upazilas","WHERE district_id = '$district_id'");
                      if (!empty($upazila_list)) {
                        foreach ($upazila_list as $the_upazila) {
                          ?>
                          <option value="<?php echo $the_upazila['id'] ?>" <?php echo ($edit_post['PostUpazila'] ==  $the_upazila['id'] ) ? 'selected' : ''; ?>>
                            <?php echo $the_upazila['bn_name'] ?>
                          </option>
                          <?php
                        }
                      }else {
                        ?>
                        <option selected="">উপজেলা</option>
                        <?php
                      }
                    ?>
                  </select>
                </div>
                <?php
                if ($edit_access == true) {
                  echo csrfField();
                  ?>
                  <button type="submit"  class="btn btn-<?php echo ($the_writer['PostPublish'] == 'Automatic')? 'success' : 'warning' ?>"> <?php echo ($the_writer['PostPublish'] == 'Automatic')? 'আপডেট করুণ' : 'সাবমিট করুণ' ?> </button>
                  <?php
                }else {
                  ?>
                  <style media="screen">
                  .position-relative::before {
                      position: absolute;
                      display: block;
                      height: 100%;
                      width: 100%;
                      background: rgb(233 236 239 / 22%);
                      z-index: 9;
                      content: "";
                  }
                  </style>
                  <span class="cursor-pointer rounded-3 text-center fs-6 border d-block px-4 py-2 border-warning bg-warning-subtle"> সম্পাদনা করার অনুমতি নেই  </span>
                  <?php
                }
                if ($edit_post['PostStatus'] == 'published') {
                  ?>
                  <div class="input-group mt-3">
                    <a target="_blank" href="<?php echo articleLink($edit_post['PostId']) ?>" class="form-control border-success text-muted overflow-hidden"> <i class="bi bi-link-45deg"></i> আর্টিকেলটি পড়ুন </a>
                    <span data-tt-link="<?php echo articleLink($edit_post['PostId']) ?>" class="copy_tt_link bg-success border-success text-white input-group-text cursor-pointer">
                        <i class="bi bi-clipboard"></i>
                    </span>
                  </div>
                  <?php
                }
                ?>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </section>

  <script type="text/javascript">

    (function () {
    'use strict'

    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.querySelectorAll('.post-validation')

    // Loop over them and prevent submission
    Array.prototype.slice.call(forms)
      .forEach(function (form) {
        form.addEventListener('submit', function (event) {
          if (!form.checkValidity()) {
            event.preventDefault()
            event.stopPropagation()
          }

          form.classList.add('was-validated')
        }, false)
      })
    })();
    $('.news-box').richText({height: 365 ,ol: false,ul: false, heading: false, fonts: false, fontList: [], fontColor: false, fontSize: false, imageUpload: false, fileUpload: false, videoEmbed: false, urls: false, table: false, code: false});

    function changeDistrict() {
        let divisionID = $("#ttDivision").val();
        $.ajax({
            url: "<?php echo $site_domain;?>ajax_master/location_news/",
            type: "POST",
            data: { requestType: "ttDivision", division: divisionID },
            success: function(response) {
                $("#ttDistrict").html(response);
                $("#ttUpazila").html('<option value="" selected>উপজেলা</option>'); // Reset upazila
            }
        });
    }

    function changeUpazilla() {
        let ttDistrict = $("#ttDistrict").val();
        $.ajax({
            url: "<?php echo $site_domain;?>ajax_master/location_news/",
            type: "POST",
            data: { requestType: "ttDistrict", district: ttDistrict },
            success: function(response) {
                $("#ttUpazila").html(response);
            }
        });
    }
    $(document).ready(function() {
      $("#imageInput").change(function() {
        const preview = $("#previewImage")[0];
        const fileInput = $(this)[0];

        if (fileInput.files && fileInput.files[0]) {
          const reader = new FileReader();
          reader.onload = function(e) {
            preview.src = e.target.result;
          }
          reader.readAsDataURL(fileInput.files[0]);
        } else {
          preview.src = '<?php echo $site_domain ?>assets/image/featured_image_placeholder.webp';
        }
      });
    });
  </script>
<?php
require_once('./footer.php'); // Include Footer
?>
