<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireAuth();
$db   = getDB();

$imageId = (int)post('image_id', 0);
if (!$imageId) apiError('Image ID required.', 422);

$row = $db->prepare("SELECT * FROM checklist_item_images WHERE id = ?");
$row->execute([$imageId]);
$img = $row->fetch();
if (!$img) apiError('Image not found.', 404);

// Delete the file
$filePath = __DIR__ . '/uploads/' . $img['filename'];
if (file_exists($filePath)) @unlink($filePath);

// Remove from multi-image table
$db->prepare("DELETE FROM checklist_item_images WHERE id = ?")->execute([$imageId]);

// Update legacy single-image column to the most recent remaining image (or null)
$latest = $db->prepare("
    SELECT filename FROM checklist_item_images
    WHERE instance_id = ? AND template_item_id = ?
    ORDER BY uploaded_at DESC LIMIT 1
");
$latest->execute([$img['instance_id'], $img['template_item_id']]);
$latestFile = $latest->fetchColumn();

$db->prepare("
    UPDATE checklist_instance_items SET image_filename = ?
    WHERE instance_id = ? AND template_item_id = ?
")->execute([$latestFile ?: null, $img['instance_id'], $img['template_item_id']]);

apiSuccess(['deleted' => $imageId], 'Image removed.');