<?php

/**
 * @file
 * Install, update and uninstall functions for the Product Calculator Improved module.
 */

/**
 * Implements hook_schema().
 */
function product_calculator_improved_schema() {
  $schema = [];

  // ===== TABLE 1: INGREDIENT USAGE TRACKING =====
  $schema['product_calculator_ingredient_usage'] = [
    'description' => 'Stores ingredient usage for reporting',
    'fields' => [
      'id' => [
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Primary Key',
      ],
      'timestamp' => [
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'Time when calculation was performed',
      ],
      'user_id' => [
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'User ID who performed calculation',
      ],
      'ingredient_id' => [
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'Taxonomy term ID of the ingredient',
      ],
      'ingredient_name' => [
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Name of the ingredient',
      ],
      'quantity' => [
        'type' => 'float',
        'size' => 'normal',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'Amount of ingredient used',
      ],
      'unit_price' => [
        'type' => 'float',
        'size' => 'normal',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'Unit price of ingredient at time of calculation',
      ],
      'calculation_id' => [
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Unique ID for this calculation',
      ],
    ],
    'primary key' => ['id'],
    'indexes' => [
      'timestamp' => ['timestamp'],
      'ingredient_id' => ['ingredient_id'],
      'calculation_id' => ['calculation_id'],
      'user_id' => ['user_id'],  // ? ADDED: User tracking index
    ],
  ];

  // ===== TABLE 2: RECIPE STORAGE (SHARED ACCESS) =====
  $schema['recipe_storage'] = [
    'description' => 'Stores saved product recipes - SHARED across authenticated users',
    'fields' => [
      'recipe_id' => [
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Primary key',
      ],
      'recipe_name' => [
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'description' => 'User-defined recipe name (unique)',
      ],
      'ingredients_data' => [
        'type' => 'text',
        'size' => 'big',
        'not null' => TRUE,
        'description' => 'JSON-serialized array of ingredients',
      ],
      'created_by_user_id' => [
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'User ID who created the recipe (audit trail)',
      ],
      'created_timestamp' => [
        'type' => 'int',
        'not null' => TRUE,
        'description' => 'Recipe creation timestamp',
      ],
      'updated_by_user_id' => [
        'type' => 'int',
        'unsigned' => TRUE,
        'description' => 'User ID who last updated the recipe',
      ],
      'updated_timestamp' => [
        'type' => 'int',
        'unsigned' => TRUE,
        'description' => 'Last modification timestamp',
      ],
      'deleted_by_user_id' => [
        'type' => 'int',
        'unsigned' => TRUE,
        'description' => 'User ID who deleted the recipe (audit)',
      ],
      'deleted_timestamp' => [
        'type' => 'int',
        'unsigned' => TRUE,
        'description' => 'Recipe deletion timestamp',
      ],
      'restored_by_user_id' => [
        'type' => 'int',
        'unsigned' => TRUE,
        'description' => 'User ID who restored the recipe (admin only)',
      ],
      'restored_timestamp' => [
        'type' => 'int',
        'unsigned' => TRUE,
        'description' => 'Recipe restoration timestamp',
      ],
      'is_active' => [
        'type' => 'int',
        'size' => 'tiny',
        'default' => 1,
        'not null' => TRUE,
        'description' => 'Soft delete flag (1 = active, 0 = deleted)',
      ],
    ],
    'primary key' => ['recipe_id'],
    'unique keys' => [
      'recipe_name_unique' => ['recipe_name'],  // ? CHANGED: Unique by name alone (SHARED)
    ],
    'indexes' => [
      'is_active_idx' => ['is_active'],
      'created_timestamp_idx' => ['created_timestamp'],
      'created_by_user_id_idx' => ['created_by_user_id'],  // ? ADDED: Audit trail
      'updated_timestamp_idx' => ['updated_timestamp'],     // ? ADDED: Modification tracking
      'deleted_by_user_id_idx' => ['deleted_by_user_id'],   // ? ADDED: Deletion tracking
    ],
  ];

  return $schema;
}

/**
 * Implements hook_install().
 */
function product_calculator_improved_install() {
  \Drupal::messenger()->addStatus(
    t('Product Calculator Improved module installed successfully. Database tables created.')
  );
  
  // Log installation
  \Drupal::logger('product_calculator_improved')->notice('Module installed');
}

