<div class="content">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="fas fa-birthday-cake me-2"></i>Cake Features</h2>
    <a href="<?= url('dashboard') ?>" class="btn btn-secondary btn-sm"><i class="fas fa-arrow-left me-1"></i>Back</a>
  </div>

  <ul class="nav nav-tabs" role="tablist">
    <li class="nav-item">
      <a class="nav-link" data-bs-toggle="tab" href="#flavors">Flavors</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" data-bs-toggle="tab" href="#sizes">Sizes</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" data-bs-toggle="tab" href="#types">Types</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" data-bs-toggle="tab" href="#pricing">Pricing</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" data-bs-toggle="tab" href="#locations">Pickup Locations</a>
    </li>
  </ul>

  <div class="tab-content mt-3">
    <!-- Flavors Tab -->
    <div id="flavors" class="tab-pane fade">
      <div class="card">
        <div class="card-header d-flex justify-content-between">
          <span>Cake Flavors</span>
          <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addFlavorModal">
            <i class="fas fa-plus me-1"></i>Add Flavor
          </button>
        </div>
        <div class="card-body">
          <table class="table table-sm">
            <thead>
              <tr>
                <th>Name (PL)</th>
                <th>Name (EN)</th>
                <th>Image URL</th>
                <th>Sort</th>
                <th>Active</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach($flavors as $flavor): ?>
              <tr>
                <td><?= htmlspecialchars($flavor['name']) ?></td>
                <td><?= htmlspecialchars($flavor['name_en'] ?? '') ?></td>
                <td><?= htmlspecialchars(substr($flavor['image_url'] ?? '', 0, 30)) ?></td>
                <td><?= $flavor['sort_order'] ?></td>
                <td><?= $flavor['active'] ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>' ?></td>
                <td>
                  <button class="btn btn-sm btn-warning" onclick="editFlavor(<?= htmlspecialchars(json_encode($flavor)) ?>)">
                    <i class="fas fa-edit"></i>
                  </button>
                  <form method="POST" action="<?= url('cake-features/flavor/' . $flavor['id'] . '/delete') ?>" class="d-inline" onsubmit="return confirm('Delete?')">
                    <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                  </form>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Sizes Tab -->
    <div id="sizes" class="tab-pane fade">
      <div class="card">
        <div class="card-header d-flex justify-content-between">
          <span>Cake Sizes</span>
          <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addSizeModal">
            <i class="fas fa-plus me-1"></i>Add Size
          </button>
        </div>
        <div class="card-body">
          <table class="table table-sm">
            <thead>
              <tr>
                <th>Name (PL)</th>
                <th>Name (EN)</th>
                <th>Image URL</th>
                <th>Sort</th>
                <th>Active</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach($sizes as $size): ?>
              <tr>
                <td><?= htmlspecialchars($size['name']) ?></td>
                <td><?= htmlspecialchars($size['name_en'] ?? '') ?></td>
                <td><?= htmlspecialchars(substr($size['image_url'] ?? '', 0, 30)) ?></td>
                <td><?= $size['sort_order'] ?></td>
                <td><?= $size['active'] ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>' ?></td>
                <td>
                  <button class="btn btn-sm btn-warning" onclick="editSize(<?= htmlspecialchars(json_encode($size)) ?>)">
                    <i class="fas fa-edit"></i>
                  </button>
                  <form method="POST" action="<?= url('cake-features/size/' . $size['id'] . '/delete') ?>" class="d-inline" onsubmit="return confirm('Delete?')">
                    <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                  </form>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Types Tab -->
    <div id="types" class="tab-pane fade">
      <div class="card">
        <div class="card-header d-flex justify-content-between">
          <span>Cake Types</span>
          <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addTypeModal">
            <i class="fas fa-plus me-1"></i>Add Type
          </button>
        </div>
        <div class="card-body">
          <table class="table table-sm">
            <thead>
              <tr>
                <th>Name (PL)</th>
                <th>Name (EN)</th>
                <th>Price</th>
                <th>Sort</th>
                <th>Active</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach($types as $type): ?>
              <tr>
                <td><?= htmlspecialchars($type['name']) ?></td>
                <td><?= htmlspecialchars($type['name_en'] ?? '') ?></td>
                <td><?= number_format($type['price'] ?? 0, 2) ?> PLN</td>
                <td><?= $type['sort_order'] ?></td>
                <td><?= $type['active'] ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>' ?></td>
                <td>
                  <button class="btn btn-sm btn-warning" onclick="editType(<?= htmlspecialchars(json_encode($type)) ?>)">
                    <i class="fas fa-edit"></i>
                  </button>
                  <form method="POST" action="<?= url('cake-features/type/' . $type['id'] . '/delete') ?>" class="d-inline" onsubmit="return confirm('Delete?')">
                    <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                  </form>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Pricing Tab -->
    <div id="pricing" class="tab-pane fade">
      <div class="card">
        <div class="card-header">
          <span>Flavor Pricing (Price per Size)</span>
        </div>
        <div class="card-body">
          <form method="POST" action="<?= url('cake-features/pricing/update') ?>">
            <div class="table-responsive">
              <table class="table table-bordered table-sm">
                <thead>
                  <tr>
                    <th>Flavor</th>
                    <?php foreach($sizes as $size): ?>
                      <th><?= htmlspecialchars($size['name']) ?></th>
                    <?php endforeach; ?>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach($flavors as $flavor): ?>
                  <tr>
                    <td><?= htmlspecialchars($flavor['name']) ?></td>
                    <?php foreach($sizes as $size): 
                      $price = 0;
                      foreach($pricing as $p) {
                        if ($p['flavor_id'] == $flavor['id'] && $p['size_id'] == $size['id']) {
                          $price = $p['price'];
                          break;
                        }
                      }
                    ?>
                      <td>
                        <div class="input-group input-group-sm">
                          <input type="number" step="0.01" min="0" 
                                 name="pricing[<?= $flavor['id'] ?>][<?= $size['id'] ?>]" 
                                 value="<?= number_format($price, 2, '.', '') ?>" 
                                 class="form-control form-control-sm" 
                                 style="max-width: 100px;">
                          <span class="input-group-text">PLN</span>
                        </div>
                      </td>
                    <?php endforeach; ?>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
            <button type="submit" class="btn btn-primary mt-3">Save All Pricing</button>
          </form>
        </div>
      </div>
    </div>

    <!-- Locations Tab -->
    <div id="locations" class="tab-pane fade">
      <div class="card">
        <div class="card-header d-flex justify-content-between">
          <span>Pickup Locations</span>
          <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addLocationModal">
            <i class="fas fa-plus me-1"></i>Add Location
          </button>
        </div>
        <div class="card-body">
          <table class="table table-sm">
            <thead>
              <tr>
                <th>Name</th>
                <th>Address</th>
                <th>Sort</th>
                <th>Active</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach($locations as $location): ?>
              <tr>
                <td><?= htmlspecialchars($location['name']) ?></td>
                <td><?= htmlspecialchars($location['address'] ?? '') ?></td>
                <td><?= $location['sort_order'] ?></td>
                <td><?= $location['active'] ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>' ?></td>
                <td>
                  <button class="btn btn-sm btn-warning" onclick="editLocation(<?= htmlspecialchars(json_encode($location)) ?>)">
                    <i class="fas fa-edit"></i>
                  </button>
                  <form method="POST" action="<?= url('cake-features/location/' . $location['id'] . '/delete') ?>" class="d-inline" onsubmit="return confirm('Delete?')">
                    <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                  </form>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Modals -->
