<?php
declare(strict_types=1);

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

$db = Database::getInstance();

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

if (empty($data['product_id'])) {
    Response::error('product_id is required', 422);
}

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

/**
 * 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'], true)) {
    Response::error('You are not authorized to approve products', 403);
}

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

$currentStatus = $stmt->fetchColumn();

if (!$currentStatus) {
    Response::error('Retail product not found', 404);
}

if ($currentStatus === 'Approved') {
    Response::error('Product is already approved', 409);
}

/**
 * Approve product
 */
$stmt = $db->prepare("
    UPDATE retail_products
    SET
        approval_status = 'Approved',
        status = 'Active',
        rejection_reason = NULL,
        approved_by = :approved_by,
        updated_at = NOW()
    WHERE id = :id
");
$stmt->execute([
    'approved_by' => $_SESSION['employee_id'],
    'id'          => $productId
]);

Response::success('Retail product approved and published successfully');
