<?php
require_once('config.php');

if (isset($_POST['add_post'])) {
  // Upload And Crop Image
  if(isset($_FILES["PostImage"]) && $_FILES["PostImage"]["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['PostImage']['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 {
    // Image Upload failed
    $advancenews_featured_img = NULL;
    $advancenews_og_img = NULL;
  }

  // Post Type video if have video link
  if ($_POST['PostVideoLink'] !='') {
    $this_post_type = 'video';
  }else {
    $this_post_type = 'article';
  }

  if (!empty($_POST['PostTopic'])) {
      $save_topic = json_encode($_POST['PostTopic'], JSON_UNESCAPED_UNICODE);
  } else {
      $save_topic = NULL;
  }

  $post_form_data = array(
    "PostTitle"             => $_POST['PostTitle'],
    "PostSubtitle"          => $_POST['PostSubtitle'],
    "PostContent"           => $_POST['PostContent'],
    "PostImage"             => $advancenews_featured_img,
    "PostImageOG"           => $advancenews_og_img,
    "PostVideoLink"         => $_POST['PostVideoLink'],
    "PostDivision"          => $_POST['PostDivision'],
    "PostDistrict"          => $_POST['PostDistrict'],
    "PostUpazila"           => $_POST['PostUpazila'],
    "PostWriterName"        => htmlentities($_POST['PostWriterName'], ENT_QUOTES, 'utf-8'),
    "PostWriterDesignation" => htmlentities($_POST['PostWriterDesignation'], ENT_QUOTES, 'utf-8'),
    "PostAuthor"            => $_POST['PostAuthor'],
    "PostCategory"          => $_POST['PostCategory'],
    "PostSubCategory"       => json_encode($_POST['sub_category']),
    "PostTopic"             => $save_topic,
    "PostSpotlight"         => $_POST['PostSpotlight'],
    "PostSlider"            => isset($_POST['PostSlider']) ? '1' : '0',
    "PostLead"              => $_POST['PostLead'],
    "PostTicker"            => $_POST['PostTicker'],
    "PostImageCaption"      => htmlentities($_POST['PostImageCaption'], ENT_QUOTES, 'utf-8'),
    "PostAttachment"        => $_POST['PostAttachment'],
    "PostStatus"            => $_POST['PostStatus'],
    "PostDatePublic"        => (new DateTime($_POST['publishDateTime']))->format('Y-m-d H:i:s'),
    "PostDayPublic"         => (new DateTime($_POST['publishDateTime']))->format('Y-m-d'),
    "PageContentType"       => $this_post_type,
    "PostURL"               => createUlink($_POST['PostTitle']),
    "PostDate"              => $the_time,
    "PostAdmin"             => getSingleValue('admin_user', 'admin_security_key', $_COOKIE['Google_SLKA'] , 'admin_id'),
  );

   // Insert Database
   $insert_now = InsertData('mahamudfutureit_article', $post_form_data);
      if ($insert_now) {
          header("Location:article-edit.php?article_id=".$insert_now);
          exit;
       }else {
         $tt_alert = ttAlert('danger', 'Something went wrong to add Article !');
       }
    }
require_once('inc/header.php');
?>

<main id="main" class="main">
  <div class="row">
    <div class="col-6 align-items-center">
      <div class="pagetitle mb-2">
        <h1><?php echo $page_title ?></h1>
      </div>
    </div>
    <div class="col-6 text-end">
        <a href="article.php" class="btn btn-primary btn-sm"><i class="bi bi-grid"></i> All Article </a>
    </div>
  </div>

  <?php
  if (!extension_loaded('gd')) {
    ?>
    <div class="alert alert-warning my-2">
      GD extension is requered for Image watermark.
    </div>
    <?php
  }
  echo $tt_alert ?? '';
  ?>
  <section class="section mt-4">
    <form class="row" action="" method="post" enctype="multipart/form-data">
      <div class="col-md-8">
        <div class="bg-white rounded-2 p-3">

            <!-- ***********************
            Article Title
            *************************-->
            <div class="form-group mb-2">
              <label>Article Title <span class="text-danger">*</span> </label>
              <input name="PostTitle" type="text" class="form-control" placeholder="Article Title" required>
            </div>
            <div class="form-group mb-2">
              <label>Subtitle </label>
              <input name="PostSubtitle" type="text" class="form-control" placeholder="Article Subtitle">
            </div>
            <!-- ***********************
            Article Content
            *************************-->
            <!-- Modal -->
            <div class="modal fade" id="addRelatedNews" tabindex="-1"   aria-hidden="true">
              <div class="modal-dialog modal-dialog-scrollable">
                <div class="modal-content">
                  <div class="modal-header">
                    <h5 class="modal-title">Add Recent Article</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                  </div>
                  <div class="modal-body">
                    <?php
                    $recent_100 = showAllttdata("mahamudfutureit_article", "WHERE PostStatus ='published' ORDER BY  PostDate  DESC LIMIT 100");
                    foreach ($recent_100 as $the_recent) {
                      ?>
                      <p class="border g-2 p-2 rounded-2 d-flex justify-content-between align-items-center">
                        <a target="_blank" title="View Article" class="d-block text-dark" href="<?php echo articleLink($the_recent['PostId']) ?>"><?php echo $the_recent['PostTitle'] ?></a>
                        <button data-readalso="[MAHAMUDFUTUREIT-POST:<?php echo  $the_recent['PostId']  ?>]" class="d-block addReadMoreNews btn btn-secondary btn-sm " type="button">Add</button>
                      </p>
                      <?php
                    }
                    ?>
                  </div>
                </div>
              </div>
            </div>

            <div class="form-group mt-2 mb-2">
              <div class="d-flex justify-content-between pb-2 align-items-center ">
                <div>
                  <label>Article Content <span class="text-danger">*</span></label>
                </div>
                <div>
                  <button type="button" class="btn btn-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#addRelatedNews">
                    Recent Article
                  </button>
                </div>
              </div>
              <textarea name="PostContent" class="form-control editor2" rows="4" required></textarea>
            </div>
        </div>
        <div class="bg-white mt-3 rounded-2 p-3">
          <div class="form-group mb-2">
            <label>Youtube Link </label>
            <input name="PostVideoLink" type="url" class="form-control" placeholder="eg. https://www.youtube.com/watch?v=ABCDE">
          </div>
          <div class="form-group">
            <label>Attach File</label>
            <div class='input-group'>
              <input id='fileAtt' name='PostAttachment' type='url' class='form-control rounded-0 border-success' value='' placeholder='Select file'>
              <a href='#' class='addMediaButton input-group-text border-success bg-success text-white rounded-0' data-media_type='' data-bs-toggle='modal' data-bs-target='#SelectMedia' data-target='#fileAtt'>
                <i class='bi bi-upload'></i>
              </a>
            </div>
          </div>
        </div>
          <div class="row g-2">
            <div class="col-md-6">
              <div class="bg-white rounded-2 p-3 mt-3">
                <!-- ***********************
                Article Location Division
                *************************-->
                <?php
                    $get_divisions = showAllttdata("mahamudfutureit_loc_divisions");
                ?>
                <div class="form-group mb-2">
                    <label>
                      <strong>Article Location (Division)</strong>
                    </label>
                    <select id="newsDivision" name="PostDivision" class="form-control form-select">
                        <option value="" selected >Select Division</option>
                        <?php
                            foreach($get_divisions as $this_division){
                                ?>
                                <option value="<?php echo $this_division['id'] ?>"><?php echo $this_division['name'].' - '.$this_division['bn_name'] ?></option>
                                <?php
                            }
                        ?>
                    </select>
                </div>

                <!-- ***********************
                Article Location District
                *************************-->
                <div class="form-group mb-2">
                    <label>
                      <strong>District</strong>
                    </label>
                    <select id="newsDistrict" name="PostDistrict" class="form-control form-select">
                        <option value="" selected>Select District</option>
                    </select>
                </div>

                <!-- ***********************
                Article Location Upazilla
                *************************-->
                <div class="form-group mb-0">
                    <label>
                      <strong>Upazila</strong>
                    </label>
                    <select id="newsUpazila" name="PostUpazila" class="form-control form-select">
                        <option value="" selected>Select Upazila</option>
                    </select>
                </div>
              </div>
            </div>
            <div class="col-md-6">
              <div class="bg-white rounded-2 p-3 mt-3">

                  <!-- ***********************
                  Guest Writer Name
                  *************************-->
                  <div class="form-group">
                    <label for="WriterName" class="form-label">Guest Writer Name</label>
                    <input type="text" class="form-control" name="PostWriterName" id="WriterName" placeholder="Writer Name">
                  </div>

                  <!-- ***********************
                  Guest Writer Designation
                  *************************-->
                  <div class="form-group mt-2">
                    <label for="WriterDesignation" class="form-label">Guest Writer Designation</label>
                    <input type="text" class="form-control" name="PostWriterDesignation" id="WriterDesignation" placeholder="Writer Designation">
                  </div>

                  <!-- ***********************
                  Select Writer
                  *************************-->
                  <div class="form-group mt-2">
                    <label>Article Writer <span class="text-danger">*</span> </label>
                    <select class="form-control tt-select-single" name="PostAuthor">
                      <option value="" disabled selected>Select Writer</option>
                      <?php
                      $tt_writers = showAllttdata("tt_accounts", "WHERE AccountStatus = 'active' and PostAbility = 'yes' ORDER BY  UserID  ASC");
                      foreach ($tt_writers as $the_writer) {
                        ?>
                        <option value="<?php echo $the_writer['UserID'] ?>"><?php echo $the_writer['UserName']; echo ($the_writer['UserDesignation'] !='')?  ' - '.$the_writer['UserDesignation'] : ''; ?> </option>
                        <?php
                      }
                      ?>
                    </select>
                  </div>
              </div>
            </div>
          </div>
      </div>
      <div class="col-md-4">
        <div class="bg-white rounded-2 p-3">
          <!-- ***********************
          Article Category
          *************************-->
          <div class="form-group mb-2">
            <label>Article Category <span class="text-danger">*</span> </label>
            <select class="form-control tt-select-single" name="PostCategory" required>
              <option value="">Select Category</option>
              <?php
              $data_p_cat = showAllttdata("mahamudfutureit_category" , "WHERE CategorySataus ='Published' and CategoryParent IS NULL OR CategoryParent = '' ORDER BY  CategoryID  DESC ");
              if (!empty($data_p_cat)) {
                foreach ($data_p_cat as $parent_category) {
                  ?>
                  <option value="<?php echo $parent_category['CategoryID'] ?>"><?php echo $parent_category['CategoryName'] ?></option>
                  <?php
                  $parent = $parent_category['CategoryID'];
                  $data_p_cat = showAllttdata("mahamudfutureit_category", "WHERE CategorySataus ='Published' and  CategoryParent = '$parent' ORDER BY  CategoryID  DESC ");
                  if (!empty($data_p_cat)) {
                    foreach ($data_p_cat as $tt_sub_category) {
                      ?>
                      <option value="<?php echo $tt_sub_category['CategoryID'] ?>">--<?php echo $tt_sub_category['CategoryName'] ?></option>
                      <?php
                    }
                  }
                }
              }
              ?>
            </select>
          </div>
          <div>

            <!-- ***********************
            Article Subcategorys
            *************************-->
            <div class="form-group">
              <label class="d-block">Article Sub Category   </label>
            </div>
            <div class="tt_checkbox multi_cat_selector">
              <?php
              $data_p_cat = showAllttdata("mahamudfutureit_category" , "WHERE CategorySataus ='Published' and CategoryParent IS NULL OR CategoryParent = '' ORDER BY  CategoryID  DESC ");
              if (!empty($data_p_cat)) {
                foreach ($data_p_cat as $parent_category) {
                  ?>
                  <div class="form-group d-block m-0 mb-0">
                    <input name="sub_category[]" type="checkbox" value="<?php echo $parent_category['CategoryID'] ?>" id="cat<?php echo $parent_category['CategoryID'] ?>">
                    <label for="cat<?php echo $parent_category['CategoryID'] ?>">  <?php echo $parent_category['CategoryName'] ?>  </label>
                  </div>
                  <?php
                  $parent = $parent_category['CategoryID'];
                  $data_p_cat = showAllttdata("mahamudfutureit_category", "WHERE CategorySataus ='Published' and  CategoryParent = '$parent' ORDER BY  CategoryID  DESC ");
                  if (!empty($data_p_cat)) {
                    foreach ($data_p_cat as $tt_sub_category) {
                      ?>
                      <div class="form-group d-block ms-3 mb-0">
                        <input name="sub_category[]" type="checkbox" value="<?php echo $tt_sub_category['CategoryID'] ?>" id="cat<?php echo $tt_sub_category['CategoryID'] ?>">
                        <label for="cat<?php echo $tt_sub_category['CategoryID'] ?>">  <?php echo $tt_sub_category['CategoryName'] ?>  </label>
                      </div>
                      <?php
                    }
                  }
                }
              }
              ?>
            </div>


            <!-- ***********************
            Article Tags
            *************************-->
            <div class="form-group mb-2 mt-3">
              <label>Tag/Topic   </label>
              <select name="PostTopic[]" class="form-control tt-tag-selector" multiple="multiple">
                <?php
                $all_topic = showArticleTopic();
                $current_topics = json_decode($topics['PostTopic'], true);
                foreach ($all_topic as $the_topic) {
                  ?>
                  <option><?php echo $the_topic ?></option>
                  <?php
                }
                ?>
              </select>
            </div>

            <div class="tt_checkbox mt-3 row g-0">
              <!-- ***********************
              Article Extra Meta
              *************************-->
              <div class="col-12">
                <div class="form-check form-switch">
                  <input class="form-check-input" type="checkbox" name="PostTicker" role="switch" id="NewsTicker">
                  <label class="form-check-label" for="NewsTicker">News Ticker</label>
                </div>
              </div>
              <div class="col-12">
                <div class="form-check form-switch">
                  <input class="form-check-input" name="PostLead" type="checkbox" role="switch" id="LeadNews">
                  <label class="form-check-label" for="LeadNews"> Lead News </label>
                </div>
              </div>
              <div class="col-12">
                <div class="form-check form-switch">
                  <input class="form-check-input" name="PostSpotlight" type="checkbox" role="switch" id="Spotlight">
                  <label class="form-check-label" for="Spotlight"> Spotlight </label>
                </div>
              </div>
              <div class="col-12">
                <div class="form-check form-switch">
                  <input class="form-check-input" name="PostSlider" type="checkbox" role="switch" id="SliderNews">
                  <label class="form-check-label" for="SliderNews"> 🎬 Slider News (হোমপেজ স্লাইডারে দেখাবে) </label>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="bg-white rounded-2 p-3 mt-3">

          <!-- ***********************
          Article Featured Image
          *************************-->
          <div class="image_upload_div">
            <div class="featured_image_article_selector " id="fileInputContainer">
              <div class="image_preview">
                <img class="w-100" id="previewImage" src="assets/img/featured_image_placeholder.webp" alt="Featured Image">
              </div>
              <input name="PostImage" type="file" id="imageInput" accept=".jpg, .jpeg, .png">
              <span class="align-middle">  Choice Image </span>
            </div>
          </div>

          <!-- ***********************
          Article Featured Image Caption
          *************************-->
          <div class="form-group mt-2">
            <input type="text" class="form-control form-control-sm" id="ImageCaption" name="PostImageCaption" placeholder="Image Caption">
          </div>

        </div>
        <div class="bg-white rounded-2 p-3 mt-3">
          <div class="form-group">
            <label class="form-label">Published Date <span class="text-danger">*</span></label>
            <input type="datetime-local" step="1"  class="form-control" value="<?php echo date('Y-m-d\TH:i') ?>" name="publishDateTime" required>
          </div>

          <div class="form-group mt-3" >
            <label class="form-label">Publish Status</label>
            <select name="PostStatus" class="form-select form-control">
              <option value="published">Published</option>
              <option value="draft">Draft</option>
              <option value="pending">Pending</option>
            </select>
          </div>

          <button type="submit" class="mt-3 btn btn-success btn-sm w-100" name="add_post" ><i class="bi bi-floppy"></i> Add New Post</button>
        </div>
      </div>
    </form>
  </section>
</main>
<script>
$(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 = 'assets/img/featured_image_placeholder.webp';
    }
  });
});
document.addEventListener('DOMContentLoaded', function () {
    // Helper function to make an HTTP POST request
    function postData(url, data, callback) {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', url, true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                callback(xhr.responseText);
            } else if (xhr.readyState === 4) {
                console.error('Request failed with status: ' + xhr.status);
            }
        };
        xhr.send(data);
    }

    // Populate the District dropdown based on Division selection
    document.getElementById('newsDivision').addEventListener('change', function () {
        const divisionId = this.value;
        if (divisionId) {
            postData(
                '<?php echo $site_domain ?>ajax_master/location_news/',
                'requestType=ttDivision&division=' + encodeURIComponent(divisionId),
                function (response) {
                    document.getElementById('newsDistrict').innerHTML = response;
                    // Clear Upazila dropdown
                    document.getElementById('newsUpazila').innerHTML = '<option selected>Select Upazila</option>';
                }
            );
        } else {
            // Handle blank divisionId
            document.getElementById('newsDistrict').innerHTML = '<option selected>Select District</option>';
            // Clear Upazila dropdown
            document.getElementById('newsUpazila').innerHTML = '<option selected>Select Upazila</option>';
        }
    });

    // Populate the Upazila dropdown based on District selection
    document.getElementById('newsDistrict').addEventListener('change', function () {
        const districtId = this.value;
        if (districtId) {
            postData(
                '<?php echo $site_domain ?>ajax_master/location_news/',
                'requestType=ttDistrict&district=' + encodeURIComponent(districtId),
                function (response) {
                    document.getElementById('newsUpazila').innerHTML = response;
                }
            );
        }
    });
});

</script>
<?php require_once('inc/footer.php'); ?>