<?php
use yii\helpers\Html;
use kartik\widgets\ActiveForm;
use kartik\widgets\FileInput;
use kartik\widgets\Select2;
use yii\helpers\ArrayHelper;
use common\widgets\Alert;
use yii\helpers\Url;

$this->registerCssFile('https://www.exploreourindia.com/frontend/web/css/sharetravel.css', ['position' => \yii\web\View::POS_HEAD]);

$this->registerJs("
    $('#upload-form').on('beforeSubmit', function () {
        var form = $(this);

        $.ajax({
            url: form.attr('action'),
            type: 'post',
            data: new FormData(this),
            processData: false,
            contentType: false,
            success: function (response) {
                if (response.success) {
                    $('#modalForm').modal('hide');
                    alert('Form submitted successfully');
                } else {
                    alert('Error occurred');
                }
            }
        });
        return false;
    });
");
?>  
<!-- LEFT -->
    <div class="col-left" aria-hidden="true">
      <div class="hero">Explore • Capture • Inspire<br>
        <small style="opacity:.95;font-weight:600">Share moments that spark journeys</small></div>
    </div>
	<!-- RIGHT -->
    <div class="col-right">
      <button class="close-btn" aria-label="Close dialog" onclick="closePopup()">✕</button>
      <h2 id="dialogTitle" class="title">Share Your Travel Story</h2>
      <p class="sub">Tell fellow explorers about your journey — photos welcome!</p>
      <?php $form = ActiveForm::begin(['id' => 'upload-form',
         'options' => ['enctype' => 'multipart/form-data'],
         'fieldConfig' => [
			'template' => "{input}{error}",
		],
	]); ?>
        <?= $form->field($model, 'name')->textInput(['placeholder' => $model->getAttributeLabel('name')]) ?>
        <?= $form->field($model, 'email')->textInput(['placeholder' => $model->getAttributeLabel('email')]) ?>
        <?= $form->field($model, 'contact_no')->textInput(['placeholder' => $model->getAttributeLabel('contact_no')]) ?>
        <?=$form->field($model, 'message')->textArea(['placeholder' => 'Write your travel experience...']) ?>
        <div class="form-row" style="margin-top:10px;">
          <div class="file-area">
            <label class="file-label" for="imgInput" id="fileLabel" tabindex="0" role="button" aria-controls="previewArea"> + Upload Your pic </label>
            <!-- hidden file input -->
            <input id="imgInput" type="file" name="ShareYourTravelStory[img]" accept="image/*" style="display:none" />
            <div style="flex:1"></div>
          </div>          
          <!-- preview area -->
          <div id="previewArea" class="preview-area" aria-live="polite"></div>
        </div>
        <button type="submit" class="submit-btn">Submit</button>
      <?php ActiveForm::end(); ?>
    </div>
<script>
    // Elements
    const imgInputId = 'imgInput';
    let imgInput = document.getElementById(imgInputId);
    const previewArea = document.getElementById('previewArea');
    const fileLabel = document.getElementById('fileLabel');
    const form = document.getElementById('testiForm');
    const successBox = document.getElementById('successBox');


    // Safe clear preview helper
    function clearPreview(){
      previewArea.innerHTML = '';
      // try simple clear
      try {
        imgInput.value = '';
      } catch (err) {
        // fallback: replace with a fresh input
        const newInput = imgInput.cloneNode(false);
        newInput.addEventListener('change', handleFileChange);
        imgInput.parentNode.replaceChild(newInput, imgInput);
        imgInput = newInput;
      }
    }

    // Handle file change & show preview + remove icon
    async function handleFileChange(e){
      const file = (e.target.files && e.target.files[0]) || null;
      // clear previous
      previewArea.innerHTML = '';
      if(!file) return;

      // basic validation: size limit e.g., 5MB (optional)
      const maxMB = 5;
      if(file.size > maxMB * 1024 * 1024){
        alert('Please upload an image smaller than ' + maxMB + 'MB.');
        clearPreview();
        return;
      }

      // create preview wrapper
      const wrap = document.createElement('div');
      wrap.className = 'preview-thumb';

      const img = document.createElement('img');
      img.alt = 'Uploaded photo preview';

      const removeBtn = document.createElement('button');
      removeBtn.type = 'button';
      removeBtn.className = 'remove-btn';
      removeBtn.setAttribute('aria-label', 'Remove uploaded image');
      removeBtn.innerHTML = '×';

      // file name node
      const nameNode = document.createElement('div');
      nameNode.className = 'filename';
      nameNode.textContent = file.name;

      // read file
      const reader = new FileReader();
      reader.onload = function(ev){
        img.src = ev.target.result;
        wrap.appendChild(img);
        wrap.appendChild(removeBtn);
        previewArea.appendChild(wrap);
        previewArea.appendChild(nameNode);
        // focus remove button so keyboard users can remove quickly
        removeBtn.focus();
      };
      reader.readAsDataURL(file);

      // remove handler
      removeBtn.addEventListener('click', function(){
        clearPreview();
        // return focus to upload label (accessibility)
        fileLabel.focus();
      });

      removeBtn.addEventListener('keydown', function(evt){
        if(evt.key === 'Enter' || evt.key === ' '){
          evt.preventDefault();
          clearPreview();
          fileLabel.focus();
        }
      });
    }

    // ensure label is keyboard-activatable
    fileLabel.addEventListener('keydown', function(evt){
      if(evt.key === 'Enter' || evt.key === ' '){
        evt.preventDefault();
        imgInput.click();
      }
    });

    // Bind change
    imgInput.addEventListener('change', handleFileChange);
</script>