<?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();
$data = json_decode(file_get_contents('php://input'), true);

/**
 * ================= VALIDATION =================
 */
Validator::required($data, ['image_id', 'status']);

$imageId = (int)$data['image_id'];
$status  = $data['status'];

$allowed = ['Active', 'InActive'];

if (!in_array($status, $allowed, 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 update image status', 403);
}

/**
 * ================= CHECK IMAGE =================
 */
$stmt = $db->prepare("
    SELECT status
    FROM retail_product_images
    WHERE id = :id
");
$stmt->execute(['id' => $imageId]);
$currentStatus = $stmt->fetchColumn();

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

if ($currentStatus === $status) {
    Response::error('Image already in requested status', 409);
}

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

Response::success(
    $status === 'Active'
        ? 'Image activated successfully'
        : 'Image deactivated successfully'
);
