<?php
/**
 * POST /api/admin/products_update_status.php
 * Body (JSON): { id, status } — status must be one of active|inactive|sold.
 * Unlike products/update.php, this does NOT check listing ownership — it's
 * for moderation (e.g. hiding a reported listing).
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/notifications.php';

only_post_allowed();
require_login();
require_role(['admin']);

$input = get_json_input();
$id = (int) ($input['id'] ?? 0);
$status = $input['status'] ?? '';

if ($id <= 0 || !in_array($status, ['active', 'inactive', 'sold'], true)) {
    send_error('A valid product id and status are required.', 422);
}

$pdo = Database::connect();
$stmt = $pdo->prepare('SELECT id, owner_id, name FROM products WHERE id = ?');
$stmt->execute([$id]);
$product = $stmt->fetch();
if (!$product) {
    send_error('Product not found.', 404);
}

$stmt = $pdo->prepare('UPDATE products SET status = ? WHERE id = ?');
$stmt->execute([$status, $id]);

if ($status === 'inactive') {
    create_notification(
        $pdo, (int) $product['owner_id'], 'listing_hidden',
        "Your listing \"{$product['name']}\" was hidden by an admin. Contact support if you have questions."
    );
}

send_json(true, 'Listing status updated.');