/**
 * Update 8001: Create product_calculator_ingredient_usage table.
 */
function product_calculator_improved_update_8001() {
  $schema = \Drupal::database()->schema();

  if (!$schema->tableExists('product_calculator_ingredient_usage')) {
    $definition = product_calculator_improved_schema();
    $schema->createTable(
      'product_calculator_ingredient_usage',
      $definition['product_calculator_ingredient_usage']
    );
    return t('? Created product_calculator_ingredient_usage table');
  }

  return t('? Table already exists - no changes made');
}

/**
 * Update 8002: Create recipe_storage table.
 */
function product_calculator_improved_update_8002() {
  $schema = \Drupal::database()->schema();

  if (!$schema->tableExists('recipe_storage')) {
    $definition = product_calculator_improved_schema();
    $schema->createTable('recipe_storage', $definition['recipe_storage']);
    return t('? Created recipe_storage table for shared recipe management');
  }

  return t('? Table already exists - no changes made');
}

/**
 * Update 8003: Migrate from user-specific to shared recipes.
 * 
 * This update removes user_id constraint, enabling shared access.
 */
function product_calculator_improved_update_8003() {
  $schema = \Drupal::database()->schema();
  $database = \Drupal::database();

  if (!$schema->tableExists('recipe_storage')) {
    return t('Recipe storage table does not exist - skipping migration');
  }

  try {
    // Check if old user_id field exists
    if ($schema->fieldExists('recipe_storage', 'user_id')) {
      // For shared recipes, user_id is no longer needed for filtering
      // Keep it for backward compatibility but don't use in queries
      \Drupal::logger('product_calculator_improved')->notice(
        'Migrating recipe_storage to shared access model'
      );

      // Drop old unique constraint if it exists
      if ($schema->indexExists('recipe_storage', 'recipe_name_user')) {
        $schema->dropIndex('recipe_storage', 'recipe_name_user');
      }

      // Add new unique constraint on recipe_name alone
      if (!$schema->indexExists('recipe_storage', 'recipe_name_unique')) {
        $schema->addUniqueKey('recipe_storage', 'recipe_name_unique', ['recipe_name']);
      }

      return t('? Migrated recipe_storage to shared access model');
    }

    return t('? Already on shared access model - no migration needed');
  } catch (\Exception $e) {
    \Drupal::logger('product_calculator_improved')->error(
      'Migration error: @message',
      ['@message' => $e->getMessage()]
    );
    return t('? Migration encountered error - see logs');
  }
}

/**
 * Update 8004: Add audit columns for recipe restoration.
 */
function product_calculator_improved_update_8004() {
  $schema = \Drupal::database()->schema();

  if (!$schema->tableExists('recipe_storage')) {
    return t('Recipe storage table does not exist');
  }

  $fields_to_add = [
    'restored_by_user_id' => [
      'type' => 'int',
      'unsigned' => TRUE,
      'description' => 'User ID who restored the recipe (admin only)',
    ],
    'restored_timestamp' => [
      'type' => 'int',
      'unsigned' => TRUE,
      'description' => 'Recipe restoration timestamp',
    ],
  ];

  $changes = 0;
  foreach ($fields_to_add as $field_name => $field_spec) {
    if (!$schema->fieldExists('recipe_storage', $field_name)) {
      $schema->addField('recipe_storage', $field_name, $field_spec);
      $changes++;
    }
  }

  if ($changes > 0) {
    return t('? Added @count audit fields for recipe restoration', ['@count' => $changes]);
  }

  return t('? Audit columns already exist - no changes made');
}

/**
 * Implements hook_uninstall().
 */
function product_calculator_improved_uninstall() {
  $schema = \Drupal::database()->schema();

  // Drop tables on uninstall
  if ($schema->tableExists('product_calculator_ingredient_usage')) {
    $schema->dropTable('product_calculator_ingredient_usage');
  }

  if ($schema->tableExists('recipe_storage')) {
    $schema->dropTable('recipe_storage');
  }

  \Drupal::logger('product_calculator_improved')->notice('Module uninstalled - tables removed');

  \Drupal::messenger()->addStatus(
    t('Product Calculator Improved module uninstalled. Database tables removed.')
  );
}