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

$imageId   = (int)$data['image_id'];
$productId = (int)$data['product_id'];
$isFeatured= (int)($data['is_featured'] ?? 0);
$force     = isset($_GET['force']);

if ($isFeatured && !$force) {
    $stmt = $db->prepare("
        SELECT id FROM retail_product_images
        WHERE product_id = :pid AND is_featured = 1 AND id != :id
    ");
    $stmt->execute(['pid'=>$productId,'id'=>$imageId]);
    if ($stmt->fetch()) {
        Response::success('Featured image exists. Replace it?', ['confirm'=>true]);
    }
}

$db->beginTransaction();

if ($isFeatured) {
    $db->prepare("UPDATE retail_product_images SET is_featured = 0 WHERE product_id = :pid")
       ->execute(['pid'=>$productId]);
}

$db->prepare("
    UPDATE retail_product_images
    SET alt_text=:alt, caption=:cap, sort_order=:ord, is_featured=:feat
    WHERE id=:id
")->execute([
    'alt'=>$data['alt_text'],
    'cap'=>$data['caption'],
    'ord'=>$data['sort_order'],
    'feat'=>$isFeatured,
    'id'=>$imageId
]);

$db->commit();

Response::success('Image updated');
