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

$page_title = 'Edit Story '; // Custom Page Title

if (isset($_GET['story_id'])) {
  $story_id_get = $_GET['story_id'];
  $this_story = showAllttdata("mahamudfutureit_photostories", "WHERE id = '$story_id_get'");
  if (!empty($this_story)) {
    foreach ($this_story as $the_story);
  }else {
    header("Location:404.php");
    exit;
  }
}else {
  header("Location:404.php");
  exit;
}

if (isset($_POST['update_story'])) {
  $post_form_data = array(
    "story_title"      => htmlentities($_POST['story_title'], ENT_QUOTES, 'utf-8'),
    "story_items"      => json_encode($_POST['story_items']),
    "story_cat"         => $_POST['story_cat'],
    "story_date"       => $_POST['story_date'],
    "story_status"      => htmlentities($_POST['story_status'], ENT_QUOTES, 'utf-8'),
  );

   // Insert Database
   $update_data = UpdateData('mahamudfutureit_photostories', 'id', $story_id_get, $post_form_data);
      if ($update_data) {
          header("Location:photo-stories-edit.php?story_id=".$story_id_get);
          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="photo-stories.php" class="btn btn-primary btn-sm"><i class="bi bi-grid"></i> All Stories </a>
    </div>
  </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 mb-3">

            <!-- ***********************
            Story Title
            *************************-->
            <div class="form-group mb-2">
              <label>Story Title <span class="text-danger">*</span> </label>
              <input value="<?php echo $the_story['story_title'] ?>" name="story_title" type="text" class="form-control" placeholder="Story Title" required>
            </div>

            <div class="row g-2" id="storyItems">
              <?php
                $storyData =  json_decode( $the_story['story_items'] ,true);

                for ($i = 1; $i <= 9; $i++) {
                    $storyImage = !empty($storyData[$i]["storyimage"]) ? $storyData[$i]["storyimage"] : 'assets/img/placeholder/story-placeholder.jpg';
                    echo "<div class='col-md-6 col-lg-4 story-single'>
                            <div class='border rounded-2 p-2'>
                              <div class='position-relative'>
                                <textarea class='story-caption' name='story_items[$i][storycaption]' placeholder='Story Caption'>{$storyData[$i]['storycaption']}</textarea>
                                <img class='img-fluid w-100 bg-white' id='psItem{$i}_Preview'
                                     src='{$storyImage}'
                                     style='aspect-ratio: 920 / 1560; object-fit: cover; width: 100%; height: auto; max-height: 1560px;'>
                              </div>
                              <div class='m-0 input-group'>
                                <input id='psItem{$i}' name='story_items[$i][storyimage]' type='url' class='form-control rounded-0 border-success' value='{$storyData[$i]['storyimage']}' 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='#psItem{$i}'>
                                  <i class='bi bi-upload'></i>
                                </a>
                              </div>
                            </div>
                          </div>";
                }
              ?>
            </div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="bg-white rounded-2 p-3">
          <div class="form-group mb-2">
            <label>Story Category <span class="text-danger">*</span> </label>
            <select class="form-control tt-select-single" name="story_cat" 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['CategoryID'] == $the_story['story_cat'])? 'selected' : '' ?>>
                    <?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['CategoryID'] == $the_story['story_cat'])? 'selected' : '' ?>>
                        --<?php echo $tt_sub_category['CategoryName'] ?>
                      </option>
                      <?php
                    }
                  }
                }
              }
              ?>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">Published Date <span class="text-danger">*</span></label>
            <input type="datetime-local"  class="form-control" value="<?php echo $the_story['story_date'] ?>" name="story_date" step="1" required>
              <?php
              if (isPublished($the_story['story_date']) == false) {
                ?>
                <div class="bg-warning mt-2 rounded-2 text-center p-2">
                  Scheduled
                </div>
                <?php
              }
              ?>
          </div>
          <div class="form-group mt-3" >
            <label class="form-label">Publish Status</label>
            <select name="story_status" class="form-select form-control">
              <option value="Published" <?php echo ($the_story['story_status'] == 'Published')? 'selected' : '' ?>>Published</option>
              <option value="Draft" <?php echo ($the_story['story_status'] == 'Draft')? 'selected' : '' ?>>Draft</option>
            </select>
          </div>
          <?php
            if ($the_story['story_status'] == 'Published') {
              ?>
              <div class="input-group mt-3">
                <a target="_blank" href="<?php echo $site_domain."photo-stories/".$the_story['story_url'] ?>/" class="form-control text-muted overflow-hidden" ><?php echo $site_domain."photo-stories/".$the_story['story_url'] ?>/</a>
                <span data-tt-link="<?php echo $site_domain."photo-stories/".$the_story['story_url'] ?>/" 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 w-100" name="update_story" ><i class="bi bi-floppy pe-2"></i> Update Story </button>
        </div>
      </div>
    </form>
  </section>
</main>
<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'); ?>
