<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user   = requireRole([1,2,5]);
$db     = getDB();
$itemId = (int)post('item_id',0);
if (!$itemId) apiError('Item ID required.',422);

if (empty($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) apiError('No file.',422);
$file  = $_FILES['image'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime  = finfo_file($finfo,$file['tmp_name']); finfo_close($finfo);
if (!in_array($mime,['image/jpeg','image/png','image/webp','image/gif'])) apiError('Images only.',422);
if ($file['size'] > 10*1024*1024) apiError('Max 10MB.',422);

$dir = __DIR__.'/../../uploads/stock/';
if (!is_dir($dir)) mkdir($dir,0755,true);
$ext = strtolower(pathinfo($file['name'],PATHINFO_EXTENSION))?:'jpg';
$fn  = 'item_'.$itemId.'_'.uniqid().'.'.$ext;
if (!move_uploaded_file($file['tmp_name'],$dir.$fn)) apiError('Upload failed.',500);

$path = 'uploads/stock/'.$fn;
// Delete old image
$old = $db->prepare("SELECT image_path FROM stock_items WHERE id=?"); $old->execute([$itemId]);
$oldRow = $old->fetch();
if ($oldRow && $oldRow['image_path'] && file_exists(__DIR__.'/../../'.$oldRow['image_path'])) {
    unlink(__DIR__.'/../../'.$oldRow['image_path']);
}
$db->prepare("UPDATE stock_items SET image_path=? WHERE id=?")->execute([$path,$itemId]);
apiSuccess(['image_path'=>$path],'Image saved.');