<!-- Add/Edit Flavor Modal -->
<div class="modal fade" id="addFlavorModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="flavorForm" method="POST" action="<?= url('cake-features/flavor/create') ?>">
        <div class="modal-header">
          <h5 class="modal-title">Add Flavor</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="flavor_id" id="flavor_id">
          <div class="mb-3">
            <label class="form-label">Name (Polish)*</label>
            <input type="text" name="name" id="flavor_name" class="form-control" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Name (English)</label>
            <input type="text" name="name_en" id="flavor_name_en" class="form-control">
          </div>
          <div class="mb-3">
            <label class="form-label">Image URL</label>
            <div class="input-group">
              <input type="text" name="image_url" id="flavor_image_url" class="form-control">
              <input type="file" id="flavor_image_file" class="d-none" accept="image/*">
              <button type="button" class="btn btn-outline-secondary" onclick="document.getElementById('flavor_image_file').click()">
                <i class="fas fa-upload"></i> Upload
              </button>
            </div>
            <small class="text-muted">Or enter URL directly</small>
          </div>
          <div class="mb-3">
            <label class="form-label">Sort Order</label>
            <input type="number" name="sort_order" id="flavor_sort_order" class="form-control" value="0">
          </div>
          <div class="form-check">
            <input class="form-check-input" type="checkbox" name="active" id="flavor_active" checked>
            <label class="form-check-label" for="flavor_active">Active</label>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Similar modals for Size, Type, Location (abbreviated for brevity) -->
