<?php
require_once '../includes/config.php';

function product_types_get_categories($conn) {
    $sql = "SELECT id, name FROM categories ORDER BY name ASC";
    return $conn->query($sql);
}

function product_types_get_one($conn, $id) {
    $id = (int)$id;
    $sql = "SELECT * FROM product_types WHERE id = $id LIMIT 1";
    $result = $conn->query($sql);
    return ($result && $result->num_rows > 0) ? $result->fetch_assoc() : null;
}

function product_types_name_exists($conn, $category_id, $name, $exclude_id = 0) {
    $category_id = (int)$category_id;
    $exclude_id = (int)$exclude_id;
    $name = trim($name);

    $stmt = $conn->prepare("SELECT id FROM product_types WHERE category_id = ? AND name = ? AND id != ? LIMIT 1");
    $stmt->bind_param("isi", $category_id, $name, $exclude_id);
    $stmt->execute();
    $result = $stmt->get_result();

    return ($result && $result->num_rows > 0);
}

function product_types_has_links($conn, $product_type_id) {
    $product_type_id = (int)$product_type_id;

    $check_table = $conn->query("SHOW TABLES LIKE 'product_type_links'");
    if (!$check_table || $check_table->num_rows === 0) {
        return false;
    }

    $stmt = $conn->prepare("SELECT id FROM product_type_links WHERE product_type_id = ? LIMIT 1");
    $stmt->bind_param("i", $product_type_id);
    $stmt->execute();
    $result = $stmt->get_result();

    return ($result && $result->num_rows > 0);
}