<?php

namespace App\Models;

use CodeIgniter\Model;

class ConsentHistoryModel extends Model
{
    protected $table = 'user_consent_history';
    protected $primaryKey = 'id';
    
    protected $useAutoIncrement = true;
    
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    
    protected $allowedFields = [
        'user_id',
        'device_uuid',
        'kvkk_consent',
        'gdpr_consent',
        'privacy_consent',
        'marketing_consent',
        'analytics_consent',
        'device_info_consent',
        'push_notification_consent',
        'membership_agreement',
        'electronic_communication',
        'explicit_consent', // Açık rıza metni için yeni alan
        'consent_version',
        'consent_text_versions',
        'previous_versions',
        'version_changes',
        'change_type',
        'platform',
        'device_model',
        'ip_address',
        'country_code',
        'region',
        'language',
        'timestamp',
        'is_authenticated',
        'user_agent',
        'legal_consents_group',
        'communication_consents_group',
        'experience_consents_group',
        'retention_expires_at',
        'legal_basis'
    ];
    
    protected $useTimestamps = false;
    
    protected $validationRules = [
        'device_uuid' => 'required|min_length[10]|max_length[255]',
        'kvkk_consent' => 'required|in_list[0,1]',
        'gdpr_consent' => 'required|in_list[0,1]',
        'privacy_consent' => 'required|in_list[0,1]',
        'marketing_consent' => 'required|in_list[0,1]',
        'explicit_consent' => 'required|in_list[0,1]', // Açık rıza zorunlu
        'is_authenticated' => 'permit_empty|in_list[0,1]',
        'change_type' => 'permit_empty|in_list[initial_consent,consent_change,version_update,single_consent_update,reconfirmation]'
    ];

    /**
     * Kurucu - tablo kontrolü yap ve gerekirse oluştur/güncelle
     */
    public function __construct()
    {
        parent::__construct();
        
        // Tablo ve sütunları kontrol et
        $this->_checkAndUpdateTable();
    }

    /**
     * Kullanıcının izin geçmişini getir - Versiyon bilgileri ile
     * 
     * @param string $userId User ID
     * @param int $limit Number of records to retrieve
     * @param int $offset Starting offset for records
     * @return array User's consent history with version information
     */
    public function getConsentHistoryWithVersions($userId, $limit = 50, $offset = 0)
    {
        return $this->where('user_id', $userId)
                    ->orderBy('timestamp', 'DESC')
                    ->limit($limit, $offset)
                    ->findAll();
    }

    /**
     * Cihazın izin geçmişini getir - Versiyon bilgileri ile
     * 
     * @param string $deviceUuid Device UUID
     * @param int $limit Number of records to retrieve
     * @param int $offset Starting offset for records
     * @return array Device's consent history with version information
     */
    public function getDeviceConsentHistoryWithVersions($deviceUuid, $limit = 50, $offset = 0)
    {
        return $this->where('device_uuid', $deviceUuid)
                    ->orderBy('timestamp', 'DESC')
                    ->limit($limit, $offset)
                    ->findAll();
    }

    /**
     * Belirli bir değişiklik tipine göre geçmişi getir
     * 
     * @param string $userId User ID
     * @param string $changeType Change type (initial_consent, consent_change, version_update, etc.)
     * @param int $limit Number of records to retrieve
     * @return array Filtered consent history
     */
    public function getConsentHistoryByChangeType($userId, $changeType, $limit = 20)
    {
        return $this->where('user_id', $userId)
                    ->where('change_type', $changeType)
                    ->orderBy('timestamp', 'DESC')
                    ->limit($limit)
                    ->findAll();
    }

    /**
     * Versiyon yükseltme geçmişini getir
     * 
     * @param string $userId User ID
     * @param int $limit Number of records to retrieve
     * @return array Version upgrade history
     */
    public function getVersionUpgradeHistory($userId, $limit = 20)
    {
        return $this->where('user_id', $userId)
                    ->where('change_type', 'version_update')
                    ->where('version_changes IS NOT NULL')
                    ->orderBy('timestamp', 'DESC')
                    ->limit($limit)
                    ->findAll();
    }

