<?php
if (!function_exists('e')) {
    function e($value) {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

function product_slugify($text) {
    $text = trim((string)$text);
    $text = preg_replace('/[^\p{Arabic}\p{L}\p{N}\s\-_]+/u', '', $text);
    $text = preg_replace('/[\s\-_]+/u', '-', $text);
    $text = trim($text, '-');
    return mb_strtolower($text, 'UTF-8');
}

function product_redirect($url) {
    header("Location: {$url}");
    exit;
}

function product_upload_image($fieldName, $oldImage = null) {
    if (
        !isset($_FILES[$fieldName]) ||
        !isset($_FILES[$fieldName]['error']) ||
        $_FILES[$fieldName]['error'] !== UPLOAD_ERR_OK
    ) {
        return $oldImage;
    }

    $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    $original = $_FILES[$fieldName]['name'];
    $tmp      = $_FILES[$fieldName]['tmp_name'];
    $ext      = strtolower(pathinfo($original, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed, true)) {
        return $oldImage;
    }

    $uploadDirFs  = dirname(__DIR__) . '/uploads/products/';
    $uploadDirDb  = 'uploads/products/';

    if (!is_dir($uploadDirFs)) {
        @mkdir($uploadDirFs, 0775, true);
    }

    $newName = 'prd_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
    $target  = $uploadDirFs . $newName;

    if (move_uploaded_file($tmp, $target)) {
        if ($oldImage) {
            $oldFs = dirname(__DIR__) . '/' . ltrim($oldImage, '/');
            if (is_file($oldFs)) {
                @unlink($oldFs);
            }
        }
        return $uploadDirDb . $newName;
    }

    return $oldImage;
}

function get_categories(mysqli $conn) {
    $sql = "SELECT id, name
            FROM categories
            WHERE status = 1
            ORDER BY COALESCE(sort_order, 999999), id DESC";
    $res = $conn->query($sql);
    $items = [];
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $items[] = $row;
        }
    }
    return $items;
}

function get_brands(mysqli $conn) {
    $sql = "SELECT id, name
            FROM brands
            WHERE status = 1
            ORDER BY name ASC";
    $res = $conn->query($sql);
    $items = [];
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $items[] = $row;
        }
    }
    return $items;
}

function get_product(mysqli $conn, int $id) {
    $stmt = $conn->prepare("
        SELECT p.*,
               c.name AS category_name,
               b.name AS brand_name
        FROM products p
        LEFT JOIN categories c ON c.id = p.category_id
        LEFT JOIN brands b ON b.id = p.brand_id
        WHERE p.id = ?
        LIMIT 1
    ");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $res = $stmt->get_result();
    return $res ? $res->fetch_assoc() : null;
}

function get_product_variants(mysqli $conn, int $productId) {
    $stmt = $conn->prepare("
        SELECT *
        FROM product_variants
        WHERE product_id = ?
        ORDER BY COALESCE(sort_order, 999999), id ASC
    ");
    $stmt->bind_param('i', $productId);
    $stmt->execute();
    $res = $stmt->get_result();
    $rows = [];
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $rows[] = $row;
        }
    }
    return $rows;
}

function save_product_variants(mysqli $conn, int $productId, array $post, array $files) {
    $conn->query("DELETE FROM product_variants WHERE product_id = " . (int)$productId);

    $variantNames  = $post['variant_name'] ?? [];
    $variantSkus   = $post['variant_sku'] ?? [];
    $variantPrices = $post['variant_price'] ?? [];
    $variantCompare= $post['variant_compare_price'] ?? [];
    $variantStock  = $post['variant_stock_qty'] ?? [];
    $variantStatus = $post['variant_is_active'] ?? [];

    $stmt = $conn->prepare("
        INSERT INTO product_variants
        (product_id, variant_name, sku, price, compare_price, stock_qty, image, sort_order, is_active)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    for ($i = 0; $i < count($variantNames); $i++) {
        $name = trim((string)($variantNames[$i] ?? ''));
        if ($name === '') {
            continue;
        }

        $sku     = trim((string)($variantSkus[$i] ?? ''));
        $price   = (float)($variantPrices[$i] ?? 0);
        $compare = ($variantCompare[$i] ?? '') !== '' ? (float)$variantCompare[$i] : null;
        $stock   = (int)($variantStock[$i] ?? 0);
        $active  = isset($variantStatus[$i]) ? 1 : 0;
        $sort    = $i + 1;
        $image   = null;

        if (
            isset($files['variant_image']['name'][$i]) &&
            !empty($files['variant_image']['name'][$i]) &&
            ($files['variant_image']['error'][$i] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_OK
        ) {
            $single = [
                'name'     => $files['variant_image']['name'][$i],
                'type'     => $files['variant_image']['type'][$i] ?? '',
                'tmp_name' => $files['variant_image']['tmp_name'][$i],
                'error'    => $files['variant_image']['error'][$i],
                'size'     => $files['variant_image']['size'][$i] ?? 0,
            ];
            $_FILES['_tmp_variant_image'] = $single;
            $image = product_upload_image('_tmp_variant_image');
            unset($_FILES['_tmp_variant_image']);
        }

        $stmt->bind_param(
            'issddiisi',
            $productId,
            $name,
            $sku,
            $price,
            $compare,
            $stock,
            $image,
            $sort,
            $active
        );
        $stmt->execute();
    }
}

function product_flash($key, $message = null) {
    if (session_status() === PHP_SESSION_NONE) {
        @session_start();
    }

    if ($message !== null) {
        $_SESSION['product_flash'][$key] = $message;
        return;
    }

    $value = $_SESSION['product_flash'][$key] ?? null;
    unset($_SESSION['product_flash'][$key]);
    return $value;
}
