<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

header('Content-Type: application/json');
hw_require_auth(['admin']);

$input = json_decode(file_get_contents('php://input'), true);
$id = isset($input['id']) ? (int)$input['id'] : 0;
$action = $input['action'] ?? '';

if ($id <= 0 || !in_array($action, ['archive', 'restore'], true)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

try {
    $pdo = hw_db();
    $active = $action === 'archive' ? 0 : 1;
    $stmt = $pdo->prepare('UPDATE products SET active = ?, updated_at = NOW() WHERE id = ?');
    $stmt->execute([$active, $id]);

    if ($stmt->rowCount() === 0) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Product not found']);
        exit;
    }

    echo json_encode(['success' => true, 'message' => $action === 'archive' ? 'Product archived' : 'Product restored']);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
