<?= $this->extend('admin/layout/default') ?>
<?= $this->section('content') ?>

<section class="content-header">
  <div class="container-fluid">
    <div class="row mb-2">
      <div class="col-sm-6">
        <h1>Add Shop</h1>
      </div>
      <div class="col-sm-6">
        <ol class="breadcrumb float-sm-right">
          <li class="breadcrumb-item"><a href="<?php echo url('/') ?>">Home</a></li>
          <li class="breadcrumb-item"><a href="<?php echo url('shops') ?>">Shops</a></li>
          <li class="breadcrumb-item active">Add</li>
        </ol>
      </div>
    </div>
  </div>
</section>

<section class="content">
<?php echo form_open('shops/save', ['class' => 'form-validate', 'autocomplete' => 'off', 'enctype' => 'multipart/form-data']); ?>
  <div class="card">
    <div class="card-body">
      <div class="form-group">
        <label>Name</label>
        <input type="text" class="form-control" name="name" required autofocus>
      </div>
      <div class="form-row">
        <div class="form-group col-md-6">
          <label>Phone</label>
          <input type="text" class="form-control" name="phone">
        </div>
        <div class="form-group col-md-6">
          <label>Status</label>
          <select class="form-control" name="status">
            <option value="1" selected>Active</option>
            <option value="0">Inactive</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label>Address</label>
        <textarea class="form-control" name="address" rows="3"></textarea>
      </div>
      <div class="form-group">
        <label>City</label>
        <select name="city_id" class="form-control select2">
          <option value="">Select</option>
          <?php foreach ($cities as $c): ?>
            <option value="<?php echo $c->id ?>"><?php echo esc($c->label) ?></option>
          <?php endforeach ?>
        </select>
      </div>
      <div class="form-group">
        <label>Category</label>
        <select name="category_id" class="form-control select2">
          <option value="">Select</option>
          <?php foreach ($categories as $cat): ?>
            <option value="<?php echo $cat->id ?>"><?php echo esc($cat->name) ?></option>
          <?php endforeach ?>
        </select>
      </div>
      <div class="form-group">
        <label>Shop Image</label>
        <input type="file" class="form-control" name="image" accept="image/*" id="shopImage" onchange="previewShopImage(this)">
        <div class="mt-2" id="shopImagePreviewWrap" style="display:none;">
          <img src="" class="img-thumbnail" style="max-width: 160px; max-height: 160px;" id="shopImagePreview">
        </div>
      </div>
      <div class="form-group">
        <label>Owner (Shopkeeper user)</label>
        <select name="owner_user_id" id="owner_user_id" class="form-control select2">
          <option value="">Select</option>
          <?php foreach ($shopkeepers as $u): ?>
            <option value="<?php echo $u->id ?>"><?php echo esc($u->name) ?> (<?php echo esc($u->username ?? $u->email) ?>)</option>
          <?php endforeach ?>
        </select>
      </div>
      <hr>
      <h5 class="mb-3">Subscription</h5>
      <div class="form-group">
        <label>Subscription Plan</label>
        <select name="subscription_id" class="form-control select2" required>
          <option value="">Select</option>
          <?php foreach ($subscriptions as $sub): ?>
            <option value="<?php echo $sub->id ?>"><?php echo esc($sub->title) ?> (<?php echo (int) ($sub->duration_months ?? 0) ?> months - <?php echo esc($sub->price ?? 0) ?>)</option>
          <?php endforeach ?>
        </select>
      </div>
      <div class="form-row">
        <div class="form-group col-md-6">
          <label>Subscription Start at (Y-m-d H:i:s)</label>
          <input type="text" class="form-control" name="subscription_start_at" value="<?php echo date('Y-m-d H:i:s') ?>">
        </div>
        <div class="form-group col-md-6">
          <label>Subscription Status</label>
          <select name="subscription_status" class="form-control">
            <option value="ACTIVE" selected>ACTIVE</option>
            <option value="EXPIRED">EXPIRED</option>
            <option value="CANCELLED">CANCELLED</option>
          </select>
        </div>
      </div>
    </div>
    <div class="card-footer">
      <div class="row">
        <div class="col"><a href="<?php echo url('shops') ?>" class="btn btn-flat btn-danger" onclick="return confirm('Leave without saving?')">Cancel</a></div>
        <div class="col text-right"><button type="submit" class="btn btn-flat btn-primary">Save</button></div>
      </div>
    </div>
  </div>
<?php echo form_close(); ?>

