<?php
$tt_page_info = array(
  'Page_Info' =>   array(
    'Title' => 'সংবাদ লিখুন ',
    'Description' => '',
    'Keyword' => '',
  ),
  'Social_og' => array(
    'Image' => '',
    'Type' => 'website',
    'URL' => 'account/article/new/',
  ),
);

$error = [];
// 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')) {

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

          // Check if the year folder exists
          $year_dir = $uploads_dir . '/' . $the_year;
          if (!is_dir($year_dir)) {
              mkdir($year_dir, 0755, true); // Create year directory
          }
          // Check if the month folder exists
          $month_dir = $year_dir . '/' . $the_month;
          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 = NULL;
          }

          // 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 = NULL;
            }
          }else {
            $advancenews_og_img = NULL;
          }
        }else {
          $error[] = 'ছবি আপলোড সম্ভব হয়নি ! আবার চেষ্টা করুণ ।';
        }
      }

      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'],
          "PostAuthor"            => $the_writer['UserID'],
          "PostCategory"          => $post_category,
          "PostImageCaption"      => $featured_image_caption,
          "PostStatus"            => ($the_writer['PostPublish'] == 'Automatic')? 'published' : 'pending',
          "PostDatePublic"        => $the_time,
          "PostDayPublic"         => date('Y-m-d'),
          "PageContentType"       => 'article',
          "PostURL"               => createUlink($post_title),
          "PostDate"              => $the_time,
        );
         // Insert Database
         $insert_now = InsertData('mahamudfutureit_article', $post_form_data);
        if ($insert_now) {
            header("Location:".$site_domain."account/article/edit/".$insert_now."/");
            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'] ?>
            </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>

          <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 type="text" id="postTitle" name="post_title" class="form-control form-control-lg" placeholder="সংবাদ শিরোনাম" required>
                  <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">
                    <textarea name="post_content" id="newsBox" class="news-box" required></textarea>
                    <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 $site_domain ?>assets/image/featured_image_placeholder.webp" alt="Featured Image">
                    </div>
                    <input name="featured_image" type="file" id="imageInput" accept=".jpg, .jpeg, .png" required>
                    <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 class="form-control" type="text" name="featured_image_caption" placeholder="ছবির ক্যাপশন">
                </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>
                    <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 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()">
                    <option selected="">বিভাগ</option>
                    <?php
                    $district_list = showAllttdata("mahamudfutureit_loc_divisions");
                    foreach ($district_list as $this_division) {
                      ?>
                      <option data-url="<?php echo $this_division['slag'] ?>" value="<?php echo $this_division['id'] ?>">
                        <?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()">
                    <option selected="">জেলা</option>
                  </select>

                  <select id="ttUpazila" name="post_upazila" class="form-select  form-select-sm mt-2" onchange="setUpazilla()">
                    <option selected="">উপজেলা</option>
                  </select>
                </div>
                <?php echo csrfField() ?>
                <button type="submit"  class="btn btn-<?php echo ($the_writer['PostPublish'] == 'Automatic')? 'success' : 'warning' ?>"> <?php echo ($the_writer['PostPublish'] == 'Automatic')? 'প্রকাশ করুণ' : 'সাবমিট করুণ' ?> </button>
              </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
?>
