39728-vm/seed_items.php

62 lines
2.4 KiB
PHP

<?php
require 'db/config.php';
require 'includes/pexels.php';
$db = db();
// Define items to insert
$items = [
['sku' => '10000001', 'name' => 'Laptop Pro 15', 'price' => 1200.000, 'base_stock' => 10, 'category_id' => 1, 'supplier_id' => 1, 'query' => 'laptop'],
['sku' => '10000002', 'name' => 'Wireless Mouse', 'price' => 25.500, 'base_stock' => 50, 'category_id' => 2, 'supplier_id' => 2, 'query' => 'computer mouse'],
['sku' => '10000003', 'name' => 'Mechanical Keyboard', 'price' => 85.000, 'base_stock' => 30, 'category_id' => 2, 'supplier_id' => 1, 'query' => 'keyboard'],
['sku' => '10000004', 'name' => 'USB-C Hub', 'price' => 40.000, 'base_stock' => 100, 'category_id' => 2, 'supplier_id' => 2, 'query' => 'usb cable'],
['sku' => '10000005', 'name' => 'Cotton T-Shirt', 'price' => 15.000, 'base_stock' => 200, 'category_id' => 3, 'supplier_id' => 3, 'query' => 't-shirt'],
];
foreach ($items as $item) {
// Check if sku already exists
$stmt = $db->prepare("SELECT id FROM items WHERE sku = ?");
$stmt->execute([$item['sku']]);
if ($stmt->fetch()) {
echo "SKU {" . $item['sku'] . "} already exists.\n";
continue;
}
$imageUrl = null;
$localImagePath = null;
// Fetch image from pexels
$url = 'https://api.pexels.com/v1/search?query=' . urlencode($item['query']) . '&orientation=square&per_page=1&page=1';
$data = pexels_get($url);
if ($data && !empty($data['photos'])) {
$photo = $data['photos'][0];
$src = $photo['src']['medium'] ?? ($photo['src']['original'] ?? null);
if ($src) {
$dest = __DIR__ . '/assets/images/items/' . $photo['id'] . '.jpg';
if (download_to($src, $dest)) {
$localImagePath = 'assets/images/items/' . $photo['id'] . '.jpg';
}
}
}
if (!$localImagePath) {
$localImagePath = 'https://picsum.photos/400?random=' . rand(1, 1000); // fallback
}
$stmt = $db->prepare("INSERT INTO items (sku, name, price, base_stock, vat, category_id, supplier_id, image_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([
$item['sku'],
$item['name'],
$item['price'],
$item['base_stock'],
5.000, // default VAT
$item['category_id'],
$item['supplier_id'],
$localImagePath
]);
echo "Inserted {" . $item['name'] . "}\n";
}
echo "Done seeding items.\n";