<?php

if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed');
}

function createAttribute(string $name): int {
    try {
        $stmt = pdo()->prepare("INSERT INTO attributes (name) VALUES (?) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)");
        $stmt->execute([$name]);
        return (int)pdo()->lastInsertId();
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error creating attribute '{$name}': " . $e->getMessage() . "\n", FILE_APPEND);
        return 0;
    }
}

function createAttributeValue(int $attribute_id, string $value): int {
    try {
        $stmt = pdo()->prepare("INSERT INTO attribute_values (attribute_id, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)");
        $stmt->execute([$attribute_id, $value]);
        return (int)pdo()->lastInsertId();
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error creating attribute value '{$value}' for attribute {$attribute_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return 0;
    }
}

function getAttributes(): array {
    try {
        return pdo()->query("SELECT * FROM attributes ORDER BY name ASC")->fetchAll();
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting attributes: " . $e->getMessage() . "\n", FILE_APPEND);
        return [];
    }
}

function getAttributeValues(int $attribute_id): array {
    try {
        $stmt = pdo()->prepare("SELECT * FROM attribute_values WHERE attribute_id = ? ORDER BY value ASC");
        $stmt->execute([$attribute_id]);
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting values for attribute {$attribute_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return [];
    }
}

function addAttributeToProduct(int $product_id, int $attribute_id): bool {
    try {
        $stmt = pdo()->prepare("INSERT IGNORE INTO product_attributes (product_id, attribute_id) VALUES (?, ?)");
        return $stmt->execute([$product_id, $attribute_id]);
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error adding attribute {$attribute_id} to product {$product_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return false;
    }
}

function getProductAttributes(int $product_id): array {
    try {
        $stmt = pdo()->prepare("SELECT a.* FROM attributes a 
                                   JOIN product_attributes pa ON a.id = pa.attribute_id 
                                   WHERE pa.product_id = ? 
                                   ORDER BY a.name ASC");
        $stmt->execute([$product_id]);
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting product attributes for {$product_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return [];
    }
}

function setSelectedValuesForProduct(int $product_id, array $attribute_value_ids): bool {
    $pdo = pdo();
    try {
        $pdo->beginTransaction();

        $stmt_delete = $pdo->prepare("DELETE FROM product_attribute_values WHERE product_id = ?");
        $stmt_delete->execute([$product_id]);

        if (!empty($attribute_value_ids)) {
            $sql_insert = "INSERT IGNORE INTO product_attribute_values (product_id, attribute_value_id) VALUES ";
            $params = [];
            $rows = [];
            foreach ($attribute_value_ids as $value_id) {
                $rows[] = "(?, ?)";
                $params[] = $product_id;
                $params[] = (int)$value_id;
            }
            $sql_insert .= implode(', ', $rows);
            $stmt_insert = $pdo->prepare($sql_insert);
            $stmt_insert->execute($params);
        }
        
        $pdo->commit();
        return true;
    } catch (PDOException $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error setting selected values for product {$product_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return false;
    }
}

function getSelectedValuesForProduct(int $product_id): array {
    try {
        $stmt = pdo()->prepare("SELECT av.*, a.name as attribute_name
                                  FROM attribute_values av
                                  JOIN product_attribute_values pav ON av.id = pav.attribute_value_id
                                  JOIN attributes a ON av.attribute_id = a.id
                                  WHERE pav.product_id = ?
                                  ORDER BY av.attribute_id, av.value ASC");
        $stmt->execute([$product_id]);
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting selected values for product {$product_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return [];
    }
}

function getSelectedValuesGroupedByAttribute(int $product_id): array {
    $values = getSelectedValuesForProduct($product_id);
    $grouped = [];
    foreach ($values as $value) {
        $attribute_id = $value['attribute_id'];
        $attribute_name = $value['attribute_name'];
        if (!isset($grouped[$attribute_id])) {
            $grouped[$attribute_id] = [
                'attribute_id' => $attribute_id,
                'attribute_name' => $attribute_name,
                'values' => []
            ];
        }
        $grouped[$attribute_id]['values'][] = $value;
    }
    return array_values($grouped);
}

function deleteAttribute(int $attribute_id): bool {
    try {
        $stmt = pdo()->prepare("DELETE FROM attributes WHERE id = ?");
        return $stmt->execute([$attribute_id]);
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error deleting attribute {$attribute_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return false;
    }
}

function deleteAttributeValue(int $value_id): bool {
    try {
        $stmt = pdo()->prepare("DELETE FROM attribute_values WHERE id = ?");
        return $stmt->execute([$value_id]);
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error deleting attribute value {$value_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return false;
    }
}

?>