<div class="modal fade" id="addSizeModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="sizeForm" method="POST" action="<?= url('cake-features/size/create') ?>">
        <div class="modal-header">
          <h5 class="modal-title">Add Size</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="size_id" id="size_id">
          <div class="mb-3">
            <label>Name (Polish)*</label>
            <input type="text" name="name" id="size_name" class="form-control" required>
          </div>
          <div class="mb-3">
            <label>Name (English)</label>
            <input type="text" name="name_en" id="size_name_en" class="form-control">
          </div>
          <div class="mb-3">
            <label>Image URL</label>
            <input type="text" name="image_url" id="size_image_url" class="form-control">
          </div>
          <div class="mb-3">
            <label>Sort Order</label>
            <input type="number" name="sort_order" id="size_sort_order" class="form-control" value="0">
          </div>
          <div class="form-check">
            <input class="form-check-input" type="checkbox" name="active" id="size_active" checked>
            <label class="form-check-label">Active</label>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="addTypeModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="typeForm" method="POST" action="<?= url('cake-features/type/create') ?>">
        <div class="modal-header">
          <h5 class="modal-title">Add Type</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="type_id" id="type_id">
          <div class="mb-3">
            <label>Name (Polish)*</label>
            <input type="text" name="name" id="type_name" class="form-control" required>
          </div>
          <div class="mb-3">
            <label>Name (English)</label>
            <input type="text" name="name_en" id="type_name_en" class="form-control">
          </div>
          <div class="mb-3">
            <label>Price (PLN)</label>
            <input type="number" step="0.01" min="0" name="price" id="type_price" class="form-control" value="0">
          </div>
          <div class="mb-3">
            <label>Sort Order</label>
            <input type="number" name="sort_order" id="type_sort_order" class="form-control" value="0">
          </div>
          <div class="form-check">
            <input class="form-check-input" type="checkbox" name="active" id="type_active" checked>
            <label class="form-check-label">Active</label>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="addLocationModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="locationForm" method="POST" action="<?= url('cake-features/location/create') ?>">
        <div class="modal-header">
          <h5 class="modal-title">Add Location</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="location_id" id="location_id">
          <div class="mb-3">
            <label>Name*</label>
            <input type="text" name="name" id="location_name" class="form-control" required>
          </div>
          <div class="mb-3">
            <label>Address</label>
            <textarea name="address" id="location_address" class="form-control" rows="2"></textarea>
          </div>
          <div class="mb-3">
            <label>Sort Order</label>
            <input type="number" name="sort_order" id="location_sort_order" class="form-control" value="0">
          </div>
          <div class="form-check">
            <input class="form-check-input" type="checkbox" name="active" id="location_active" checked>
            <label class="form-check-label">Active</label>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function editFlavor(flavor) {
  document.getElementById('flavorForm').action = '<?= url('cake-features/flavor') ?>/' + flavor.id + '/update';
  document.getElementById('flavor_name').value = flavor.name;
  document.getElementById('flavor_name_en').value = flavor.name_en || '';
  document.getElementById('flavor_image_url').value = flavor.image_url || '';
  document.getElementById('flavor_sort_order').value = flavor.sort_order;
  document.getElementById('flavor_active').checked = flavor.active == 1;
  document.querySelector('#addFlavorModal .modal-title').textContent = 'Edit Flavor';
  new bootstrap.Modal(document.getElementById('addFlavorModal')).show();
}

