<?php require'sidebar.php'; ?>

<!--Page Container--> 
<section class="page-container">
  <div class="page-content-wrapper">

    <!--Main Content-->

    <div class="content sm-gutter">
      <div class="container-fluid padding-25 sm-padding-10">
        <div class="row">
          <div class="col-12">
            <div class="section-title">
              <h5><?php echo _EDITITEM; ?></h5>
            </div>
            
            <?php if (isset($_GET['status'])): ?>
              <div class="alert alert-info"><?php echo htmlspecialchars($_GET['status']); ?></div>
            <?php endif; ?>
            
            <?php if (isset($_GET['error'])): ?>
              <div class="alert alert-danger">Error: <?php echo htmlspecialchars($_GET['error']); ?></div>
            <?php endif; ?>
          </div>

          <div class="col-md-12">

            <div class="form-block mb-4">

              <form enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">

               <input type="hidden" value="<?php echo isset($store['store_id']) ? $store['store_id'] : ''; ?>" name="store_id">

               <div class="form-row">
                <div class="form-group col-md-9">
                  <div class="block col-md-12">

                    <label class="required"><?php echo _TABLEFIELDTITLE; ?></label>
                    <input type="text" value="<?php echo isset($store['store_title']) ? htmlspecialchars($store['store_title']) : ''; ?>" name="store_title" class="form-control" required="">

                    <label><?php echo _TABLEFIELDSLUG; ?></label>
                    <input type="hidden" value="<?php echo isset($store['store_slug']) ? $store['store_slug'] : ''; ?>" name="store_slug_save">
                    <input type="text" placeholder="<?php echo isset($store['store_slug']) ? $store['store_slug'] : ''; ?>" name="store_slug" class="form-control">
                    
                    <label><?php echo _TABLEFIELDDESCRIPTION; ?></label>

                    <textarea type="text" class="mceNoEditor form-control" name="store_description"><?php echo isset($store['store_description']) ? htmlspecialchars($store['store_description']) : ''; ?></textarea>

                    <label class="control-label"><?php echo _TABLEFIELDFEATURED; ?></label>

                    <select class="custom-select form-control" name="store_featured" required="">
                      <?php
                      if($store['store_featured'] == 1)
                      {
                        echo '<option value="1" selected="selected">'._YESTEXT.'</option>';
                        echo '<option value="0">'._NOTEXT.'</option>';

                      }
                      else {
                        echo '<option value="0" selected="selected">'._NOTEXT.'</option>';
                        echo '<option value="1">'._YESTEXT.'</option>';
                      }
                      ?>
                    </select>

                    <br>
                    <br>

                    <fieldset>
                      <legend><?php echo _SEO; ?></legend>

                      <label class="no-margin-top"><?php echo _SEOTITLE; ?></label>
                      <input type="text" value="<?php echo $store['store_seotitle']; ?>" name="store_seotitle" class="form-control">


                      <label><?php echo _SEODESCRIPTION; ?></label>
                      <textarea type="text" class="form-control" name="store_seodescription"><?php echo $store['store_seodescription']; ?></textarea>

                    </fieldset>

                  </div>
                </div>

                <div class="form-group col-md-3 sidebar">

                 <div class="block col-md-12">
                   <label><?php echo _TABLEFIELDSTATUS; ?></label>

                   <select class="custom-select form-control" name="store_status">

                    <?php
                    if($store['store_status'] == 1){
                      echo '<option value="1" selected="selected">'._ENABLED.'</option>';
                      echo '<option value="0">'._DISABLED.'</option>';

                    } else{
                      echo '<option value="0" selected="selected">'._DISABLED.'</option>';
                      echo '<option value="1">'._ENABLED.'</option>';
                    }
                    ?>
                  </select>

                </div>

                <div class="block col-md-12">
                   <label><?php echo _TABLEFIELDCATEGORY; ?></label>
                   
                   <?php 
                   // Get current store categories
                   // Ensure $store_categories is set
                   if (!isset($store_categories)) {
                     $store_categories = array();
                   }
                   
                   // Group subcategories by parent
                   $subcategories_by_parent = array();
                   foreach($all_subcategories as $sub) {
                     if (!isset($subcategories_by_parent[$sub['subcategory_parent']])) {
                       $subcategories_by_parent[$sub['subcategory_parent']] = array();
                     }
                     $subcategories_by_parent[$sub['subcategory_parent']][] = $sub;
                   }
                   
                   // Find selected parent and subcategory
                   $selected_parent = '';
                   $selected_subcategory = '';
                   
                   // FIRST: Check if any selected category is a subcategory (check this FIRST to avoid ID conflicts)
                   // Only take the FIRST subcategory found
                   $found_subcategory_ids = array();
                   foreach($store_categories as $cat_id) {
                     if (!empty($selected_subcategory)) {
                       break; // Already found a subcategory, stop looking
                     }
                     foreach($all_subcategories as $sub) {
                       if ($sub['subcategory_id'] == $cat_id) {
                         $selected_subcategory = $cat_id;
                         $selected_parent = $sub['subcategory_parent'];
                         $found_subcategory_ids[] = $cat_id;
                         break;
                       }
                     }
                   }
                   
                   // SECOND: If no subcategory found, check for parent categories
                   if (empty($selected_parent)) {
                     foreach($store_categories as $cat_id) {
                       if (in_array($cat_id, $found_subcategory_ids)) {
                         continue;
                       }
                       foreach($categories as $cat) {
                         if ($cat['category_id'] == $cat_id) {
                           $selected_parent = $cat_id;
                           break 2; // Break both loops, we found our parent
                         }
                       }
                     }
                   }
                   ?>
                   
                   <label>Parent Category</label>
                   <select class="form-control" name="parent_category" id="parent_category" onchange="updateSubcategories()" required>
                     <option value="">-- Select Parent Category --</option>
                     <?php foreach($categories as $category): ?>
                       <option value="<?php echo $category['category_id']; ?>" <?php echo ($selected_parent == $category['category_id']) ? 'selected' : ''; ?>>
                         <?php echo htmlspecialchars($category['category_title']); ?>
                       </option>
                     <?php endforeach; ?>
                   </select>
                   
                   <label class="mt-3">Subcategory (Optional)</label>
                   <select class="form-control" name="subcategory" id="subcategory">
                     <option value="">-- No Subcategory --</option>
                   </select>
                   
                   <small class="form-text text-muted mt-2">
                     <i class="fa fa-info-circle"></i> Select a parent category first, then optionally select a subcategory. The store will be assigned to both.
                   </small>
                   
                   <script>
                   // Subcategory data
                   var subcategoryData = <?php echo json_encode($subcategories_by_parent); ?>;
                   var selectedSubcategory = '<?php echo $selected_subcategory; ?>';
                   
                   // Debug logging
                   console.log('=== CATEGORY DEBUG ===');
                   console.log('Store Categories:', <?php echo json_encode($store_categories); ?>);
                   console.log('Selected Parent:', '<?php echo $selected_parent; ?>');
                   console.log('Selected Subcategory:', selectedSubcategory);
                   console.log('Timestamp:', '<?php echo time(); ?>');
                   
                   function updateSubcategories() {
                     var parentId = document.getElementById('parent_category').value;
                     var subcategorySelect = document.getElementById('subcategory');
                     
                     // Clear existing options
                     subcategorySelect.innerHTML = '<option value="">-- No Subcategory --</option>';
                     
                     // Add subcategories for selected parent
                     if (parentId && subcategoryData[parentId]) {
                       subcategoryData[parentId].forEach(function(sub) {
                         var option = document.createElement('option');
                         option.value = sub.subcategory_id;
                         option.textContent = sub.subcategory_title;
                         subcategorySelect.appendChild(option);
                       });
                     }
                   }
                   
                   // Initialize on page load
                   document.addEventListener('DOMContentLoaded', function() {
                     updateSubcategories();
                     if (selectedSubcategory) {
                       document.getElementById('subcategory').value = selectedSubcategory;
                     }
                   });
                   </script>

                </div>

                <div class="block col-md-12">
                  <label><?php echo _TABLEFIELDIMAGE; ?></label>

                  <div class="uk-margin-small">
                    <label class="uk-form-label" style="font-weight: normal; font-size: 13px;">
                      <input type="radio" name="image_type" value="keep" class="uk-radio" checked onchange="toggleEditImageInput()"> Keep Current
                    </label>
                    <label class="uk-form-label" style="font-weight: normal; font-size: 13px; margin-left: 15px;">
                      <input type="radio" name="image_type" value="upload" class="uk-radio" onchange="toggleEditImageInput()"> Upload File
                    </label>
                    <label class="uk-form-label" style="font-weight: normal; font-size: 13px; margin-left: 15px;">
                      <input type="radio" name="image_type" value="url" class="uk-radio" onchange="toggleEditImageInput()"> Image URL
                    </label>
                  </div>

                  <div id="current-image-section">
                    <div style="text-align: center; padding: 10px; border: 1px solid #ddd; border-radius: 8px; background: #f9f9f9;">
                      <img src="../../images/<?php echo $store['store_image']; ?>" style="max-width: 200px; max-height: 200px; border-radius: 8px;">
                      <p class="text-muted" style="margin-top: 10px; font-size: 13px;">Current Image</p>
                    </div>
                  </div>

                  <div id="upload-section" style="display: none;">
                    <div class="new-image" id="image-preview" style="background: url(../../images/<?php echo $store['store_image'] ?>);">
                      <label for="image-upload" id="image-label"><?php echo _CHOOSEFILE; ?></label>
                      <input type="file" name="store_image" id="image-upload" />
                    </div>
                  </div>

                  <div id="url-section" style="display: none;">
                    <input type="url" name="image_url" id="image_url" class="form-control" placeholder="https://example.com/logo.png" oninput="previewEditImageUrl()">
                    <div id="url-preview" style="margin-top: 10px; text-align: center;"></div>
                  </div>

                  <input type="hidden" value="<?php echo $store['store_image']; ?>" name="store_image_save">

                  <span class="text-danger recomendedsize"><?php echo _RECOMMENDEDSIZE; ?> <b>350 x 350</b> </span>
                  <br/>
                </div>

                <!-- CDN Image URL -->
                <div class="block col-md-12">
                  <label>CDN Image URL (Optional)</label>
                  <input type="url" name="store_image_cdn_url" id="store_image_cdn_url" class="form-control" 
                         value="<?php echo isset($store['store_image_cdn_url']) ? htmlspecialchars($store['store_image_cdn_url']) : ''; ?>" 
                         placeholder="https://cdn.example.com/stores/store-image.jpg"
                         oninput="previewStoreCdnUrl()">
                  <small class="form-text text-muted">Enter external CDN URL. If provided, this will be used instead of local image.</small>
                  
                  <!-- CDN Preview -->
                  <div id="cdn-url-preview" style="margin-top: 15px; display: none;">
                    <div style="text-align: center; padding: 10px; border: 2px solid #28a745; border-radius: 8px; background: #f0fff4;">
                      <img id="cdn-url-preview-img" src="" style="max-width: 200px; max-height: 200px; border-radius: 8px;">
                      <p class="text-success" style="margin-top: 10px; font-size: 13px; font-weight: bold;">
                        <i class="fa fa-check-circle"></i> CDN Image Preview
                      </p>
                    </div>
                  </div>
                </div>

                <script>
                function previewStoreCdnUrl() {
                  const cdnUrl = document.getElementById('store_image_cdn_url').value;
                  const previewSection = document.getElementById('cdn-url-preview');
                  const previewImg = document.getElementById('cdn-url-preview-img');
                  
                  if (cdnUrl && cdnUrl.trim() !== '') {
                    previewImg.src = cdnUrl;
                    previewImg.onerror = function() {
                      previewSection.style.display = 'none';
                    };
                    previewImg.onload = function() {
                      previewSection.style.display = 'block';
                    };
                  } else {
                    previewSection.style.display = 'none';
                  }
                }
                
                // Show preview on page load if CDN URL exists
                document.addEventListener('DOMContentLoaded', function() {
                  previewStoreCdnUrl();
                });
                </script>

                <script>
                function toggleEditImageInput() {
                  const currentSection = document.getElementById('current-image-section');
                  const uploadSection = document.getElementById('upload-section');
                  const urlSection = document.getElementById('url-section');
                  const imageUpload = document.getElementById('image-upload');
                  const imageUrl = document.getElementById('image_url');
                  const selectedType = document.querySelector('input[name="image_type"]:checked').value;
                  
                  currentSection.style.display = 'none';
                  uploadSection.style.display = 'none';
                  urlSection.style.display = 'none';
                  imageUpload.removeAttribute('required');
                  imageUrl.removeAttribute('required');
                  
                  if (selectedType === 'keep') {
                    currentSection.style.display = 'block';
                  } else if (selectedType === 'upload') {
                    uploadSection.style.display = 'block';
                  } else if (selectedType === 'url') {
                    urlSection.style.display = 'block';
                  }
                }
                
                function previewEditImageUrl() {
                  const url = document.getElementById('image_url').value;
                  const preview = document.getElementById('url-preview');
                  
                  if (url && isValidImageUrl(url)) {
                    preview.innerHTML = '<img src="' + url + '" style="max-width: 200px; max-height: 200px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">';
                  } else {
                    preview.innerHTML = '';
                  }
                }
                
                function isValidImageUrl(url) {
                  return url.match(/\.(jpeg|jpg|gif|png|webp|svg)$/i) != null || url.includes('image');
                }
                </script>

                <button class="btn btn-primary" type="submit" name="save"><?php echo _UPDATEITEM; ?></button>
                <button class="btn btn-danger deleteItem" type="button" data-url="../controller/delete_store.php?id=<?php echo $store['store_id']; ?>" data-redirect="../controller/categories.php"><?php echo _DELETEITEM; ?></button>

              </div>
            </div>

          </form>
        </div>
      </div>
    </div>
  </div>
</div>
</div>
</section>