    /**
     * İzin türüne göre istatistikleri getir - Versiyon bilgileri dahil
     * 
     * @param string $consentType Consent type (kvkk_consent, gdpr_consent, etc.)
     * @return array Statistics for the consent type with version breakdown
     */
    public function getConsentStatsByTypeWithVersions($consentType)
    {
        // Validate consent type
        $validTypes = [
            'kvkk_consent', 'gdpr_consent', 'privacy_consent',
            'marketing_consent', 'analytics_consent', 'device_info_consent',
            'push_notification_consent', 'membership_agreement', 'electronic_communication',
            'explicit_consent'
        ];
        
        if (!in_array($consentType, $validTypes)) {
            return [];
        }
        
        // Get statistics by consent type
        $query = $this->select("$consentType, change_type, COUNT(*) as total")
                      ->groupBy([$consentType, 'change_type'])
                      ->findAll();
        
        // Format the result
        $result = [
            'accepted' => 0,
            'rejected' => 0,
            'by_change_type' => [],
            'version_related' => 0
        ];
        
        foreach ($query as $row) {
            if ($row[$consentType] === '1') {
                $result['accepted'] += (int)$row['total'];
            } else {
                $result['rejected'] += (int)$row['total'];
            }

            $changeType = $row['change_type'] ?? 'unknown';
            if (!isset($result['by_change_type'][$changeType])) {
                $result['by_change_type'][$changeType] = 0;
            }
            $result['by_change_type'][$changeType] += (int)$row['total'];

            if ($changeType === 'version_update') {
                $result['version_related'] += (int)$row['total'];
            }
        }
        
        return $result;
    }

