<?php

/**
 * Migration 040 – Create activity logs table
 *
 * Stores admin action history for auditing.
 * Also adds the activity_log_enabled setting.
 */

use App\Database\Migration;

class CreateActivityLogs extends Migration
{
    public function up(): void
    {
        $this->db->query("
            CREATE TABLE IF NOT EXISTS iw_activity_logs (
                id              INT AUTO_INCREMENT PRIMARY KEY,
                user_id         INT          NOT NULL,
                action          VARCHAR(50)  NOT NULL COMMENT 'create, update, delete, publish, activate, login, etc.',
                resource_type   VARCHAR(50)  NOT NULL COMMENT 'page, blog_post, user, settings, plugin, theme, etc.',
                resource_id     INT          DEFAULT NULL,
                resource_name   VARCHAR(255) DEFAULT NULL,
                details         TEXT         DEFAULT NULL COMMENT 'Optional JSON with extra context',
                ip_address      VARCHAR(45)  DEFAULT NULL,
                created_at      DATETIME     DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_user_id (user_id),
                INDEX idx_resource_type (resource_type),
                INDEX idx_action (action),
                INDEX idx_created_at (created_at),
                CONSTRAINT fk_activity_user FOREIGN KEY (user_id) REFERENCES iw_users(id) ON DELETE CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        // Setting
        $existing = $this->db->fetch(
            "SELECT id FROM iw_settings WHERE setting_key = 'activity_log_enabled' LIMIT 1"
        );
        if (!$existing) {
            $this->db->insert('iw_settings', [
                'setting_key'   => 'activity_log_enabled',
                'setting_value' => '1',
                'setting_group' => 'general',
            ]);
        }
    }

    public function down(): void
    {
        $this->db->query("DROP TABLE IF EXISTS iw_activity_logs");
        $this->db->query("DELETE FROM iw_settings WHERE setting_key = 'activity_log_enabled'");
    }
}
