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

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

if (isset($_GET['gallery_id'])) {
  $story_id_get = $_GET['gallery_id'];
  $this_story = showAllttdata("mahamudfutureit_gallery", "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(
    "gallery_title"      => htmlentities($_POST['gallery_title'], ENT_QUOTES, 'utf-8'),
    "gallery_items"      => json_encode($_POST['gallery_items'],JSON_UNESCAPED_UNICODE),
    "gallery_author"              => $_POST['Author'],
    "gallery_author_name"         => $_POST['WriterName'],
    "gallery_author_designation"  => $_POST['WriterDesignation'],
    "gallery_date"       => $_POST['gallery_date'],
    "gallery_status"      => htmlentities($_POST['gallery_status'], ENT_QUOTES, 'utf-8'),
  );

   // Insert Database
   $update_data = UpdateData('mahamudfutureit_gallery', 'id', $story_id_get, $post_form_data);
      if ($update_data) {
          header("Location:photo-gallery-edit.php?gallery_id=".$story_id_get);
          exit;
       }else {
         $tt_alert = ttAlert('danger', 'Something went wrong to Update Gallery !');
       }
    }

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-gallery.php" class="btn btn-primary btn-sm"><i class="bi bi-grid"></i> All Gallery </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['gallery_title'] ?>" name="gallery_title" type="text" class="form-control" placeholder="Story Title" required>
            </div>

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

                for ($i = 1; $i <= 10; $i++) {
                    $storyImage = !empty($storyData[$i]["storyimage"]) ? $storyData[$i]["storyimage"] : 'assets/img/placeholder/story-placeholder.jpg';
                    echo "<div class='col-md-12 col-lg-6 story-single'>
                            <div class='border rounded-2 p-2'>
                              <div>
                                <img class='img-fluid w-100 bg-white' id='psItem{$i}_Preview'
                                     src='{$storyImage}'
                                     style='aspect-ratio: 1280 / 720; object-fit: cover; width: 100%; height: auto; max-height: 720;'>
                              </div>
                              <div class='m-0 input-group my-2'>
                                <input id='psItem{$i}' name='gallery_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>
                                <textarea class='form-control '  name='gallery_items[$i][storycaption]' placeholder='Story Caption'>{$storyData[$i]['storycaption']}</textarea>

                            </div>
                          </div>";
                }
              ?>
            </div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="bg-white rounded-2 p-3">
          <!-- ***********************
          Guest Writer Name
          *************************-->
          <div class="form-group mt-3">
            <label for="WriterName" class="form-label">Guest Writer Name</label>
            <input type="text" value="<?php echo $the_story['gallery_author_name'] ?>" class="form-control" name="WriterName" id="WriterName" placeholder="Writer Name">
          </div>

          <!-- ***********************
          Guest Writer Designation
          *************************-->
          <div class="form-group mt-3">
            <label for="WriterDesignation" class="form-label">Guest Writer Designation</label>
            <input type="text" value="<?php echo $the_story['gallery_author_designation'] ?>" class="form-control" name="WriterDesignation" id="WriterDesignation" placeholder="Writer Designation">
          </div>

          <!-- ***********************
          Select Writer
          *************************-->
          <div class="form-group mt-3">
            <label>Article Writer  </label>
            <select class="form-control tt-select-single" name="Author">
              <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['UserID'] == $the_story['gallery_author'])?  'selected' : ''; ?>><?php echo $the_writer['UserName']; echo ($the_writer['UserDesignation'] !='')?  ' - '.$the_writer['UserDesignation'] : ''; ?> </option>
                <?php
              }
              ?>
            </select>
          </div>
          <hr>
          <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['gallery_date'] ?>" name="gallery_date" step="1" required>
              <?php
              if (isPublished($the_story['gallery_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="gallery_status" class="form-select form-control">
              <option value="Published" <?php echo ($the_story['gallery_status'] == 'Published')? 'selected' : '' ?>>Published</option>
              <option value="Draft" <?php echo ($the_story['gallery_status'] == 'Draft')? 'selected' : '' ?>>Draft</option>
            </select>
          </div>
          <?php
            if ($the_story['gallery_status'] == 'Published') {
              ?>
              <div class="input-group mt-3">
                <a target="_blank" href="<?php echo $site_domain."photos/".$the_story['gallery_url'] ?>/" class="form-control text-muted overflow-hidden" ><?php echo $site_domain."photos/".$the_story['gallery_url'] ?>/</a>
                <span data-tt-link="<?php echo $site_domain."photos/".$the_story['gallery_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 Gallery </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'); ?>
