START TRANSACTION;

-- 1. Pindahkan item yang sudah kadaluarsa ke tabel archives
INSERT INTO archives (
    item_id, name, category_id, photo_url, location,
    description, date_found, status, reporter_name,
    reporter_contact, archived_reason, archived_at
)
SELECT 
    id, name, category_id, photo_url, location,
    description, date_found, 'expired', reporter_name,
    reporter_contact, 'expired', NOW()
FROM items
WHERE expires_at < NOW() 
AND status = 'unclaimed'
AND deleted_at IS NULL
-- Pastikan item ini belum ada di archives untuk mencegah duplikat
AND NOT EXISTS (SELECT 1 FROM archives WHERE archives.item_id = items.id);

-- 2. Update status di tabel items menjadi 'expired'
UPDATE items
SET status = 'expired'
WHERE expires_at < NOW() 
AND status = 'unclaimed'
AND deleted_at IS NULL;

COMMIT;

-- 3. Cek Hasilnya
SELECT id, name, status, expires_at FROM items WHERE status = 'expired';
SELECT * FROM archives WHERE archived_reason = 'expired';