<?php
/**
 * ============================================================================
 * ajax/update-product-status.php
 * Update product status
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once '../config/config.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    jsonError('Unauthorized', 401);
}

if (!isPost()) {
    jsonError('Invalid request method');
}

$productId = (int)($_POST['product_id'] ?? 0);
$newStatus = $_POST['status'] ?? '';
$userId = getUserId();

if ($productId <= 0) {
    jsonError('Invalid product ID');
}

$validStatuses = ['available', 'sold', 'reserved', 'expired'];
if (!in_array($newStatus, $validStatuses)) {
    jsonError('Invalid status');
}

$database = new Database();
$db = $database->getConnection();

// Check if user owns the product
$sql = "SELECT seller_id FROM products WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$productId]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$product) {
    jsonError('Product not found');
}

if ($product['seller_id'] != $userId && getUserType() !== 'admin') {
    jsonError('Unauthorized to update this product');
}

// Update status - ADD THE NAMESPACE
$productClass = new \App\Product($db);
$result = $productClass->updateStatus($productId, $newStatus);

if ($result['success']) {
    logActivity($userId, 'update_product_status', "Changed product ID {$productId} to {$newStatus}");
    jsonSuccess($result['message']);
} else {
    jsonError($result['message']);
}
?>