    /**
     * İzin eğilimlerini getir - Versiyon bilgileri ile
     * 
     * @param string $consentType Consent type
     * @param string $interval Time interval (day, week, month)
     * @param int $limit Number of periods to retrieve
     * @return array Consent trends over time with version information
     */
    public function getConsentTrendsWithVersions($consentType, $interval = 'day', $limit = 30)
    {
        // Validate consent type
        $validTypes = [
            'kvkk_consent', 'gdpr_consent', 'privacy_consent',
            'marketing_consent', 'analytics_consent', 'device_info_consent',
            'push_notification_consent', 'membership_agreement', 'electronic_communication',
            'explicit_consent'
        ];
        
        if (!in_array($consentType, $validTypes)) {
            return [];
        }
        
        // Set date format based on interval
        $dateFormat = '%Y-%m-%d'; // Daily (default)
        
        if ($interval === 'week') {
            $dateFormat = '%Y-%u'; // Year-Week
        } else if ($interval === 'month') {
            $dateFormat = '%Y-%m'; // Year-Month
        }
        
        // Create SQL query with version information
        $db = \Config\Database::connect();
        $query = $db->query("
            SELECT 
                DATE_FORMAT(timestamp, '$dateFormat') as period,
                SUM(CASE WHEN $consentType = '1' THEN 1 ELSE 0 END) as accepted,
                SUM(CASE WHEN $consentType = '0' THEN 1 ELSE 0 END) as rejected,
                SUM(CASE WHEN change_type = 'version_update' THEN 1 ELSE 0 END) as version_updates,
                SUM(CASE WHEN change_type = 'initial_consent' THEN 1 ELSE 0 END) as initial_consents,
                SUM(CASE WHEN change_type = 'consent_change' THEN 1 ELSE 0 END) as consent_changes
            FROM 
                {$this->table}
            GROUP BY 
                period
            ORDER BY 
                period DESC
            LIMIT $limit
        ");
        
        return $query->getResultArray();
    }

    /**
     * Versiyon uyumluluk raporu getir
     * 
     * @param array $currentVersions Current system versions
     * @return array Version compliance report
     */
    public function getVersionComplianceReport($currentVersions = [])
    {
        $db = \Config\Database::connect();
        
        // En son kayıtları al
        $latestRecords = $db->query("
            SELECT 
                user_id,
                device_uuid,
                consent_text_versions,
                timestamp,
                change_type
            FROM {$this->table} h1
            WHERE timestamp = (
                SELECT MAX(timestamp) 
                FROM {$this->table} h2 
                WHERE h2.user_id = h1.user_id OR h2.device_uuid = h1.device_uuid
            )
            ORDER BY timestamp DESC
        ")->getResultArray();

        $complianceStats = [
            'total_records' => count($latestRecords),
            'compliant' => 0,
            'non_compliant' => 0,
            'unknown_version' => 0,
            'version_breakdown' => [],
            'outdated_users' => []
        ];

        foreach ($latestRecords as $record) {
            if (empty($record['consent_text_versions'])) {
                $complianceStats['unknown_version']++;
                continue;
            }

            try {
                $userVersions = json_decode($record['consent_text_versions'], true);
                $isCompliant = true;

                foreach ($currentVersions as $consentType => $currentVersion) {
                    $userVersion = $userVersions[$consentType . '_version'] ?? '0.0';
                    
                    if (version_compare($userVersion, $currentVersion, '<')) {
                        $isCompliant = false;
                        
                        if (!isset($complianceStats['version_breakdown'][$consentType])) {
                            $complianceStats['version_breakdown'][$consentType] = [
                                'compliant' => 0,
                                'non_compliant' => 0
                            ];
                        }
                        
                        $complianceStats['version_breakdown'][$consentType]['non_compliant']++;
                        
                        $complianceStats['outdated_users'][] = [
                            'user_id' => $record['user_id'],
                            'device_uuid' => $record['device_uuid'],
                            'consent_type' => $consentType,
                            'current_version' => $userVersion,
                            'required_version' => $currentVersion,
                            'last_update' => $record['timestamp']
                        ];
                    } else {
                        if (!isset($complianceStats['version_breakdown'][$consentType])) {
                            $complianceStats['version_breakdown'][$consentType] = [
                                'compliant' => 0,
                                'non_compliant' => 0
                            ];
                        }
                        
                        $complianceStats['version_breakdown'][$consentType]['compliant']++;
                    }
                }

                if ($isCompliant) {
                    $complianceStats['compliant']++;
                } else {
                    $complianceStats['non_compliant']++;
                }

            } catch (\Exception $e) {
                $complianceStats['unknown_version']++;
                log_message('error', 'Error parsing consent versions: ' . $e->getMessage());
            }
        }

        return $complianceStats;
    }

    /**
     * GDPR/KVKK uyumluluğu için veri saklama süresi kontrolü
     * 
     * @return array Records that are approaching or past retention period
     */
    public function getRetentionComplianceReport()
    {
        $db = \Config\Database::connect();
        
        // 7 yıl - 30 gün (uyarı için)
        $warningDate = date('Y-m-d H:i:s', strtotime('+30 days'));
        // 7 yıl (silme için)
        $deletionDate = date('Y-m-d H:i:s');
        
        $query = $db->query("
            SELECT 
                user_id,
                device_uuid,
                timestamp,
                retention_expires_at,
                legal_basis,
                DATEDIFF(retention_expires_at, NOW()) as days_remaining
            FROM {$this->table}
            WHERE retention_expires_at IS NOT NULL
            AND (
                retention_expires_at <= '$warningDate' 
                OR retention_expires_at <= '$deletionDate'
            )
            ORDER BY retention_expires_at ASC
        ");
        
        $results = $query->getResultArray();
        
        $report = [
            'total_records_checked' => count($results),
            'deletion_required' => [],
            'deletion_warning' => [],
            'summary' => [
                'immediate_deletion' => 0,
                'warning_period' => 0
            ]
        ];
        
        foreach ($results as $record) {
            if ($record['days_remaining'] <= 0) {
                $report['deletion_required'][] = $record;
                $report['summary']['immediate_deletion']++;
            } elseif ($record['days_remaining'] <= 30) {
                $report['deletion_warning'][] = $record;
                $report['summary']['warning_period']++;
            }
        }
        
        return $report;
    }

    /**
     * KVKK/GDPR için veri dışa aktarma
     * 
     * @param int $userId User ID
     * @return array Complete consent history for data export
     */
    public function exportUserConsentHistory($userId)
    {
        $userHistory = $this->where('user_id', $userId)
                           ->orderBy('timestamp', 'ASC')
                           ->findAll();
        
        $exportData = [
            'user_id' => $userId,
            'export_timestamp' => date('Y-m-d H:i:s'),
            'total_records' => count($userHistory),
            'data_retention_period' => '7 years (2555 days)',
            'legal_basis' => 'KVKK Article 7, GDPR Article 6',
            'consent_history' => []
        ];
        
        foreach ($userHistory as $record) {
            $exportRecord = [
                'timestamp' => $record['timestamp'],
                'consents' => [
                    'kvkk_consent' => $record['kvkk_consent'],
                    'gdpr_consent' => $record['gdpr_consent'],
                    'privacy_consent' => $record['privacy_consent'],
                    'marketing_consent' => $record['marketing_consent'],
                    'analytics_consent' => $record['analytics_consent'],
                    'device_info_consent' => $record['device_info_consent'],
                    'push_notification_consent' => $record['push_notification_consent'],
                    'membership_agreement' => $record['membership_agreement'],
                    'electronic_communication' => $record['electronic_communication'],
                    'explicit_consent' => $record['explicit_consent'] ?? '0',
                ],
                'version_information' => [
                    'consent_version' => $record['consent_version'],
                    'consent_text_versions' => !empty($record['consent_text_versions']) ? 
                        json_decode($record['consent_text_versions'], true) : null,
                    'previous_versions' => !empty($record['previous_versions']) ? 
                        json_decode($record['previous_versions'], true) : null,
                    'version_changes' => !empty($record['version_changes']) ? 
                        json_decode($record['version_changes'], true) : null,
                ],
                'change_information' => [
                    'change_type' => $record['change_type'],
                    'platform' => $record['platform'],
                    'ip_address' => $record['ip_address'],
                    'country_code' => $record['country_code'],
                    'language' => $record['language'],
                    'is_authenticated' => $record['is_authenticated'],
                ],
                'retention_information' => [
                    'retention_expires_at' => $record['retention_expires_at'],
                    'legal_basis' => $record['legal_basis'],
                ]
            ];
            
            $exportData['consent_history'][] = $exportRecord;
        }
        
        return $exportData;
    }

    /**
     * İzin geçmişi sayısını getir
     * 
     * @param int $userId User ID (optional)
     * @param string $deviceUuid Device UUID (optional)
     * @param string $changeType Change type filter (optional)
     * @return int Number of history records
     */
    public function getHistoryCount($userId = null, $deviceUuid = null, $changeType = null)
    {
        $query = $this->builder();
        
        if ($userId !== null) {
            $query->where('user_id', $userId);
        }
        
        if ($deviceUuid !== null) {
            $query->where('device_uuid', $deviceUuid);
        }
        
        if ($changeType !== null) {
            $query->where('change_type', $changeType);
        }
        
        return $query->countAllResults();
    }

    /**
     * En son izin geçmişi kaydını getir
     * 
     * @param int $userId User ID (optional)
     * @param string $deviceUuid Device UUID (optional)
     * @return array|null Latest consent history record or null if not found
     */
    public function getLatestHistory($userId = null, $deviceUuid = null)
    {
        $query = $this;
        
        if ($userId !== null) {
            $query = $query->where('user_id', $userId);
        }
        
        if ($deviceUuid !== null) {
            $query = $query->where('device_uuid', $deviceUuid);
        }
        
        return $query->orderBy('timestamp', 'DESC')
                    ->first();
    }

    /**
     * İzin geçmişini CSV formatında dışa aktar - Versiyon bilgileri ile
     * 
     * @param array $history Consent history array
     * @return string CSV-formatted data with version information
     */
    public function exportHistoryToCSVWithVersions($history)
    {
        // Define CSV headers with version information
        $headers = [
            'ID', 'User ID', 'Device UUID', 'KVKK Consent', 'GDPR Consent', 
            'Privacy Consent', 'Marketing Consent', 'Analytics Consent', 
            'Device Info Consent', 'Push Notification Consent',
            'Membership Agreement', 'Electronic Communication', 'Explicit Consent',
            'Consent Version', 'Change Type', 'Platform', 'IP Address', 
            'Country Code', 'Language', 'Timestamp', 'Is Authenticated',
            'Version Changes', 'Retention Expires', 'Legal Basis'
        ];
        
        // Create temporary file for CSV output
        $output = fopen('php://temp', 'r+');
        fputcsv($output, $headers);
        
        // Add data rows
        foreach ($history as $row) {
            $versionChanges = '';
            if (!empty($row['version_changes'])) {
                $changes = json_decode($row['version_changes'], true);
                if (is_array($changes)) {
                    $changesSummary = [];
                    foreach ($changes as $key => $change) {
                        $changesSummary[] = "$key: {$change['previous_version']} → {$change['new_version']}";
                    }
                    $versionChanges = implode('; ', $changesSummary);
                }
            }
            
            $csvRow = [
                $row['id'] ?? '',
                $row['user_id'] ?? '',
                $row['device_uuid'] ?? '',
                $row['kvkk_consent'] ?? '0',
                $row['gdpr_consent'] ?? '0',
                $row['privacy_consent'] ?? '0',
                $row['marketing_consent'] ?? '0',
                $row['analytics_consent'] ?? '0',
                $row['device_info_consent'] ?? '0',
                $row['push_notification_consent'] ?? '0',
                $row['membership_agreement'] ?? '0',
                $row['electronic_communication'] ?? '0',
                $row['explicit_consent'] ?? '0',
                $row['consent_version'] ?? '',
                $row['change_type'] ?? '',
                $row['platform'] ?? '',
                $row['ip_address'] ?? '',
                $row['country_code'] ?? '',
                $row['language'] ?? '',
                $row['timestamp'] ?? '',
                $row['is_authenticated'] ?? '0',
                $versionChanges,
                $row['retention_expires_at'] ?? '',
                $row['legal_basis'] ?? ''
            ];
            
            fputcsv($output, $csvRow);
        }
        
        // Get the CSV content
        rewind($output);
        $csv = stream_get_contents($output);
        fclose($output);
        
        return $csv;
    }

    /**
     * Belirli bir tarih aralığındaki değişiklikleri getir
     * 
     * @param string $startDate Start date (Y-m-d format)
     * @param string $endDate End date (Y-m-d format)
     * @param string $changeType Change type filter (optional)
     * @return array Changes within date range
     */
    public function getChangesByDateRange($startDate, $endDate, $changeType = null)
    {
        $query = $this->where('timestamp >=', $startDate . ' 00:00:00')
                      ->where('timestamp <=', $endDate . ' 23:59:59');
        
        if ($changeType !== null) {
            $query->where('change_type', $changeType);
        }
        
        return $query->orderBy('timestamp', 'DESC')->findAll();
    }

    /**
     * Versiyon yükseltmesi gerektiren kullanıcıları bul
     * 
     * @param array $currentVersions Current system versions
     * @return array Users requiring version updates
     */
    public function findUsersRequiringVersionUpdate($currentVersions)
    {
        $db = \Config\Database::connect();
        
        // Her kullanıcının en son kaydını al
        $latestRecords = $db->query("
            SELECT 
                user_id,
                device_uuid,
                consent_text_versions,
                timestamp
            FROM {$this->table} h1
            WHERE timestamp = (
                SELECT MAX(timestamp) 
                FROM {$this->table} h2 
                WHERE h2.user_id = h1.user_id 
                   OR (h1.user_id IS NULL AND h2.device_uuid = h1.device_uuid)
            )
            AND consent_text_versions IS NOT NULL
        ")->getResultArray();
        
        $usersRequiringUpdate = [];
        
        foreach ($latestRecords as $record) {
            try {
                $userVersions = json_decode($record['consent_text_versions'], true);
                $outdatedConsents = [];
                
                foreach ($currentVersions as $consentType => $currentVersion) {
                    $userVersion = $userVersions[$consentType . '_version'] ?? '0.0';
                    
                    if (version_compare($userVersion, $currentVersion, '<')) {
                        $outdatedConsents[] = [
                            'consent_type' => $consentType,
                            'current_version' => $userVersion,
                            'required_version' => $currentVersion
                        ];
                    }
                }
                
                if (!empty($outdatedConsents)) {
                    $usersRequiringUpdate[] = [
                        'user_id' => $record['user_id'],
                        'device_uuid' => $record['device_uuid'],
                        'last_update' => $record['timestamp'],
                        'outdated_consents' => $outdatedConsents,
                        'total_outdated' => count($outdatedConsents)
                    ];
                }
                
            } catch (\Exception $e) {
                log_message('error', 'Error checking user versions: ' . $e->getMessage());
            }
        }
        
        return $usersRequiringUpdate;
    }

    /**
     * Saklama süresi dolmuş kayıtları temizle - KVKK/GDPR uyumluluğu
     * 
     * @param bool $dryRun If true, only return records that would be deleted
     * @return array Result of cleanup operation
     */
    public function cleanupExpiredRecords($dryRun = true)
    {
        $db = \Config\Database::connect();
        
        // Saklama süresi dolmuş kayıtları bul
        $expiredRecords = $this->where('retention_expires_at <=', date('Y-m-d H:i:s'))
                              ->where('retention_expires_at IS NOT NULL')
                              ->findAll();
        
        $result = [
            'total_expired' => count($expiredRecords),
            'expired_records' => $expiredRecords,
            'deleted_count' => 0,
            'dry_run' => $dryRun
        ];
        
        if (!$dryRun && !empty($expiredRecords)) {
            // Anonimleştirme işlemi - Silmek yerine anonimleştir
            foreach ($expiredRecords as $record) {
                $anonymizedData = [
                    'user_id' => null,
                    'device_uuid' => 'ANONYMIZED_' . substr(md5($record['device_uuid']), 0, 8),
                    'ip_address' => null,
                    'user_agent' => 'ANONYMIZED',
                    'device_model' => null,
                    'legal_basis' => $record['legal_basis'] . ' - ANONYMIZED',
                    'anonymized_at' => date('Y-m-d H:i:s'),
                    'original_retention_date' => $record['retention_expires_at']
                ];
                
                $this->update($record['id'], $anonymizedData);
                $result['deleted_count']++;
            }
            
            log_message('info', "Anonymized {$result['deleted_count']} expired consent history records");
        }
        
        return $result;
    }

    /**
     * Tablo ve sütunları kontrol et, yoksa oluştur/güncelle
     */
    private function _checkAndUpdateTable()
    {
        $db = \Config\Database::connect();
        $forge = \Config\Database::forge();
        
        // Tablo var mı kontrol et
        $tables = $db->listTables();
        
        if (!in_array($this->table, $tables)) {
            // Tablo yok, oluştur
            $this->_createTable($forge);
        } else {
            // Tablo var, sütunları kontrol et ve eksikleri ekle
            $this->_updateTableColumns($db);
        }
    }

    /**
     * Tabloyu oluştur
     */
    private function _createTable($forge)
    {
        $forge->addField([
            'id' => [
                'type' => 'INT',
                'constraint' => 11,
                'unsigned' => true,
                'auto_increment' => true
            ],
            'user_id' => [
                'type' => 'INT',
                'constraint' => 11,
                'null' => true
            ],
            'device_uuid' => [
                'type' => 'VARCHAR',
                'constraint' => 255,
                'null' => false
            ],
            'kvkk_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'gdpr_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'privacy_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'marketing_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'analytics_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'device_info_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'push_notification_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'membership_agreement' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'electronic_communication' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
      'explicit_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'consent_version' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
                'null' => true
            ],
            'consent_text_versions' => [
                'type' => 'JSON',
                'null' => true
            ],
            'previous_versions' => [
                'type' => 'JSON',
                'null' => true
            ],
            'version_changes' => [
                'type' => 'JSON',
                'null' => true
            ],
            'change_type' => [
                'type' => 'VARCHAR',
                'constraint' => 50,
                'default' => 'consent_update'
            ],
            'platform' => [
                'type' => 'VARCHAR',
                'constraint' => 50,
                'null' => true
            ],
            'device_model' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true
            ],
            'ip_address' => [
                'type' => 'VARCHAR',
                'constraint' => 45,
                'null' => true
            ],
            'country_code' => [
                'type' => 'VARCHAR',
                'constraint' => 10,
                'null' => true
            ],
            'region' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true
            ],
            'language' => [
                'type' => 'VARCHAR',
                'constraint' => 10,
                'null' => true
            ],
            'timestamp' => [
                'type' => 'TIMESTAMP',
                'null' => false,
                'default' => 'CURRENT_TIMESTAMP'
            ],
            'is_authenticated' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'user_agent' => [
                'type' => 'TEXT',
                'null' => true
            ],
            'legal_consents_group' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'communication_consents_group' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'experience_consents_group' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'retention_expires_at' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ],
            'legal_basis' => [
                'type' => 'VARCHAR',
                'constraint' => 255,
                'null' => true,
                'default' => 'KVKK Article 7, GDPR Article 6'
            ],
            'anonymized_at' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ]
        ]);
        
