<?php
/**
 * POST /api/admin/products_toggle_featured.php
 * Admin-only. Body (JSON): { id, is_featured, featured_until? }
 * featured_until is optional (YYYY-MM-DD) - leave unset/null for an
 * indefinite feature, or set a date to auto-expire the highlight without
 * needing to remember to turn it off manually.
 */

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

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

$input = get_json_input();
$id = (int) ($input['id'] ?? 0);
if ($id <= 0) {
    send_error('A valid product id is required.', 422);
}

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

$isFeatured = !empty($input['is_featured']) ? 1 : 0;
$featuredUntil = null;
if ($isFeatured && !empty($input['featured_until'])) {
    $featuredUntil = $input['featured_until'];
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $featuredUntil)) {
        send_error('featured_until must be in YYYY-MM-DD format.', 422);
    }
}

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

send_json(true, $isFeatured ? 'Product featured.' : 'Product unfeatured.');
