<?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();

/**
 * ================= INPUT =================
 */
if (empty($_POST['product_id']) || empty($_FILES['image'])) {
    Response::error('product_id and image are required', 422);
}

$productId  = (int)$_POST['product_id'];
$variantId  = isset($_POST['variant_id']) ? (int)$_POST['variant_id'] : null;
$altText    = $_POST['alt_text'] ?? null;
$caption    = $_POST['caption'] ?? null;
$isFeatured = isset($_POST['is_featured']) && $_POST['is_featured'] == 1 ? 1 : 0;
$sortOrder  = isset($_POST['sort_order']) ? (int)$_POST['sort_order'] : 1;

/**
 * ================= VALIDATE PRODUCT =================
 */
$stmt = $db->prepare("SELECT id FROM retail_products WHERE id = :id");
$stmt->execute(['id' => $productId]);
if (!$stmt->fetch()) {
    Response::error('Invalid product', 404);
}

/**
 * ================= FILE VALIDATION =================
 */
$file = $_FILES['image'];
$allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];

if (!in_array($file['type'], $allowedTypes, true)) {
    Response::error('Only JPG, PNG, WEBP images allowed', 422);
}

if ($file['size'] > 5 * 1024 * 1024) {
    Response::error('Image size exceeds 5MB limit', 422);
}

/**
 * ================= UPLOAD =================
 */
$uploadDir = __DIR__ . '/../../uploads/retail-products/' . $productId . '/images/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$fileName = uniqid('prod_', true) . '.' . $ext;
$targetPath = $uploadDir . $fileName;

if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
    Response::error('Failed to upload image', 500);
}

$imagePath = '/uploads/retail-products/' . $productId . '/images/' . $fileName;

/**
 * ================= TRANSACTION =================
 */
$db->beginTransaction();

try {

    /**
     * Shift existing sort_order safely
     */
    $stmt = $db->prepare("
        UPDATE retail_product_images
        SET sort_order = sort_order + 1
        WHERE product_id = :pid
          AND sort_order >= :order
    ");
    $stmt->execute([
        'pid'   => $productId,
        'order' => $sortOrder
    ]);

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

    /**
     * Insert image
     */
    $stmt = $db->prepare("
        INSERT INTO retail_product_images (
            product_id,
            variant_id,
            image_path,
            alt_text,
            caption,
            is_featured,
            sort_order,
            status
        ) VALUES (
            :product_id,
            :variant_id,
            :image_path,
            :alt_text,
            :caption,
            :is_featured,
            :sort_order,
            'Active'
        )
    ");

    $stmt->execute([
        'product_id' => $productId,
        'variant_id' => $variantId,
        'image_path' => $imagePath,
        'alt_text'   => $altText,
        'caption'    => $caption,
        'is_featured'=> $isFeatured,
        'sort_order' => $sortOrder
    ]);

    $db->commit();

} catch (Throwable $e) {
    $db->rollBack();
    Response::error('Failed to upload image', 500);
}

Response::success('Product image uploaded successfully');