        $forge->addKey('id', true);
        $forge->addKey('user_id');
        $forge->addKey('device_uuid');
        $forge->addKey('timestamp');
        $forge->addKey('change_type');
        $forge->addKey('retention_expires_at');
        
        $forge->createTable($this->table);
        
        log_message('info', "Consent history table '{$this->table}' created with versioning support");
    }

    /**
     * Tablo sütunlarını güncelle - MySQL 5.7 uyumlu versiyon
     */
    private function _updateTableColumns($db)
    {
        $existingColumns = $db->getFieldNames($this->table);
        
        // MySQL 5.7 uyumlu sütun ekleme işlemleri
        $columnUpdates = [
            'membership_agreement' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN membership_agreement CHAR(1) NOT NULL DEFAULT '0'"
            ],
            'electronic_communication' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN electronic_communication CHAR(1) NOT NULL DEFAULT '0'"
            ],
            'explicit_consent' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN explicit_consent CHAR(1) NOT NULL DEFAULT '0'"
            ],
            'previous_versions' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN previous_versions JSON NULL"
            ],
            'version_changes' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN version_changes JSON NULL"
            ],
            'change_type' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN change_type VARCHAR(50) NOT NULL DEFAULT 'consent_update'"
            ],
            'retention_expires_at' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN retention_expires_at TIMESTAMP NULL"
            ],
            'legal_basis' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN legal_basis VARCHAR(255) NULL DEFAULT 'KVKK Article 7, GDPR Article 6'"
            ],
            'anonymized_at' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN anonymized_at TIMESTAMP NULL"
            ],
            'experience_consents_group' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN experience_consents_group CHAR(1) NOT NULL DEFAULT '0'"
            ]
        ];
        
        // Eksik sütunları güvenli şekilde ekle
        foreach ($columnUpdates as $column => $config) {
            if (!in_array($column, $existingColumns)) {
                try {
                    $db->query($config['sql']);
                    log_message('info', "Added column '{$column}' to consent history table");
                } catch (\Exception $e) {
                    log_message('error', "Error adding column '{$column}': " . $e->getMessage());
                }
            }
        }

        // İndeksleri ekle/güncelle
        $this->_updateTableIndexes($db);
    }

    /**
     * Tablo indekslerini güncelle - MySQL 5.7 uyumlu
     */
    private function _updateTableIndexes($db)
    {
        try {
            // Mevcut indeksleri kontrol et
            $existingIndexes = $this->_getExistingIndexes($db);
            
            // MySQL 5.7 uyumlu indeks oluşturma - IF NOT EXISTS kullanmadan
            $indexesToCreate = [
                'idx_change_type' => [
                    'sql' => "CREATE INDEX idx_change_type ON {$this->table} (change_type)",
                    'columns' => ['change_type']
                ],
                'idx_retention_expires' => [
                    'sql' => "CREATE INDEX idx_retention_expires ON {$this->table} (retention_expires_at)",
                    'columns' => ['retention_expires_at']
                ],
                'idx_user_timestamp' => [
                    'sql' => "CREATE INDEX idx_user_timestamp ON {$this->table} (user_id, timestamp DESC)",
                    'columns' => ['user_id', 'timestamp']
                ],
                'idx_device_timestamp' => [
                    'sql' => "CREATE INDEX idx_device_timestamp ON {$this->table} (device_uuid, timestamp DESC)",
                    'columns' => ['device_uuid', 'timestamp']
                ],
                'idx_explicit_consent' => [
                    'sql' => "CREATE INDEX idx_explicit_consent ON {$this->table} (explicit_consent)",
                    'columns' => ['explicit_consent']
                ]
            ];
            
            // İndeksleri kontrol et ve ekle
            foreach ($indexesToCreate as $indexName => $indexConfig) {
                if (!in_array($indexName, $existingIndexes)) {
                    try {
                        $db->query($indexConfig['sql']);
                        log_message('info', "Created index '{$indexName}' on consent history table");
                    } catch (\Exception $e) {
                        // İndeks zaten varsa hata almayı önle
                        if (!strpos($e->getMessage(), 'Duplicate key name')) {
                            log_message('error', "Error creating index '{$indexName}': " . $e->getMessage());
                        }
                    }
                }
            }
            
            log_message('info', 'Consent history table indexes updated successfully');
        } catch (\Exception $e) {
            log_message('error', 'Error updating consent history indexes: ' . $e->getMessage());
        }
    }

    /**
     * Mevcut indeksleri getir - MySQL uyumlu
     */
    private function _getExistingIndexes($db)
    {
        try {
            $query = $db->query("SHOW INDEX FROM {$this->table}");
            $indexes = $query->getResultArray();
            
            $indexNames = [];
            foreach ($indexes as $index) {
                if ($index['Key_name'] !== 'PRIMARY') {
                    $indexNames[] = $index['Key_name'];
                }
            }
            
            return array_unique($indexNames);
        } catch (\Exception $e) {
            log_message('error', 'Error getting existing indexes: ' . $e->getMessage());
            return [];
        }
    }
}

?>