<?php
$adminTitle = 'Product Management';
require_once __DIR__ . '/includes/header.php';

$action = $_GET['action'] ?? 'list';

// Handle DELETE
if ($action === 'delete' && isset($_GET['id'])) {
    Database::execute("UPDATE products SET is_active=0 WHERE id=?", [(int)$_GET['id']]);
    $_SESSION['flash']['success'] = 'Product deactivated.';
    header('Location: /admin/products.php');
    exit;
}

// Handle ADD/EDIT
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id       = (int)($_POST['id'] ?? 0);
    $catId    = (int)($_POST['category_id'] ?? 0);
    $name     = sanitize($_POST['name'] ?? '');
    $sku      = sanitize($_POST['sku'] ?? '');
    $shortDesc = sanitize($_POST['short_description'] ?? '');
    $desc     = sanitize($_POST['description'] ?? '');
    $specs    = trim($_POST['specifications'] ?? '');
    $standards = sanitize($_POST['standards'] ?? '');
    $brand    = sanitize($_POST['brand'] ?? '');
    $origin   = sanitize($_POST['origin'] ?? '');
    $stock    = in_array($_POST['stock_status'] ?? '', ['in_stock','out_of_stock','on_order']) ? $_POST['stock_status'] : 'in_stock';
    $featured = isset($_POST['is_featured']) ? 1 : 0;
    $slug     = slugify($name);

    // Handle image upload
    $image = $_POST['existing_image'] ?? null;
    $uploadError = '';
    if (!empty($_FILES['image']['tmp_name'])) {
        $res = handleFileUpload($_FILES['image'], 'products', ALLOWED_IMAGE_TYPES);
        if ($res['success']) {
            $image = $res['filename'];
        } else {
            $uploadError = ' Image upload failed: ' . $res['error'];
        }
    }

    // Handle datasheet upload
    $datasheet = $_POST['existing_datasheet'] ?? null;
    if (!empty($_FILES['datasheet']['tmp_name'])) {
        $ext = strtolower(pathinfo($_FILES['datasheet']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['pdf','doc','docx','xlsx','dwg','zip'])) {
            $dname = 'ds_' . time() . '_' . preg_replace('/[^a-z0-9\-_]/', '', strtolower(pathinfo($_FILES['datasheet']['name'], PATHINFO_FILENAME))) . '.' . $ext;
            if (move_uploaded_file($_FILES['datasheet']['tmp_name'], UPLOAD_PATH . '/' . $dname)) {
                $datasheet = $dname;
            }
        }
    }

    if ($id > 0) {
        // Make slug unique if changed
        $existing = Database::fetchOne("SELECT slug FROM products WHERE id=?", [$id]);
        if ($existing && $existing['slug'] !== $slug) {
            $check = Database::fetchOne("SELECT id FROM products WHERE slug=? AND id!=?", [$slug, $id]);
            if ($check) $slug .= '-' . $id;
        }
        Database::execute(
            "UPDATE products SET category_id=?,name=?,slug=?,sku=?,short_description=?,description=?,specifications=?,standards=?,brand=?,origin=?,stock_status=?,is_featured=?,image=?,datasheet=? WHERE id=?",
            [$catId,$name,$slug,$sku,$shortDesc,$desc,$specs,$standards,$brand,$origin,$stock,$featured,$image,$datasheet,$id]
        );
        $_SESSION['flash'][$uploadError ? 'warning' : 'success'] = 'Product updated.' . $uploadError;
    } else {
        // Ensure unique slug
        $check = Database::fetchOne("SELECT id FROM products WHERE slug=?", [$slug]);
        if ($check) $slug .= '-' . time();
        Database::insert(
            "INSERT INTO products (category_id,name,slug,sku,short_description,description,specifications,standards,brand,origin,stock_status,is_featured,image,datasheet,is_active) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,1)",
            [$catId,$name,$slug,$sku,$shortDesc,$desc,$specs,$standards,$brand,$origin,$stock,$featured,$image,$datasheet]
        );
        $_SESSION['flash'][$uploadError ? 'warning' : 'success'] = 'Product added successfully.' . $uploadError;
    }
    header('Location: /admin/products.php');
    exit;
}

