<?php
require_once('config.php');
$page_title = 'Edit Poll '; // Custom Page Title

if (isset($_GET['poll_id'])) {
  $poll_id_get = $_GET['poll_id'];
  $this_poll = showAllttdata("mahamudfutureit_poll", "WHERE PollID = '$poll_id_get'");
  if (!empty($this_poll)) {
    foreach ($this_poll as $the_poll);
  }else {
    header("Location:404.php");
    exit;
  }
}

if (isset($_POST['save_poll'])) {

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


    // The Post Year and Month
    $date_offpost = new DateTime($the_poll['PollDate']);
    $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['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 = $the_poll['PollImage'];
    }

    // 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 = $the_poll['PollImageOG'];
      }
    }else {
      $advancenews_og_img = $the_poll['PollImageOG'];
    }

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

  }else {
    // Image Upload failed
    $advancenews_featured_img = $the_poll['PollImage'];
    $advancenews_og_img = $the_poll['PollImageOG'];
  }

  $post_form_data = array(
    "PollTitle"             => $_POST['PollTitle'],
    "PollOptionOne"         => $_POST['PollOptionOne'],
    "PollOptionTwo"         => $_POST['PollOptionTwo'],
    "PollOptionThree"       => $_POST['PollOptionThree'],
    "PollImage"             => $advancenews_featured_img,
    "PollImageOG"           => $advancenews_og_img,
    "PollStatus"            => $_POST['PollStatus'],
    "PollDatePublic"        => (new DateTime($_POST['PollDate']))->format('Y-m-d H:i:s'),
  );


   // Insert Database
   $insert_now = UpdateData('mahamudfutureit_poll', 'PollID', $the_poll['PollID'], $post_form_data);
      if ($insert_now) {
        header("Location:poll-edit.php?poll_id=".$the_poll['PollID']);
        exit;
       }else {
         $tt_alert = ttAlert('danger', 'Something went wrong to Upadate 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 ?>
          <?php
          if($the_poll['PollStatus'] == 'Published'){
            ?>
            <span class="fs-6 bg-opacity-10 bg-success border border-success text-success rounded-pill px-3 p-1 pt-2 d-inline-block"> Published</span>
            <?php
          }elseif($the_poll['PollStatus'] == 'Draft'){
            ?>
            <span class="fs-6 bg-opacity-10 bg-secondary border border-secondary text-secondary rounded-pill px-3 p-1 pt-2 d-inline-block"> Draft</span>
            <?php
          }
          ?>
        </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-9">
        <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><?php echo $the_poll['PollTitle'] ?></textarea>
            </div>
            <div class="form-group mb-2">
              <label>Option One <span class="text-danger">*</span> </label>
              <input type="search" value="<?php echo $the_poll['PollOptionOne'] ?>" name="PollOptionOne" class="form-control"  required>
            </div>
            <div class="form-group mb-2">
              <label>Option Two <span class="text-danger">*</span> </label>
              <input type="search" value="<?php echo $the_poll['PollOptionTwo'] ?>" name="PollOptionTwo" class="form-control"  required>
            </div>
            <div class="form-group mb-2">
              <label>Option Three   </label>
              <input  type="search" value="<?php echo $the_poll['PollOptionThree'] ?>" name="PollOptionThree" class="form-control">
            </div>
        </div>
      </div>
      <div class="col-md-3">
        <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="<?php echo  getPollImage($the_poll['PollID']); ?>" 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 $the_poll['PollDatePublic'] ?>" 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" <?php echo ($the_poll['PollStatus'] == 'Published')? 'selected' : '' ?>>Published</option>
              <option value="Draft" <?php echo ($the_poll['PollStatus'] == 'Draft')? 'selected' : '' ?>>Draft</option>
            </select>
          </div>
          <?php
          if ($the_poll['PollStatus'] == 'Published') {
            ?>
            <div class="input-group mt-3">
              <a target="_blank" href="<?php echo pollLink($the_poll['PollID']) ?>" class="form-control text-muted overflow-hidden">View Poll</a>
              <span data-tt-link="<?php echo pollLink($the_poll['PollID']) ?>" class="copy_tt_link input-group-text cursor-pointer" id="basic-addon1">
                  <i class="bi bi-clipboard"></i>
              </span>
            </div>
            <?php
          }
          ?>
          <button type="submit" class="mt-3 btn btn-success btn-sm w-100" name="save_poll" ><i class="bi bi-floppy"></i> Save Changes</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>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        document.querySelectorAll(".copy_tt_link").forEach(function (btn) {
            btn.addEventListener("click", function () {
                let ttLink = this.getAttribute("data-tt-link"); // Get data-tt-link value
                let icon = this.querySelector("i"); // Find the <i> tag inside the button

                // Copy to clipboard
                navigator.clipboard.writeText(ttLink).then(() => {
                    // Change the icon to clipboard-check
                    icon.classList.replace("bi-clipboard", "bi-clipboard-check");

                    // Revert back to clipboard after 2 seconds
                    setTimeout(() => {
                        icon.classList.replace("bi-clipboard-check", "bi-clipboard");
                    }, 2000);
                }).catch(err => {
                    console.error("Failed to copy:", err);
                });
            });
        });
    });
</script>
<?php require_once('inc/footer.php'); ?>