<div class="modal fade" id="shopkeeperCreateModal" tabindex="-1" role="dialog" aria-labelledby="shopkeeperCreateModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <form id="shopkeeperCreateForm" autocomplete="off" enctype="multipart/form-data">
        <?= csrf_field() ?>
        <input type="hidden" name="status" value="1">
        <input type="hidden" name="countryid" value="91">
        <div class="modal-header">
          <h5 class="modal-title" id="shopkeeperCreateModalLabel">Add Shopkeeper User</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="alert alert-danger d-none" id="shopkeeperCreateError"></div>
          <div class="form-row">
            <div class="form-group col-md-6">
              <label>Name</label>
              <input type="text" class="form-control" name="name" required>
            </div>
            <div class="form-group col-md-6">
              <label>Contact Number</label>
              <div class="input-group">
                <div class="input-group-prepend">
                  <span class="input-group-text">+91</span>
                </div>
                <input type="text" class="form-control" name="phone" required>
              </div>
            </div>
          </div>
          <div class="form-row">
            <div class="form-group col-md-6">
              <label>Email</label>
              <input type="email" class="form-control" name="email" required>
            </div>
            <div class="form-group col-md-6">
              <label>Username</label>
              <input type="text" class="form-control" name="username" required>
            </div>
          </div>
          <div class="form-row">
            <div class="form-group col-md-6">
              <label>Password</label>
              <input type="password" class="form-control" name="password" minlength="6" required id="skPassword">
            </div>
            <div class="form-group col-md-6">
              <label>Confirm Password</label>
              <input type="password" class="form-control" name="confirm_password" equalTo="#skPassword" required>
            </div>
          </div>
          <div class="form-row">
            <div class="form-group col-md-6">
              <label>Profile Image</label>
              <input type="file" class="form-control" name="profile_image" accept="image/*" id="skProfileImage">
            </div>
            <div class="form-group col-md-6" id="skImagePreviewWrap" style="display:none;">
              <img src="<?php echo userProfile('default') ?>" class="img-circle" width="80" height="80" id="skImagePreview">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary" id="shopkeeperCreateSubmit">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>
</section>

<?= $this->endSection() ?>
<?= $this->section('js') ?>
<script>
  $(document).ready(function() {
    $('.form-validate').validate();
    $('.select2').select2();

    $('#shopkeeperCreateForm').validate();
    initOwnerUserAddIcon();

    $('#skProfileImage').on('change', function() {
      previewShopkeeperImage(this);
    });

    $('#shopkeeperCreateForm').on('submit', function(e) {
      e.preventDefault();
      if (!$(this).valid()) {
        return;
      }
      createShopkeeperUser();
    });
  });

  function initOwnerUserAddIcon() {
    var $select = $('#owner_user_id');
    var $container = $select.next('.select2-container');
    if (!$container.length) {
      return;
    }
    if ($container.find('.select2-add-owner-user').length) {
      return;
    }

    var $selection = $container.find('.select2-selection--single');
    $selection.css('position', 'relative');
    $selection.find('.select2-selection__rendered').css('padding-right', '4.25rem');
    $selection.find('.select2-selection__arrow').before('<span class="select2-add-owner-user" role="button" title="Add Shopkeeper"><i class="fa fa-plus"></i></span>');

    $selection.on('mousedown', '.select2-add-owner-user', function(e) {
      e.preventDefault();
      e.stopPropagation();
      $select.select2('close');
      resetShopkeeperModal();
      $('#shopkeeperCreateModal').modal('show');
    });
  }

  function resetShopkeeperModal() {
    var $form = $('#shopkeeperCreateForm');
    $form[0].reset();
    $('#shopkeeperCreateError').addClass('d-none').text('');
    $('#skImagePreviewWrap').hide();
    $('#skImagePreview').attr('src', '<?php echo userProfile('default') ?>');
    $('#shopkeeperCreateSubmit').prop('disabled', false).text('Save');
  }

  function previewShopkeeperImage(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function(e) {
        $('#skImagePreview').attr('src', e.target.result);
        $('#skImagePreviewWrap').show();
      };
      reader.readAsDataURL(input.files[0]);
      return;
    }
    $('#skImagePreviewWrap').hide();
  }

  function createShopkeeperUser() {
    $('#shopkeeperCreateError').addClass('d-none').text('');
    $('#shopkeeperCreateSubmit').prop('disabled', true).text('Saving...');

    var fd = new FormData(document.getElementById('shopkeeperCreateForm'));
    $.ajax({
      url: '<?php echo url('shops/createShopkeeperUser') ?>',
      type: 'POST',
      data: fd,
      processData: false,
      contentType: false,
      success: function(res) {
        if (res && res.success && res.user) {
          var u = res.user;
          var label = u.name + ' (' + (u.username ? u.username : u.email) + ')';
          var opt = new Option(label, u.id, true, true);
          $('#owner_user_id').append(opt).trigger('change');
          $('#shopkeeperCreateModal').modal('hide');
          return;
        }
        var msg = (res && res.message) ? res.message : 'Unable to create user';
        $('#shopkeeperCreateError').removeClass('d-none').text(msg);
        $('#shopkeeperCreateSubmit').prop('disabled', false).text('Save');
      },
      error: function(xhr) {
        var msg = 'Unable to create user';
        if (xhr && xhr.responseJSON && xhr.responseJSON.message) {
          msg = xhr.responseJSON.message;
        }
        $('#shopkeeperCreateError').removeClass('d-none').text(msg);
        $('#shopkeeperCreateSubmit').prop('disabled', false).text('Save');
      }
    });
  }

  function previewShopImage(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function(e) {
        $('#shopImagePreview').attr('src', e.target.result);
        $('#shopImagePreviewWrap').show();
      };
      reader.readAsDataURL(input.files[0]);
      return;
    }
    $('#shopImagePreviewWrap').hide();
  }
</script>

<style>
  .select2-add-owner-user {
    position: absolute;
    right: 2.1rem;
    top: 50%;
    transform: translateY(-50%);
    padding: 0.1rem 0.35rem;
    background: #ffffff;
    border: 1px solid rgba(0, 123, 255, 0.4);
    border-radius: 0.25rem;
    color: #007bff;
    cursor: pointer;
    z-index: 2;
  }
</style>
<?= $this->endSection() ?>

