<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireAuth();
$db   = getDB();

$instanceId = (int)post('instance_id', 0);
$itemId     = (int)post('item_id', 0);

if (!$instanceId || !$itemId) apiError('Instance ID and item ID required.', 422);

if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    apiError('No image uploaded or upload error.', 422);
}

$allowed  = ['image/jpeg', 'image/png', 'image/webp'];
$mimeType = mime_content_type($_FILES['image']['tmp_name']);
if (!in_array($mimeType, $allowed)) apiError('Only JPG, PNG, WebP images allowed.', 422);

$maxSize = 8 * 1024 * 1024; // 8MB
if ($_FILES['image']['size'] > $maxSize) apiError('Image too large (max 8MB).', 422);

// Check instance exists
$stmt = $db->prepare("SELECT id FROM checklist_instances WHERE id = ?");
$stmt->execute([$instanceId]);
if (!$stmt->fetch()) apiError('Instance not found.', 404);

$uploadDir = __DIR__ . '/uploads/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

$ext      = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION) ?: 'jpg');
$filename = sprintf('ci_%d_item_%d_%s.%s', $instanceId, $itemId, uniqid(), $ext);
$dest     = $uploadDir . $filename;

if (!move_uploaded_file($_FILES['image']['tmp_name'], $dest)) {
    apiError('Failed to save image.', 500);
}

// Insert into multi-image table
$db->prepare("
    INSERT INTO checklist_item_images (instance_id, template_item_id, filename, uploaded_by)
    VALUES (?, ?, ?, ?)
")->execute([$instanceId, $itemId, $filename, $user['id']]);

$imageId = (int)$db->lastInsertId();

// Also keep legacy single-image column in sync (most recent image)
$ex = $db->prepare("SELECT id FROM checklist_instance_items WHERE instance_id = ? AND template_item_id = ?");
$ex->execute([$instanceId, $itemId]);
$existing = $ex->fetch();
if ($existing) {
    $db->prepare("UPDATE checklist_instance_items SET image_filename = ? WHERE id = ?")->execute([$filename, $existing['id']]);
} else {
    $db->prepare("
        INSERT INTO checklist_instance_items (instance_id, template_item_id, image_filename, is_checked, completed_at)
        VALUES (?, ?, ?, 0, NOW())
    ")->execute([$instanceId, $itemId, $filename]);
}

apiSuccess(['id' => $imageId, 'filename' => $filename], 'Image uploaded.');