function editSize(size) {
  document.getElementById('sizeForm').action = '<?= url('cake-features/size') ?>/' + size.id + '/update';
  document.getElementById('size_name').value = size.name;
  document.getElementById('size_name_en').value = size.name_en || '';
  document.getElementById('size_image_url').value = size.image_url || '';
  document.getElementById('size_sort_order').value = size.sort_order;
  document.getElementById('size_active').checked = size.active == 1;
  document.querySelector('#addSizeModal .modal-title').textContent = 'Edit Size';
  new bootstrap.Modal(document.getElementById('addSizeModal')).show();
}

function editType(type) {
  document.getElementById('typeForm').action = '<?= url('cake-features/type') ?>/' + type.id + '/update';
  document.getElementById('type_name').value = type.name;
  document.getElementById('type_name_en').value = type.name_en || '';
  document.getElementById('type_price').value = type.price || 0;
  document.getElementById('type_sort_order').value = type.sort_order;
  document.getElementById('type_active').checked = type.active == 1;
  document.querySelector('#addTypeModal .modal-title').textContent = 'Edit Type';
  new bootstrap.Modal(document.getElementById('addTypeModal')).show();
}

function editLocation(location) {
  document.getElementById('locationForm').action = '<?= url('cake-features/location') ?>/' + location.id + '/update';
  document.getElementById('location_name').value = location.name;
  document.getElementById('location_address').value = location.address || '';
  document.getElementById('location_sort_order').value = location.sort_order;
  document.getElementById('location_active').checked = location.active == 1;
  document.querySelector('#addLocationModal .modal-title').textContent = 'Edit Location';
  new bootstrap.Modal(document.getElementById('addLocationModal')).show();
}

// Handle flavor image upload
document.getElementById('flavor_image_file').addEventListener('change', function(e) {
  const file = e.target.files[0];
  if (!file) return;
  
  const formData = new FormData();
  formData.append('file', file);
  
  fetch('<?= url('api/upload-image') ?>', {
    method: 'POST',
    body: formData
  })
  .then(res => res.json())
  .then(data => {
    if (data.success) {
      document.getElementById('flavor_image_url').value = data.url;
    } else {
      alert('Upload failed: ' + (data.error || 'Unknown error'));
    }
  })
  .catch(err => alert('Upload error: ' + err.message));
});

// Hash navigation for tabs
function activateTabFromHash() {
  const hash = window.location.hash || '#flavors';
  const tabElement = document.querySelector(`a[data-bs-toggle="tab"][href="${hash}"]`);
  if (tabElement) {
    const tab = new bootstrap.Tab(tabElement);
    tab.show();
  }
}

// Activate tab on page load
activateTabFromHash();

// Update tab when hash changes
window.addEventListener('hashchange', activateTabFromHash);

// Update hash when tab is clicked
document.querySelectorAll('a[data-bs-toggle="tab"]').forEach(tab => {
  tab.addEventListener('click', function(e) {
    const hash = this.getAttribute('href');
    if (hash) {
      window.location.hash = hash;
    }
  });
});

</script>

