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

if (isset($_POST['add_poll'])) {
  // Upload And Crop Image
  if(isset($_FILES["PollImage"]) && $_FILES["PollImage"]["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['PollImage']['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;
    $wmsource = 'assets/img/blank_image.png';
    $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['Poll_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['Poll_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_form_data = array(
    "PollTitle"             => $_POST['PollTitle'],
    "PollOptionOne"         => $_POST['PollOptionOne'],
    "PollOptionTwo"         => $_POST['PollOptionTwo'],
    "PollOptionThree"       => $_POST['PollOptionThree'],
    "PollOptionOneView"     => 0,
    "PollOptionTwoView"     => 0,
    "PollOptionThreeView"   => 0,
    "PollImage"             => $advancenews_featured_img,
    "PollImageOG"           => $advancenews_og_img,
    "PollStatus"            => $_POST['PollStatus'],
    "PollDatePublic"        => (new DateTime($_POST['PollDate']))->format('Y-m-d H:i:s'),
    "PollDate"              => $the_time,
    "PollAdmin"             => getSingleValue('admin_user', 'admin_security_key', $_COOKIE['Google_SLKA'] , 'admin_id'),
  );

   // Insert Database
   $insert_now = InsertData('mahamudfutureit_poll', $post_form_data);
      if ($insert_now) {
          header("Location:poll-edit.php?poll_id=".$insert_now);
          exit;
       }else {
         $tt_alert = ttAlert('danger', 'Something went wrong to add Poll !');
       }
    }
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="poll.php" class="btn btn-primary btn-sm"><i class="bi bi-grid"></i> All Poll </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">

            <!-- ***********************
            Poll Title
            *************************-->
            <div class="form-group mb-2">
              <label>Poll Title <span class="text-danger">*</span> </label>
              <textarea name="PollTitle" class="form-control" rows="4" required></textarea>
            </div>
            <div class="form-group mb-2">
              <label>Option One <span class="text-danger">*</span> </label>
              <input value="হ্যাঁ" type="search" name="PollOptionOne" class="form-control"  required>
            </div>
            <div class="form-group mb-2">
              <label>Option Two <span class="text-danger">*</span> </label>
              <input value="না" type="search" name="PollOptionTwo" class="form-control"  required>
            </div>
            <div class="form-group mb-2">
              <label>Option Three   </label>
              <input value="মন্তব্য নেই" type="search" name="PollOptionThree" class="form-control">
            </div>
        </div>
      </div>
      <div class="col-md-4">

        <!-- ***********************
        Poll Featured Image
        *************************-->
        <div class="bg-white rounded-2 p-3  ">
          <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="PollImage" type="file" id="imageInput" accept=".jpg, .jpeg, .png">
              <span class="align-middle">  Choice Image </span>
            </div>
          </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="PollDate" required>
          </div>
          <div class="form-group mt-3" >
            <label class="form-label">Publish Status</label>
            <select name="PollStatus" class="form-select form-control">
              <option value="Published">Published</option>
              <option value="Draft">Draft</option>
            </select>
          </div>
          <button type="submit" class="mt-3 btn btn-success btn-sm w-100" name="add_poll" ><i class="bi bi-floppy"></i> Add New Poll</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';
    }
  });
});
</script>
<?php require_once('inc/footer.php'); ?>
