<?php
// =============================================
// SHARK CRM - Items (Products & Services)
// =============================================

// Get categories
$categories = $conn->query("SELECT * FROM categories WHERE account_id = $account_id ORDER BY name");

// Get item types
$item_types = $conn->query("SELECT * FROM item_type");

// Get items with joins
$items = $conn->query("
    SELECT i.*, it.name as type_name, c.name as category_name, c.color as category_color
    FROM items i
    LEFT JOIN item_type it ON i.items_type_id = it.id
    LEFT JOIN categories c ON i.category_id = c.id
    WHERE i.account_id = $account_id
    ORDER BY i.date_created DESC
");


?>

<style>
/* =============================================
   IMAGE GALLERY
   ============================================= */
.image-gallery {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    margin-top: 12px;
}
.gallery-item {
    position: relative;
    width: 90px;
    height: 90px;
    border-radius: 10px;
    overflow: hidden;
    border: 2px solid var(--border);
    cursor: pointer;
    transition: border-color .2s, transform .2s;
}
.gallery-item:hover { transform: scale(1.04); }
.gallery-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.gallery-item.primary { border-color: var(--primary); }
.gallery-item .remove-img {
    position: absolute;
    top: 4px;
    right: 4px;
    background: rgba(0,0,0,.65);
    color: #fff;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 11px;
    cursor: pointer;
    transition: background .15s;
    z-index: 2;
}
.gallery-item .remove-img:hover { background: #e53e3e; }
.gallery-item .img-badge {
    position: absolute;
    bottom: 4px;
    left: 4px;
    font-size: 9px;
    font-weight: 700;
    letter-spacing: .3px;
    padding: 2px 6px;
    border-radius: 4px;
    cursor: pointer;
    z-index: 2;
    transition: opacity .15s;
}
.gallery-item .img-badge.is-primary {
    background: var(--primary);
    color: #fff;
    cursor: default;
}
.gallery-item .img-badge.set-primary {
    background: rgba(0,0,0,.55);
    color: #fff;
}
.gallery-item .img-badge.set-primary:hover { opacity: .8; }

/* preview badge */
.gallery-item .preview-label {
    position: absolute;
    bottom: 4px;
    right: 4px;
    font-size: 9px;
    background: rgba(0,0,0,.5);
    color: #fff;
    padding: 2px 5px;
    border-radius: 4px;
}

/* drop zone */
.drop-zone {
    border: 2px dashed var(--border);
    border-radius: 10px;
    padding: 20px;
    text-align: center;
    color: var(--text-muted);
    font-size: 13px;
    cursor: pointer;
    transition: border-color .2s, background .2s;
    position: relative;
}
.drop-zone:hover, .drop-zone.dragover {
    border-color: var(--primary);
    background: color-mix(in srgb, var(--primary) 5%, transparent);
}
.drop-zone input[type=file] {
    position: absolute;
    inset: 0;
    opacity: 0;
    cursor: pointer;
    width: 100%;
    height: 100%;
}

/* item type badge */
.item-type-tag {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 3px 9px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}
.item-type-tag.product {
    background: #dbeafe;
    color: #1d4ed8;
}
.item-type-tag.service {
    background: #d1fae5;
    color: #065f46;
}

/* table image thumb */
.item-thumb {
    width: 42px;
    height: 42px;
    object-fit: cover;
    border-radius: 8px;
    border: 1px solid var(--border);
}
.item-thumb-placeholder {
    width: 42px;
    height: 42px;
    background: var(--bg-base);
    border-radius: 8px;
    border: 1px solid var(--border);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
}
</style>

<div class="fade-in">

  <!-- TOOLBAR -->
  <div class="toolbar" style="flex-wrap:wrap;gap:12px;">
    <div class="search-wrap" style="flex:1;min-width:200px;">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
      </svg>
      <input type="text" id="itemSearch" placeholder="Search items...">
    </div>
    <button class="btn btn-secondary" onclick="openModal('categoryModal')">📁 Categories</button>
    <button class="btn btn-primary" data-permission="add" onclick="openAddItem()">+ Add Item</button>
  </div>

  <!-- ITEMS TABLE -->
  <div class="card">
    <div class="table-wrapper">
      <table class="crm-table" id="itemsTable">
        <thead>
          <tr>
            <th style="width:56px;">Image</th>
            <th>Item</th>
            <th>Type</th>
            <th>Category</th>
            <th>Description</th>
            <th>Price</th>
            <th>Created</th>
            <th style="width:110px;">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($items->num_rows === 0): ?>
          <tr>
            <td colspan="8" class="text-center text-muted" style="padding:50px 20px;">
              <div style="font-size:36px;margin-bottom:10px;">📦</div>
              No items yet — add your first product or service!
            </td>
          </tr>
          <?php else: ?>
          <?php while ($item = $items->fetch_assoc()):
            // Get primary image
            $img_q = $conn->query("
                SELECT image_path FROM item_images
                WHERE item_id = {$item['id']} AND is_primary = 1 LIMIT 1
            ");
            $primary_img = $img_q->fetch_assoc();
            $type_slug   = strtolower($item['type_name'] ?? 'product');
          ?>
          <tr>
            <td>
              <?php if ($primary_img): ?>
                <img class="item-thumb"
                     src="<?=  getUserUploadUrl() . htmlspecialchars($primary_img['image_path']) ?>"
                     alt="<?= htmlspecialchars($item['name']) ?>">
              <?php else: ?>
                <div class="item-thumb-placeholder">
                  <?= $type_slug === 'product' ? '📦' : '⚙️' ?>
                </div>
              <?php endif; ?>
            </td>
            <td>
              <div class="font-bold"><?= htmlspecialchars($item['name']) ?></div>
            </td>
            <td>
              <span class="item-type-tag <?= $type_slug ?>">
                <?= $type_slug === 'product' ? '📦' : '⚙️' ?>
                <?= htmlspecialchars($item['type_name'] ?? '') ?>
              </span>
            </td>
            <td>
              <?php if ($item['category_name']): ?>
                <span style="
                  background: <?= htmlspecialchars($item['category_color']) ?>22;
                  color: <?= htmlspecialchars($item['category_color']) ?>;
                  padding: 4px 10px;
                  border-radius: 20px;
                  font-size: 12px;
                  font-weight: 600;
                ">
                  <?= htmlspecialchars($item['category_name']) ?>
                </span>
              <?php else: ?>
                <span class="text-muted">—</span>
              <?php endif; ?>
            </td>
            <td class="text-secondary" style="max-width:200px;">
              <div class="truncate" title="<?= htmlspecialchars($item['description'] ?? '') ?>">
                <?= htmlspecialchars($item['description'] ?: '—') ?>
              </div>
            </td>
            <td class="text-accent font-bold">
              $<?= number_format($item['price'], 2) ?>
            </td>
            <td class="text-muted text-xs">
              <?= formatDate($item['date_created']) ?>
            </td>
            <td>
              <div class="d-flex gap-8">
                <button class="btn btn-secondary btn-sm"
                        onclick="editItem(<?= $item['id'] ?>)">Edit</button>
                <button class="btn btn-danger btn-sm"
                        onclick="deleteItem(<?= $item['id'] ?>, '<?= addslashes($item['name']) ?>')">Del</button>
              </div>
            </td>
          </tr>
          <?php endwhile; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

</div><!-- /fade-in -->


<!-- =============================================
     ADD / EDIT ITEM MODAL
     ============================================= -->
<div class="modal-overlay" id="addItemModal">
  <div class="modal modal-lg">

    <div class="modal-header">
      <span class="modal-title" id="itemModalTitle">Add Item</span>
      <button class="modal-close" onclick="closeModal('addItemModal')">✕</button>
    </div>

    <div class="modal-body">
      <form id="addItemForm" enctype="multipart/form-data">
        <input type="hidden" name="edit_id" id="editItemId" value="">

        <!-- Name -->
        <div class="form-group">
          <label class="form-label">Item Name <span style="color:var(--danger)">*</span></label>
          <input type="text" name="name" id="itemName" class="form-control"
                 placeholder="e.g. Web Design Package" required>
        </div>

        <!-- Type / Category / Price -->
        <div class="form-grid">
          <div class="form-group">
            <label class="form-label">Type <span style="color:var(--danger)">*</span></label>
            <select name="items_type_id" id="itemType" class="form-control" required>
              <option value="">Select type...</option>
              <?php $item_types->data_seek(0); while ($t = $item_types->fetch_assoc()): ?>
              <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['name']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">Category</label>
            <select name="category_id" id="itemCategory" class="form-control">
              <option value="">— No category —</option>
              <?php $categories->data_seek(0); while ($cat = $categories->fetch_assoc()): ?>
              <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">Price ($)</label>
            <input type="number" name="price" id="itemPrice"
                   class="form-control" step="0.01" min="0" value="0.00">
          </div>
        </div>

        <!-- Description -->
        <div class="form-group">
          <label class="form-label">Description</label>
          <textarea name="description" id="itemDescription"
                    class="form-control" rows="3"
                    placeholder="Optional description..."></textarea>
        </div>

        <!-- Images -->
        <div class="form-group">
          <label class="form-label">Images</label>
          <div class="drop-zone" id="dropZone">
            <input type="file" name="images[]" id="itemImages"
                   accept="image/*" multiple>
            <div id="dropZoneLabel">
              🖼️ Click to upload or drag & drop images here
              <div style="font-size:11px;margin-top:4px;">
                JPG, PNG, WEBP, GIF — max 5MB each
              </div>
            </div>
          </div>
          <!-- Existing saved images + new previews -->
          <div id="imageGallery" class="image-gallery"></div>
        </div>

      </form>
    </div>

    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('addItemModal')">Cancel</button>
      <button class="btn btn-primary" id="saveItemBtn" data-permission="add" onclick="submitItem()">
        Save Item
      </button>
    </div>

  </div>
</div>


<!-- =============================================
     MANAGE CATEGORIES MODAL
     ============================================= -->
<div class="modal-overlay" id="categoryModal">
  <div class="modal modal-md">

    <div class="modal-header">
      <span class="modal-title">Manage Categories</span>
      <button class="modal-close" onclick="closeModal('categoryModal')">✕</button>
    </div>

    <div class="modal-body">
      <div style="margin-bottom:16px;">
        <button class="btn btn-primary btn-sm" onclick="openAddCategoryForm()">
          + New Category
        </button>
      </div>
      <div id="categoriesList">
        <?php $categories->data_seek(0); while ($cat = $categories->fetch_assoc()): ?>
        <div class="category-row"
             data-id="<?= $cat['id'] ?>"
             style="display:flex;align-items:center;justify-content:space-between;
                    padding:12px 4px;border-bottom:1px solid var(--border);">
          <div style="display:flex;align-items:center;gap:12px;">
            <div style="width:34px;height:34px;border-radius:8px;flex-shrink:0;
                        background:<?= htmlspecialchars($cat['color']) ?>;"></div>
            <div>
              <div class="font-bold" style="font-size:14px;">
                <?= htmlspecialchars($cat['name']) ?>
              </div>
              <?php if ($cat['description']): ?>
              <div class="text-muted text-xs">
                <?= htmlspecialchars($cat['description']) ?>
              </div>
              <?php endif; ?>
            </div>
          </div>
          <div class="d-flex gap-8">
            <button class="btn btn-secondary btn-sm"
                    onclick="editCategory(<?= $cat['id'] ?>)">Edit</button>
            <button class="btn btn-danger btn-sm"
                    onclick="deleteCategory(<?= $cat['id'] ?>, '<?= addslashes($cat['name']) ?>')">Del</button>
          </div>
        </div>
        <?php endwhile; ?>
      </div>
    </div>

  </div>
</div>


<!-- =============================================
     ADD / EDIT CATEGORY FORM MODAL
     ============================================= -->
<div class="modal-overlay" id="categoryFormModal">
  <div class="modal modal-sm">

    <div class="modal-header">
      <span class="modal-title" id="categoryFormTitle">Add Category</span>
      <button class="modal-close" onclick="closeModal('categoryFormModal')">✕</button>
    </div>

    <div class="modal-body">
      <form id="categoryForm">
        <input type="hidden" name="edit_id" id="editCategoryId" value="">
        <div class="form-group">
          <label class="form-label">Name <span style="color:var(--danger)">*</span></label>
          <input type="text" name="name" class="form-control"
                 placeholder="Category name" required>
        </div>
        <div class="form-group">
          <label class="form-label">Color</label>
          <input type="color" name="color" class="form-control" value="#3B82F6"
                 style="height:42px;padding:4px 8px;cursor:pointer;">
        </div>
        <div class="form-group">
          <label class="form-label">Description</label>
          <textarea name="description" class="form-control" rows="2"
                    placeholder="Optional..."></textarea>
        </div>
      </form>
    </div>

    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('categoryFormModal')">Cancel</button>
      <button class="btn btn-primary" onclick="submitCategory()">Save Category</button>
    </div>

  </div>
</div>


<!-- =============================================
     JAVASCRIPT
     ============================================= -->
<script>
// ── Config ──────────────────────────────────────
let currentItemId  = 0;
const UPLOAD_URL   = "<?php echo getUserUploadUrl(); ?>";

// ── Search ──────────────────────────────────────
document.getElementById('itemSearch').addEventListener('input', function () {
    const q = this.value.toLowerCase();
    document.querySelectorAll('#itemsTable tbody tr').forEach(row => {
        row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none';
    });
});

// ── Open Add Modal (clean state) ─────────────────
function openAddItem() {
    document.getElementById('addItemForm').reset();
    document.getElementById('editItemId').value      = '';
    document.getElementById('itemModalTitle').textContent = 'Add Item';
    document.getElementById('imageGallery').innerHTML = '';
    document.getElementById('dropZoneLabel').innerHTML =
        '🖼️ Click to upload or drag &amp; drop images here' +
        '<div style="font-size:11px;margin-top:4px;">JPG, PNG, WEBP, GIF — max 5MB each</div>';
    currentItemId = 0;
    openModal('addItemModal');
}

// ── Image Preview (file input) ───────────────────
document.getElementById('itemImages').addEventListener('change', function () {
    renderNewPreviews(this.files);
});

// Drag & drop
const dropZone = document.getElementById('dropZone');
dropZone.addEventListener('dragover',  e => { e.preventDefault(); dropZone.classList.add('dragover'); });
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover'));
dropZone.addEventListener('drop', e => {
    e.preventDefault();
    dropZone.classList.remove('dragover');
    const dt = e.dataTransfer;
    if (dt.files.length) {
        document.getElementById('itemImages').files = dt.files;
        renderNewPreviews(dt.files);
    }
});

function renderNewPreviews(files) {
    // Remove old temp previews only
    document.querySelectorAll('.preview-temp').forEach(el => el.remove());

    const gallery   = document.getElementById('imageGallery');
    const hasExisting = gallery.querySelectorAll('.gallery-item:not(.preview-temp)').length > 0;

    Array.from(files).forEach((file, i) => {
        if (!file.type.startsWith('image/')) return;
        const reader = new FileReader();
        reader.onload = e => {
            const isPrimary = !hasExisting && i === 0;
            const div = document.createElement('div');
            div.className = 'gallery-item preview-temp' + (isPrimary ? ' primary' : '');
            div.innerHTML = `
                <img src="${e.target.result}" alt="preview">
                ${isPrimary
                    ? '<div class="img-badge is-primary">Primary</div>'
                    : '<div class="preview-label">New</div>'}
            `;
            gallery.appendChild(div);
        };
        reader.readAsDataURL(file);
    });

    // Update drop zone label
    document.getElementById('dropZoneLabel').innerHTML =
        `✅ ${files.length} file${files.length > 1 ? 's' : ''} selected`;
}

// ── Submit Item ──────────────────────────────────
async function submitItem() {
    const btn    = document.getElementById('saveItemBtn');
    const form   = document.getElementById('addItemForm');
    const editId = document.getElementById('editItemId').value;

    btn.disabled    = true;
    btn.textContent = 'Saving...';

    const fd = new FormData(form);
    fd.set('action', editId ? 'edit' : 'add');

    try {
        const res = await apiCall('handlers/items.php', fd);
        if (res.success) {
            showToast(editId ? 'Item updated!' : 'Item added!', 'success');
            closeModal('addItemModal');
            setTimeout(() => location.reload(), 600);
        } else {
            showToast(res.message || 'Error saving item', 'error');
        }
    } catch (err) {
        showToast('Network error', 'error');
    } finally {
        btn.disabled    = false;
        btn.textContent = 'Save Item';
    }
}

// ── Edit Item ────────────────────────────────────
async function editItem(id) {
    currentItemId = id;

    const res = await apiCall('handlers/items.php', { action: 'get', id });
    if (!res.success) { showToast('Failed to load item', 'error'); return; }

    const it = res.data;
    document.getElementById('editItemId').value          = id;
    document.getElementById('itemName').value            = it.name        || '';
    document.getElementById('itemType').value            = it.items_type_id || '';
    document.getElementById('itemCategory').value        = it.category_id  || '';
    document.getElementById('itemPrice').value           = it.price        || '0.00';
    document.getElementById('itemDescription').value     = it.description  || '';
    document.getElementById('itemModalTitle').textContent = 'Edit Item';

    // Reset file input label
    document.getElementById('dropZoneLabel').innerHTML =
        '🖼️ Click to upload or drag &amp; drop <strong>new</strong> images here' +
        '<div style="font-size:11px;margin-top:4px;">Existing images shown below</div>';

    // Render existing images
    const gallery = document.getElementById('imageGallery');
    gallery.innerHTML = '';

    if (res.images && res.images.length) {
        res.images.forEach(img => {
            const div = document.createElement('div');
            div.className = 'gallery-item' + (img.is_primary ? ' primary' : '');
            div.dataset.id = img.id;
            div.innerHTML = `
                <img src="${UPLOAD_URL}${img.image_path}" alt="item image">
                <div class="remove-img" onclick="removeImage(${img.id}, event)" title="Remove">✕</div>
                <div class="img-badge ${img.is_primary ? 'is-primary' : 'set-primary'}"
                     onclick="${img.is_primary ? '' : `setPrimaryImage(${img.id}, event)`}">
                    ${img.is_primary ? 'Primary' : 'Set Primary'}
                </div>
            `;
            gallery.appendChild(div);
        });
    }

    openModal('addItemModal');
}

// ── Delete Item ──────────────────────────────────
async function deleteItem(id, name) {
    confirmAction(`Delete item "${name}"? This cannot be undone.`, async () => {
        const res = await apiCall('handlers/items.php', { action: 'delete', id });
        if (res.success) {
            showToast('Item deleted', 'success');
            setTimeout(() => location.reload(), 600);
        } else {
            showToast(res.message || 'Error', 'error');
        }
    });
}

// ── Remove Single Image ──────────────────────────
async function removeImage(imageId, event) {
    event.stopPropagation();
    confirmAction('Remove this image?', async () => {
        const res = await apiCall('handlers/items.php', { action: 'remove_image', image_id: imageId });
        if (res.success) {
            showToast('Image removed', 'success');
            editItem(currentItemId); // Refresh gallery
        } else {
            showToast(res.message || 'Error', 'error');
        }
    });
}

// ── Set Primary Image ────────────────────────────
async function setPrimaryImage(imageId, event) {
    event.stopPropagation();
    const res = await apiCall('handlers/items.php', { action: 'set_primary', image_id: imageId });
    if (res.success) {
        showToast('Primary image updated', 'success');
        editItem(currentItemId);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

// ── Category: Open Add Form ──────────────────────
function openAddCategoryForm() {
    document.getElementById('categoryForm').reset();
    document.getElementById('editCategoryId').value          = '';
    document.getElementById('categoryFormTitle').textContent  = 'Add Category';
    openModal('categoryFormModal');
}

// ── Category: Edit ───────────────────────────────
async function editCategory(id) {
    const res = await apiCall('handlers/categories.php', { action: 'get', id });
    if (!res.success) { showToast('Error', 'error'); return; }
    const cat = res.data;
    const f   = document.getElementById('categoryForm');
    f.querySelector('[name=name]').value        = cat.name        || '';
    f.querySelector('[name=color]').value       = cat.color       || '#3B82F6';
    f.querySelector('[name=description]').value = cat.description || '';
    document.getElementById('editCategoryId').value          = id;
    document.getElementById('categoryFormTitle').textContent  = 'Edit Category';
    openModal('categoryFormModal');
}

// ── Category: Submit ─────────────────────────────
async function submitCategory() {
    const form   = document.getElementById('categoryForm');
    const fd     = new FormData(form);
    const editId = document.getElementById('editCategoryId').value;
    fd.set('action', editId ? 'edit' : 'add');

    const res = await apiCall('handlers/categories.php', fd);
    if (res.success) {
        showToast(editId ? 'Category updated!' : 'Category added!', 'success');
        closeModal('categoryFormModal');
        setTimeout(() => location.reload(), 600);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

// ── Category: Delete ─────────────────────────────
async function deleteCategory(id, name) {
    confirmAction(
        `Delete category "${name}"?\nItems in this category will lose their association.`,
        async () => {
            const res = await apiCall('handlers/categories.php', { action: 'delete', id });
            if (res.success) {
                showToast('Category deleted', 'success');
                setTimeout(() => location.reload(), 600);
            } else {
                showToast(res.message || 'Error', 'error');
            }
        }
    );
}
</script>