<?php
// ترقية: إنشاء جدول سجل النشاطات
if (!isset($conn) || $conn->connect_error) return;

$r = @$conn->query("SHOW TABLES LIKE 'activity_log'");
if (!$r || $r->num_rows == 0) {
    @$conn->query("CREATE TABLE activity_log (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NULL,
        username VARCHAR(50) NULL,
        action VARCHAR(50) NOT NULL,
        entity_type VARCHAR(100) NOT NULL,
        entity_id INT NULL,
        details TEXT NULL,
        ip_address VARCHAR(45) NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_created (created_at),
        INDEX idx_user (user_id),
        INDEX idx_entity (entity_type, entity_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    // إضافة FK فقط إذا وُجد جدول users ولم يُضَف القيد مسبقاً
    $chkUsers = @$conn->query("SHOW TABLES LIKE 'users'");
    $chkFk = @$conn->query("SELECT 1 FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA=DATABASE() AND TABLE_NAME='activity_log' AND CONSTRAINT_NAME='fk_activity_log_user'");
    if ($chkUsers && $chkUsers->num_rows > 0 && (!$chkFk || $chkFk->num_rows == 0)) {
        @$conn->query("ALTER TABLE activity_log ADD CONSTRAINT fk_activity_log_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL");
    }
}
