<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';
require_once __DIR__ . '/../../core/Validator.php';

$db = Database::getInstance();

/**
 * Read input
 */
$data = json_decode(file_get_contents('php://input'), true);

Validator::required($data, ['product_id', 'status']);

$productId = (int)$data['product_id'];
$status    = $data['status'];

$allowedStatuses = ['Active', 'Draft', 'InActive'];

if (!in_array($status, $allowedStatuses, true)) {
    Response::error('Invalid status value', 422);
}

/**
 * Role check
 */
$stmt = $db->prepare("
    SELECT r.name
    FROM employees e
    JOIN roles r ON r.id = e.role_id
    WHERE e.id = :id
");
$stmt->execute(['id' => $_SESSION['employee_id']]);
$role = $stmt->fetchColumn();

if (!in_array($role, ['Super Admin', 'Admin', 'SEO Manager'], true)) {
    Response::error('You are not authorized to change product status', 403);
}

/**
 * Check product exists
 */
$stmt = $db->prepare("
    SELECT id FROM retail_products WHERE id = :id
");
$stmt->execute(['id' => $productId]);

if (!$stmt->fetchColumn()) {
    Response::error('Retail product not found', 404);
}

/**
 * Update status
 */
$stmt = $db->prepare("
    UPDATE retail_products
    SET status = :status, updated_at = NOW()
    WHERE id = :id
");
$stmt->execute([
    'status' => $status,
    'id'     => $productId
]);

Response::success('Product status updated successfully');