$categories = Database::fetchAll("SELECT * FROM categories WHERE is_active=1 ORDER BY sort_order");

if ($action === 'add' || $action === 'edit') {
    $p = $action === 'edit' ? Database::fetchOne("SELECT * FROM products WHERE id=?", [(int)$_GET['id']]) : [];
?>
  <div class="flex items-center gap-4 mb-6">
    <a href="/admin/products.php" class="text-gray-400 hover:text-white">← Products</a>
    <h2 class="text-lg font-semibold"><?= $action === 'edit' ? 'Edit Product' : 'Add Product' ?></h2>
  </div>
  <div class="card-dark p-6 max-w-3xl">
    <form method="POST" enctype="multipart/form-data">
      <input type="hidden" name="id" value="<?= $p['id'] ?? '' ?>">
      <input type="hidden" name="existing_image" value="<?= e($p['image'] ?? '') ?>">
      <div class="grid grid-cols-2 gap-5 mb-4">
        <div class="col-span-2">
          <label class="text-xs text-gray-400 block mb-1.5">Product Name *</label>
          <input type="text" name="name" required value="<?= e($p['name'] ?? '') ?>">
        </div>
        <div>
          <label class="text-xs text-gray-400 block mb-1.5">Category</label>
          <select name="category_id">
            <option value="">Select Category</option>
            <?php foreach ($categories as $c): ?>
            <option value="<?= $c['id'] ?>" <?= ($p['category_id'] ?? '') == $c['id'] ? 'selected' : '' ?>><?= e($c['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div>
          <div class="flex items-center justify-between mb-1.5">
            <label class="text-xs text-gray-400 block">SKU</label>
            <button type="button" class="btn-ai-generate text-[10px] bg-navy-800 hover:bg-navy-700 text-orange-400 px-2 py-0.5 rounded border border-orange-500/20 shadow-sm transition-all" data-target="sku" data-type="sku">✨ AI</button>
          </div>
          <input type="text" name="sku" id="sku" value="<?= e($p['sku'] ?? '') ?>">
        </div>
        <div>
          <label class="text-xs text-gray-400 block mb-1.5">Standards (e.g. API 6A, ASME B16.5)</label>
          <input type="text" name="standards" value="<?= e($p['standards'] ?? '') ?>">
        </div>
        <div>
          <label class="text-xs text-gray-400 block mb-1.5">Stock Status</label>
          <select name="stock_status">
            <?php foreach (['in_stock'=>'In Stock','out_of_stock'=>'Out of Stock','on_order'=>'On Order'] as $v=>$l): ?>
            <option value="<?= $v ?>" <?= ($p['stock_status'] ?? 'in_stock') === $v ? 'selected' : '' ?>><?= $l ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div>
          <label class="text-xs text-gray-400 block mb-1.5">Brand</label>
          <input type="text" name="brand" value="<?= e($p['brand'] ?? '') ?>">
        </div>
        <div>
          <label class="text-xs text-gray-400 block mb-1.5">Origin</label>
          <input type="text" name="origin" value="<?= e($p['origin'] ?? '') ?>">
        </div>
        <div class="col-span-2">
          <div class="flex items-center justify-between mb-1.5">
            <label class="text-xs text-gray-400 block">Short Description</label>
            <button type="button" class="btn-ai-generate text-[10px] bg-navy-800 hover:bg-navy-700 text-orange-400 px-2 py-0.5 rounded border border-orange-500/20 shadow-sm transition-all" data-target="short_description" data-type="short">✨ AI Generate</button>
          </div>
          <textarea name="short_description" rows="2"><?= e($p['short_description'] ?? '') ?></textarea>
        </div>
        <div class="col-span-2">
          <div class="flex items-center justify-between mb-1.5">
            <label class="text-xs text-gray-400 block">Full Description</label>
            <button type="button" class="btn-ai-generate text-[10px] bg-navy-800 hover:bg-navy-700 text-orange-400 px-2 py-0.5 rounded border border-orange-500/20 shadow-sm transition-all" data-target="description" data-type="full">✨ AI Generate</button>
          </div>
          <textarea name="description" rows="4"><?= e($p['description'] ?? '') ?></textarea>
        </div>
        <div class="col-span-2 text-specs">
          <div class="flex items-center justify-between mb-1.5 ">
            <label class="text-xs text-gray-400 block ">Specifications (JSON or plain text)</label>
            <button type="button" class="btn-ai-generate text-[10px] bg-navy-800 hover:bg-navy-700 text-orange-400 px-2 py-0.5 rounded border border-orange-500/20 shadow-sm transition-all" data-target="specifications" data-type="specs">✨ AI Generate JSON</button>
          </div>
          <textarea name="specifications" rows="3" placeholder='{"Size": "2&quot; to 20&quot;", "Pressure": "3000 PSI", "Material": "ASTM A105"}'><?= e($p['specifications'] ?? '') ?></textarea>
        </div>
        <div class="col-span-2">
          <div class="flex items-center justify-between mb-1.5 ">
            <label class="text-xs text-gray-400 block">Product Image</label>
            <button type="button" onclick="openMediaLibrary('product_image')" class="text-[10px] bg-navy-800 hover:bg-navy-700 text-blue-400 px-2 py-0.5 rounded border border-blue-500/20 shadow-sm transition-all">🖼️ Select from Library</button>
          </div>
          <div class="flex items-center gap-4">
             <input type="file" name="image" id="image_input" accept="image/*" style="width:auto">
             <input type="hidden" name="existing_image" id="product_image_hidden" value="<?= e($p['image'] ?? '') ?>">
          </div>
          <div id="image_preview_container" class="mt-3 <?= empty($p['image']) ? 'hidden' : '' ?>">
            <img id="product_image_preview" src="<?= !empty($p['image']) ? '/uploads/'.e($p['image']) : '' ?>" class="w-32 h-32 object-cover rounded-xl border border-white/10">
          </div>
        </div>
        <div class="col-span-2">
          <label class="text-xs text-gray-400 block mb-1.5">Datasheet / Technical Document (PDF, DOC, DWG, ZIP)</label>
          <?php if (!empty($p['datasheet'])): ?>
          <div class="text-xs text-green-400 mb-1 flex items-center gap-2">
            📎 Current: <?= e(basename($p['datasheet'])) ?>
            <a href="/uploads/<?= e($p['datasheet']) ?>" target="_blank" class="text-blue-400 underline">view</a>
            <input type="hidden" name="existing_datasheet" value="<?= e($p['datasheet']) ?>">
          </div>
          <?php endif; ?>
          <input type="file" name="datasheet" accept=".pdf,.doc,.docx,.xlsx,.dwg,.zip" style="width:auto">
          <p class="text-xs text-gray-500 mt-1">Upload to replace existing datasheet. Displayed as a download link on the product page.</p>
        </div>
        <div class="flex items-center gap-2">
          <input type="checkbox" name="is_featured" id="featured" value="1" <?= ($p['is_featured'] ?? 0) ? 'checked' : '' ?> style="width:auto">
          <label for="featured" class="text-sm">Mark as Featured</label>
        </div>
      </div>
      <div class="flex gap-3 mt-8 pt-6 border-t border-navy-500/50">
        <button type="submit" class="btn-primary">Save Product</button>
        <?php if ($action === 'edit'): ?>
        <a href="cert-generate.php?id=<?= $p['id'] ?>" target="_blank" class="bg-green-600 hover:bg-green-700 text-white px-5 py-2.5 rounded-xl text-sm font-bold flex items-center gap-2 transition-all shadow-lg shadow-green-900/20">📜 Generate QC Certificate</a>
        <?php endif; ?>
        <a href="/admin/products.php" class="btn-outline">Cancel</a>
      </div>
    </form>
  </div>
<?php } else { // LIST
  $search = trim($_GET['q'] ?? '');
  $total = (int)(Database::fetchOne("SELECT COUNT(*) as c FROM products p WHERE is_active=1" . ($search ? " AND (p.name LIKE ? OR p.sku LIKE ?)" : ""), $search ? ["%$search%","%$search%"] : [])['c'] ?? 0);
  $pag = paginate($total, ADMIN_PER_PAGE, (int)($_GET['page'] ?? 1), '/admin/products.php?' . http_build_query(array_filter(['q'=>$search])));
  $products = Database::fetchAll(
    "SELECT p.*, c.name as cat FROM products p LEFT JOIN categories c ON p.category_id=c.id WHERE p.is_active=1" . ($search ? " AND (p.name LIKE ? OR p.sku LIKE ?)" : "") . " ORDER BY p.created_at DESC LIMIT ? OFFSET ?",
    array_merge($search ? ["%$search%","%$search%"] : [], [$pag['per_page'],$pag['offset']])
  );
?>
  <div class="flex items-center justify-between mb-6">
    <h2 class="text-lg font-semibold">Products (<?= $total ?>)</h2>
    <a href="?action=add" class="btn-primary text-sm">➕ Add Product</a>
  </div>
  <form method="GET" class="mb-4 flex gap-3">
    <input type="text" name="q" value="<?= e($search) ?>" placeholder="Search products..." class="max-w-xs">
    <button class="btn-outline text-sm">Search</button>
    <?php if ($search): ?><a href="/admin/products.php" class="btn-outline text-sm">Clear</a><?php endif; ?>
  </form>
  <div class="card-dark overflow-hidden">
    <table class="data-table">
      <thead><tr><th>Product</th><th>SKU</th><th>Category</th><th>Stock</th><th>Featured</th><th>Actions</th></tr></thead>
      <tbody>
      <?php foreach ($products as $p): ?>
      <tr>
        <td>
          <div class="flex items-center gap-3">
            <?php if ($p['image']): ?>
            <img src="/uploads/<?= e($p['image']) ?>" class="w-10 h-10 rounded object-cover"
                 onerror="this.onerror=null;this.style.display='none';this.nextElementSibling.style.display='flex'">
            <div class="w-10 h-10 rounded bg-navy-600 items-center justify-center text-lg" style="display:none">⚙️</div>
            <?php else: ?>
            <div class="w-10 h-10 rounded bg-navy-600 flex items-center justify-center text-lg">⚙️</div>
            <?php endif; ?>
            <div class="text-sm font-medium"><?= e($p['name']) ?></div>
          </div>
        </td>
        <td class="text-xs font-mono text-gray-400"><?= e($p['sku'] ?? '—') ?></td>
        <td class="text-xs"><?= e($p['cat'] ?? '—') ?></td>
        <td><?= statusBadge($p['stock_status']) ?></td>
        <td class="text-center"><?= $p['is_featured'] ? '⭐' : '—' ?></td>
        <td>
          <div class="flex gap-2">
            <a href="?action=edit&id=<?= $p['id'] ?>" class="text-xs text-orange-500 hover:underline">Edit</a>
            <a href="cert-generate.php?id=<?= $p['id'] ?>" target="_blank" class="text-xs text-green-400 hover:underline font-bold">📜 Cert</a>
            <a href="/product-detail.php?slug=<?= e($p['slug']) ?>" target="_blank" class="text-xs text-blue-400 hover:underline">View</a>
            <a href="?action=delete&id=<?= $p['id'] ?>" class="text-xs text-red-400 hover:underline" onclick="return confirm('Deactivate this product?')">Delete</a>
          </div>
        </td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?= paginationHtml($pag) ?>
<?php } ?>

<?php include __DIR__ . '/includes/footer.php'; ?>

<!-- Media Library Modal -->
<div id="media-library-modal" class="modal-overlay hidden" style="background: rgba(0,0,0,0.85); backdrop-filter: blur(8px); display: none;">
  <div class="modal-box max-w-5xl h-[85vh] flex flex-col p-0 overflow-hidden bg-navy-900 border border-white/5 shadow-2xl">
    <!-- Header -->
    <div class="flex items-center justify-between p-6 border-b border-white/5 bg-navy-800">
      <div>
        <h3 class="text-xl font-black text-white italic tracking-tighter uppercase">Media <span class="text-orange-500">Vault</span></h3>
        <p class="text-[10px] text-gray-500 font-bold uppercase tracking-widest mt-1">Select an existing asset from the technical library</p>
      </div>
      <button onclick="closeMediaLibrary()" class="text-gray-400 hover:text-white transition-colors">
        <span class="text-2xl">✕</span>
      </button>
    </div>
    
    <!-- Gallery -->
    <div id="library-gallery" class="flex-1 overflow-y-auto p-6 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
      <!-- Images injected here -->
      <div class="col-span-full py-20 text-center">
         <div class="animate-spin inline-block w-8 h-8 border-4 border-orange-500 border-t-transparent rounded-full mb-4"></div>
         <div class="text-xs text-gray-500 uppercase font-black">Syncing with server...</div>
      </div>
    </div>

    <!-- Footer -->
    <div class="p-6 border-t border-white/5 bg-navy-800 flex justify-between items-center text-xs">
        <span id="library-count" class="text-gray-500 font-bold uppercase tracking-widest">0 Assets Found</span>
        <button onclick="closeMediaLibrary()" class="btn-outline px-6 py-3 font-black uppercase text-[10px]">Abandon Selection</button>
    </div>
  </div>
</div>

<script>
let activeTargetId = null;

function openMediaLibrary(targetId) {
    activeTargetId = targetId;
    const modal = document.getElementById('media-library-modal');
    modal.style.display = 'flex';
    modal.classList.remove('hidden');
    
    fetchMedia();
}

function closeMediaLibrary() {
    const modal = document.getElementById('media-library-modal');
    modal.style.display = 'none';
    modal.classList.add('hidden');
}

async function fetchMedia() {
    const gallery = document.getElementById('library-gallery');
    try {
        const response = await fetch('/admin/api/media-list.php');
        const data = await response.json();
        
        if (data.success) {
            document.getElementById('library-count').innerText = data.files.length + ' Assets Found';
            if (data.files.length === 0) {
                gallery.innerHTML = '<div class="col-span-full py-20 text-center text-gray-500">No images found in library.</div>';
                return;
            }
            
            gallery.innerHTML = data.files.map(f => `
                <div onclick="selectImage('${f.name}')" class="group relative aspect-square rounded-xl overflow-hidden border border-white/5 hover:border-orange-500/50 cursor-pointer transition-all shadow-lg hover:scale-[1.02]">
                    <img src="${f.url}" class="w-full h-full object-cover">
                    <div class="absolute inset-0 bg-orange-600/20 opacity-0 group-hover:opacity-100 transition-opacity flex flex-col items-center justify-center p-2">
                        <span class="text-[9px] font-black text-white uppercase text-center truncate w-full">${f.name}</span>
                        <div class="mt-2 bg-white text-navy-900 px-2 py-1 rounded font-black text-[8px] uppercase">Select Asset</div>
                    </div>
                </div>
            `).join('');
        }
    } catch (e) {
        gallery.innerHTML = 'Error loading media library.';
    }
}

function selectImage(filename) {
    // Update hidden input
    const hiddenInput = document.getElementById('product_image_hidden');
    if(hiddenInput) hiddenInput.value = filename;
    
    // Update Preview
    const preview = document.getElementById('product_image_preview');
    const container = document.getElementById('image_preview_container');
    if(preview) {
        preview.src = '/uploads/' + filename;
        container.classList.remove('hidden');
    }
    
    // Clear file input
    document.getElementById('image_input').value = '';
    
    closeMediaLibrary();
}

// Ensure the standard file input also updates the preview
document.getElementById('image_input')?.addEventListener('change', function(e) {
    if (this.files && this.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const preview = document.getElementById('product_image_preview');
            const container = document.getElementById('image_preview_container');
            preview.src = e.target.result;
            container.classList.remove('hidden');
        }
        reader.readAsDataURL(this.files[0]);
    }
});
</script>

