<?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', 'rejection_reason']);

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

Validator::minLength($reason, 5, 'rejection_reason');

/**
 * 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 reject 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 === 'Rejected') {
    Response::error('Product is already rejected', 409);
}

/**
 * Reject product
 */
$stmt = $db->prepare("
    UPDATE retail_products
    SET
        approval_status = 'Rejected',
        status = 'InActive',
        rejection_reason = :reason,
        approved_by = :approved_by,
        updated_at = NOW()
    WHERE id = :id
");

$stmt->execute([
    'reason'      => $reason,
    'approved_by'=> $_SESSION['employee_id'],
    'id'          => $productId
]);

Response::success('Retail product rejected successfully');
