<?php

namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;

class ConsentController extends ResourceController
{
    use ResponseTrait;

    // Güncel versiyon tanımları - v1.0 sabit
    private const CURRENT_CONSENT_VERSIONS = [
        'kvkk_consent' => '1.0',
        'gdpr_consent' => '1.0',
        'privacy_consent' => '1.0',
        'marketing_consent' => '1.0',
        'analytics_consent' => '1.0',
        'push_consent' => '1.0',
        'device_info_consent' => '1.0',
        'membership_agreement' => '1.0',
        'electronic_communication' => '1.0',
        'explicit_consent' => '1.0',
    ];

    // İzin metin versiyonları - v1.0 sabit
    private const CONSENT_TEXT_VERSIONS = [
        'kvkk_text_version' => '1.0.0',
        'gdpr_text_version' => '1.0.0',
        'privacy_text_version' => '1.0.0',
        'marketing_text_version' => '1.0.0',
        'analytics_text_version' => '1.0.0',
        'push_text_version' => '1.0.0',
        'device_info_text_version' => '1.0.0',
        'membership_text_version' => '1.0.0',
        'electronic_communication_text_version' => '1.0.0',
        'explicit_consent_text_version' => '1.0.0',
    ];

    /**
     * Test metodu - ConsentController çalışıyor mu kontrol et
     */
    public function test()
    {
        return $this->respond([
            'code' => 'success',
            'message' => 'ConsentController çalışıyor!',
            'controller' => 'ConsentController',
            'timestamp' => date('Y-m-d H:i:s')
        ]);
    }

    /**
     * İzinleri getir - v1.0 versiyonlama destekli
     */
    public function getConsents()
    {
        $tokenModel = model('App\Models\TokenModel');
        $consentModel = model('App\Models\ConsentModel');

        // Token kontrolü
        if (empty($_GET['token'])) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Token missing'
            ]);
        }

        $token = $_GET['token'];
        $user_token = $tokenModel->where('token', $token)->findAll(1);

        if (count($user_token) == 0) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Valid Token missing'
            ]);
        }

        $user_id = $user_token[0]['user_id'];

        if (empty($_GET['user_id'])) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'User ID missing'
            ]);
        }

        if ($user_id != $_GET['user_id']) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Token missing permissions'
            ]);
        }

        // İzinleri getir - TEK KAYIT
        $latestConsent = $consentModel->getLatestConsent($user_id);

        if ($latestConsent) {
            // İzin versiyonlarını çöz
            $consentVersions = [];
            if (!empty($latestConsent['consent_text_versions'])) {
                $consentVersions = json_decode($latestConsent['consent_text_versions'], true) ?? [];
            }

            // Grup bilgilerini hesapla
            $groupData = $this->_calculateGroupData($latestConsent);
            
            return $this->respond([
                'code'                     => 'success',
                'kvkk_consent'            => $latestConsent['kvkk_consent'] ?? '0',
                'gdpr_consent'            => $latestConsent['gdpr_consent'] ?? '0',
                'privacy_consent'         => $latestConsent['privacy_consent'] ?? '0',
                'marketing_consent'       => $latestConsent['marketing_consent'] ?? '0',
                'analytics_consent'       => $latestConsent['analytics_consent'] ?? '0',
                'device_info_consent'     => $latestConsent['device_info_consent'] ?? '0',
                'push_consent'            => $latestConsent['push_consent'] ?? '0',
                'membership_agreement'    => $latestConsent['membership_agreement'] ?? '0',
                'electronic_communication' => $latestConsent['electronic_communication'] ?? '0',
                'explicit_consent'        => $latestConsent['explicit_consent'] ?? '0',
                'consent_version'         => $latestConsent['consent_version'] ?? '1.0.0',
                'consent_timestamp'       => $latestConsent['updated_at'] ?? $latestConsent['created_at'] ?? '',
                'consent_versions'        => $consentVersions,
                'current_versions'        => self::CURRENT_CONSENT_VERSIONS,
                'current_text_versions'   => self::CONSENT_TEXT_VERSIONS,
                'group_data'              => $groupData,
                'country_code'            => $latestConsent['country_code'] ?? '',
                'country'                 => $latestConsent['country'] ?? '',
                'region'                  => $latestConsent['region'] ?? '',
                'language'                => $latestConsent['language'] ?? '',
                'platform'                => $latestConsent['platform'] ?? '',
                'is_up_to_date'           => true, // v1.0 sabit olduğu için her zaman güncel
                'outdated_consents'       => [],
                'version_compliance'      => [
                    'is_up_to_date' => true,
                    'requires_reconfirmation' => false,
                    'outdated_consents' => []
                ],
            ]);
        } else {
            return $this->respond([
                'code'                => 'success',
                'kvkk_consent'        => '0',
                'gdpr_consent'        => '0',
                'privacy_consent'     => '0',
                'marketing_consent'   => '0',
                'analytics_consent'   => '0', 
                'device_info_consent' => '0',
                'push_consent'        => '0',
                'membership_agreement' => '0',
                'electronic_communication' => '0',
                'explicit_consent'    => '0',
                'consent_version'     => '1.0.0',
                'consent_timestamp'   => '',
                'current_versions'    => self::CURRENT_CONSENT_VERSIONS,
                'current_text_versions' => self::CONSENT_TEXT_VERSIONS,
                'group_data'          => [
                    'legal_consents_group'         => '0',
                    'communication_consents_group' => '0',
                    'experience_consents_group'    => '0'
                ],
                'is_up_to_date'       => false,
                'version_compliance'  => [
                    'is_up_to_date' => false,
                    'requires_reconfirmation' => true,
                    'outdated_consents' => array_keys(self::CURRENT_CONSENT_VERSIONS)
                ],
            ]);
        }
    }

  /**
 * İzinleri kaydet - TEK SATIR GÜNCELLEME + HISTORY KAYDI (DÜZELTİLMİŞ)
 */
public function saveConsents()
{
    $data_json = $this->request->getJSON();
    $consentModel = model('App\Models\ConsentModel');
    $deviceModel = model('App\Models\DeviceModel');
    
    // ZORUNLU: ConsentHistoryModel'i ekle
    $consentHistoryModel = model('App\Models\ConsentHistoryModel');

    // Zorunlu parametreleri kontrol et
    if (empty($data_json->device_uuid)) {
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Device UUID missing'
        ]);
    }

    // Kullanıcı kimlik bilgileri varsa doğrula
    $isAuthenticated = false;
    $userId = null;

    if (!empty($data_json->user_id) && !empty($data_json->token)) {
        $tokenModel = model('App\Models\TokenModel');
        $token = $data_json->token;
        $user_token = $tokenModel->where('token', $token)->findAll(1);

        if (count($user_token) > 0 && $user_token[0]['user_id'] == $data_json->user_id) {
            $isAuthenticated = true;
            $userId = $data_json->user_id;
        }
    }

    // İzin verilerini işle
    $consentData = [];
    $detailedConsents = [];
    $groupData = [];

    // Grup verilerini kontrol et
    if (isset($data_json->consent_group_data)) {
        $groupData = (array) $data_json->consent_group_data;
    }

    // Detaylı izinleri kontrol et
    if (isset($data_json->detailed_consents)) {
        $detailedConsents = (array) $data_json->detailed_consents;
    }

    // Zorunlu izinleri kontrol et - AÇIK RIZA DAHİL
    $requiredConsents = ['kvkk_consent', 'gdpr_consent', 'privacy_consent', 'membership_agreement', 'explicit_consent'];
    
    foreach ($requiredConsents as $required) {
        if (!isset($detailedConsents[$required])) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => ucfirst(str_replace('_', ' ', $required)) . ' field missing'
            ]);
        }
        $consentData[$required] = $detailedConsents[$required] === true || 
                                 $detailedConsents[$required] === '1' || 
                                 $detailedConsents[$required] === 1 ? '1' : '0';
    }

    // Açık rıza zorunlu kontrolü
    if ($consentData['explicit_consent'] !== '1') {
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Açık rıza metni kabul edilmesi zorunludur'
        ]);
    }
    
    // İsteğe bağlı izinleri işle
    $optionalConsents = [
        'marketing_consent', 
        'analytics_consent', 
        'push_consent', 
        'device_info_consent',
        'electronic_communication'
    ];
    
    foreach ($optionalConsents as $optional) {
        if (isset($detailedConsents[$optional])) {
            $consentData[$optional] = $detailedConsents[$optional] === true || 
                                     $detailedConsents[$optional] === '1' || 
                                     $detailedConsents[$optional] === 1 ? '1' : '0';
        } else {
            $consentData[$optional] = '0';
        }
    }

    // Grup verilerini kaydet
    foreach ($groupData as $groupKey => $groupValue) {
        $consentData[$groupKey] = $groupValue === true || 
                                 $groupValue === '1' || 
                                 $groupValue === 1 ? '1' : '0';
    }
    
    // VERSİYON BİLGİLERİNİ İŞLE - v1.0 sabit
    $fullVersionData = array_merge(
        self::CURRENT_CONSENT_VERSIONS,
        self::CONSENT_TEXT_VERSIONS,
        [
            'consent_system_version' => '1.0.0',
            'last_updated' => date('Y-m-d H:i:s'),
            'compliance_framework' => 'KVKK_GDPR_v1.0',
            'retention_period_days' => 2555, // 7 yıl
        ]
    );

    if (isset($data_json->versions) && is_object($data_json->versions)) {
        // Gelen versiyon bilgilerini mevcut verilerle birleştir
        $incomingVersions = (array) $data_json->versions;
        $fullVersionData = array_merge($fullVersionData, $incomingVersions);
    }

    $consentData['consent_text_versions'] = json_encode($fullVersionData);
    $consentData['consent_version'] = $fullVersionData['consent_system_version'] ?? '1.0.0';
    
    // Temel kayıt bilgileri
    $consentData['device_uuid'] = $data_json->device_uuid;
    $consentData['is_authenticated'] = $isAuthenticated ? '1' : '0';
    $consentData['ip_address'] = $this->request->getIPAddress();
    $consentData['user_agent'] = $this->request->getUserAgent()->getAgentString();
    
    // Kullanıcı bilgileri
    if ($isAuthenticated && $userId !== null) {
        $consentData['user_id'] = $userId;
    }
    
    if (!empty($data_json->user_email)) {
        $consentData['user_email'] = $data_json->user_email;
    }
    
    // Konum ve platform bilgileri
    $locationFields = ['country_code', 'country', 'region', 'language', 'platform'];
    foreach ($locationFields as $field) {
        if (isset($data_json->$field)) {
            $consentData[$field] = $data_json->$field;
        }
    }
    
    // Cihaz bilgilerini işle
    if (isset($data_json->device_info) && is_object($data_json->device_info)) {
        $consentData['device_info'] = json_encode($data_json->device_info);
        
        // Temel cihaz bilgilerini ayrıca ekle
        $deviceInfo = (array) $data_json->device_info;
        foreach ($locationFields as $field) {
            if (!isset($consentData[$field]) && isset($deviceInfo[$field])) {
                $consentData[$field] = $deviceInfo[$field];
            }
        }
    }

    try {
        log_message('info', '🟢 ConsentController saveConsents başladı - Device: ' . $data_json->device_uuid . ', User: ' . ($userId ?? 'guest'));
        
        // MEVCUT KAYDI BUL
        $existingRecord = null;
        
        if ($userId !== null) {
            // Kullanıcı giriş yapmışsa user_id ile ara
            $existingRecord = $consentModel->where('user_id', $userId)->first();
            log_message('info', '🔍 Kullanıcı için mevcut kayıt aranıyor - User ID: ' . $userId);
        } else {
            // Misafir kullanıcı için device_uuid ile ara
            $existingRecord = $consentModel->where('device_uuid', $data_json->device_uuid)
                                          ->where('user_id IS NULL')
                                          ->first();
            log_message('info', '🔍 Misafir için mevcut kayıt aranıyor - Device: ' . $data_json->device_uuid);
        }

        if ($existingRecord) {
            log_message('info', '📋 Mevcut kayıt bulundu - ID: ' . $existingRecord['id'] . ', şimdi değişiklik kontrolü yapılıyor');
            
            // DEĞİŞİKLİK KONTROLÜ - Sadece değişen izinler için history kaydı
            $hasChanges = false;
            $changedConsents = [];
            
            // Her izin türü için değişiklik kontrol et
            $allConsentTypes = [
                'kvkk_consent', 'gdpr_consent', 'privacy_consent', 'marketing_consent',
                'analytics_consent', 'push_consent', 'device_info_consent',
                'membership_agreement', 'electronic_communication', 'explicit_consent'
            ];
            
            foreach ($allConsentTypes as $consentType) {
                $oldValue = $existingRecord[$consentType] ?? '0';
                $newValue = $consentData[$consentType] ?? '0';
                
                if ($oldValue !== $newValue) {
                    $hasChanges = true;
                    $changedConsents[$consentType] = [
                        'old_value' => $oldValue,
                        'new_value' => $newValue
                    ];
                    log_message('info', "🔄 İzin değişikliği tespit edildi - $consentType: $oldValue → $newValue");
                }
            }
            
            if ($hasChanges) {
                log_message('info', '✅ Değişiklikler tespit edildi, history kaydı oluşturuluyor...');
                
                // ÖNEMLİ: ÖNCE history'e ESKİ VERİYİ kaydet
                $historyResult = $this->_saveConsentToHistory(
                    $existingRecord, 
                    $consentData, 
                    $isAuthenticated, 
                    $userId, 
                    'consent_change',
                    $changedConsents // Değişen izinler de gönderilsin
                );
                
                if (!$historyResult) {
                    log_message('error', '❌ History kaydı başarısız, güncelleme iptal ediliyor');
                    throw new \Exception('History kaydı oluşturulamadı');
                }
                
                // Sonra mevcut kaydı güncelle
                $consentData['updated_at'] = date('Y-m-d H:i:s');
                $result = $consentModel->update($existingRecord['id'], $consentData);
                $recordId = $existingRecord['id'];
                
                log_message('info', "📝 Consent record UPDATED - ID: $recordId, History Result: SUCCESS, Changes: " . count($changedConsents));
            } else {
                log_message('info', '⚠️ Değişiklik bulunamadı, history kaydı oluşturulmadı');
                
                // Değişiklik yoksa sadece son aktivite zamanını güncelle
                $consentData['updated_at'] = date('Y-m-d H:i:s');
                $result = $consentModel->update($existingRecord['id'], $consentData);
                $recordId = $existingRecord['id'];
            }
            
        } else {
            log_message('info', '➕ Yeni kayıt oluşturuluyor');
            
            // Yeni kayıt - önce kaydet, sonra history'e ekle
            $consentData['created_at'] = date('Y-m-d H:i:s');
            $consentData['updated_at'] = date('Y-m-d H:i:s');
            $consentData['consent_expires_at'] = date('Y-m-d H:i:s', strtotime('+2555 days'));
            $consentData['legal_basis'] = 'KVKK Article 7, GDPR Article 6';
            
            $recordId = $consentModel->insert($consentData);
            
            if ($recordId) {
                // Yeni kayıt için history'e ekle
                $historyResult = $this->_saveConsentToHistory(
                    $consentData, 
                    $consentData, 
                    $isAuthenticated, 
                    $userId, 
                    'initial_consent'
                );
                log_message('info', "✅ NEW consent record created - ID: $recordId, History Result: " . ($historyResult ? 'SUCCESS' : 'FAILED'));
            }
        }
        
        if ($recordId) {
            log_message('info', "💾 Consent record saved with ID: $recordId");
        }
        
        // Cihaz bilgilerini güncelle
        $this->_updateDeviceInfo($data_json, $deviceModel, $userId, $isAuthenticated);
        
        // Push izni değişikliği varsa topic aboneliklerini güncelle
        if (isset($consentData['push_consent'])) {
            $this->_updateTopicSubscriptions(
                $data_json->device_uuid, 
                $userId, 
                $consentData['push_consent'] === '1' ? 1 : 0,
                isset($consentData['marketing_consent']) ? ($consentData['marketing_consent'] === '1' ? 1 : 0) : null
            );
        }
        
        return $this->respond([
            'code'                => 'success',
            'message'             => 'Consents saved successfully',
            'user_id'             => $userId,
            'device_uuid'         => $data_json->device_uuid,
            'consent_timestamp'   => date('Y-m-d H:i:s'),
            'is_authenticated'    => $isAuthenticated,
            'group_summary'       => $this->_calculateGroupData($consentData),
            'has_changes'         => $hasChanges ?? true,
            'changed_consents'    => $changedConsents ?? [],
            'change_type'         => $existingRecord ? ($hasChanges ? 'consent_change' : 'no_change') : 'initial_consent',
            'version_compliance'  => [
                'is_up_to_date' => true,
                'requires_reconfirmation' => false,
                'outdated_consents' => []
            ],
            'consent_versions'    => $fullVersionData,
            'retention_info'      => [
                'retention_period_days' => 2555,
                'legal_basis' => 'KVKK Article 7, GDPR Article 6',
                'deletion_date' => date('Y-m-d', strtotime('+2555 days')),
            ],
        ]);
        
    } catch (\Exception $e) {
        log_message('error', '❌ ConsentController saveConsents hatası: ' . $e->getMessage());
        log_message('error', 'Stack trace: ' . $e->getTraceAsString());
        
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Error saving consents: ' . $e->getMessage()
        ]);
    }
}

/**
 * İzinleri ConsentHistory'e kaydet - GELİŞTİRİLMİŞ VERSİYON
 */
private function _saveConsentToHistory($existingRecord, $newData, $isAuthenticated, $userId, $changeType = 'consent_update', $changedConsents = [])
{
    try {
        log_message('info', '🟢 _saveConsentToHistory başladı - Change Type: ' . $changeType);
        
        $consentHistoryModel = model('App\Models\ConsentHistoryModel');
        
        if (!$consentHistoryModel) {
            log_message('error', '❌ ConsentHistoryModel yüklenemedi');
            return false;
        }
        
        log_message('info', '✅ ConsentHistoryModel başarıyla yüklendi');
        
        // ÖNEMLİ: Güncelleme sırasında ESKİ VERİYİ history'e kaydet
        $sourceData = ($changeType === 'consent_change' || $changeType === 'consent_update') ? $existingRecord : $newData;
        
        $historyData = [
            'user_id' => $userId,
            'device_uuid' => $sourceData['device_uuid'] ?? $newData['device_uuid'],
            'kvkk_consent' => $sourceData['kvkk_consent'] ?? '0',
            'gdpr_consent' => $sourceData['gdpr_consent'] ?? '0',
            'privacy_consent' => $sourceData['privacy_consent'] ?? '0',
            'marketing_consent' => $sourceData['marketing_consent'] ?? '0',
            'analytics_consent' => $sourceData['analytics_consent'] ?? '0',
            'device_info_consent' => $sourceData['device_info_consent'] ?? '0',
            'push_notification_consent' => $sourceData['push_consent'] ?? '0',
            'membership_agreement' => $sourceData['membership_agreement'] ?? '0',
            'electronic_communication' => $sourceData['electronic_communication'] ?? '0',
            'explicit_consent' => $sourceData['explicit_consent'] ?? '0',
            'consent_version' => $sourceData['consent_version'] ?? '1.0.0',
            'consent_text_versions' => $sourceData['consent_text_versions'] ?? null,
            'platform' => $sourceData['platform'] ?? $newData['platform'] ?? null,
            'ip_address' => $newData['ip_address'] ?? null,
            'country_code' => $sourceData['country_code'] ?? $newData['country_code'] ?? null,
            'region' => $sourceData['region'] ?? $newData['region'] ?? null,
            'language' => $sourceData['language'] ?? $newData['language'] ?? null,
            'timestamp' => date('Y-m-d H:i:s'),
            'is_authenticated' => $isAuthenticated ? '1' : '0',
            'user_agent' => $newData['user_agent'] ?? null,
            'legal_consents_group' => $sourceData['legal_consents_group'] ?? $newData['legal_consents_group'] ?? '0',
            'communication_consents_group' => $sourceData['communication_consents_group'] ?? $newData['communication_consents_group'] ?? '0',
            'experience_consents_group' => $sourceData['experience_consents_group'] ?? $newData['experience_consents_group'] ?? '0',
            'change_type' => $changeType,
            'retention_expires_at' => date('Y-m-d H:i:s', strtotime('+2555 days')),
            'legal_basis' => 'KVKK Article 7, GDPR Article 6',
        ];

        // Değişen izinlerin detaylarını JSON olarak kaydet
        if (!empty($changedConsents)) {
            $historyData['version_changes'] = json_encode([
                'changed_consents' => $changedConsents,
                'change_summary' => count($changedConsents) . ' consent(s) changed',
                'change_timestamp' => date('Y-m-d H:i:s')
            ]);
        }

        log_message('info', '📝 History data hazırlandı - Change Type: ' . $changeType);

        // Cihaz bilgilerinden model bilgisini çıkar
        if (!empty($newData['device_info'])) {
            try {
                $deviceInfo = json_decode($newData['device_info'], true);
                if (is_array($deviceInfo)) {
                    $historyData['device_model'] = $deviceInfo['device_model'] ?? $deviceInfo['model'] ?? null;
                    log_message('info', '📱 Device model eklendi: ' . ($historyData['device_model'] ?? 'null'));
                }
            } catch (\Exception $e) {
                log_message('error', 'Device info JSON decode error: ' . $e->getMessage());
            }
        } else if (!empty($sourceData['device_info'])) {
            try {
                $deviceInfo = json_decode($sourceData['device_info'], true);
                if (is_array($deviceInfo)) {
                    $historyData['device_model'] = $deviceInfo['device_model'] ?? $deviceInfo['model'] ?? null;
                }
            } catch (\Exception $e) {
                log_message('error', 'Device info JSON decode error: ' . $e->getMessage());
            }
        }

        log_message('info', '💾 History insert işlemi başlatılıyor...');
        
        $result = $consentHistoryModel->insert($historyData);
        
        if ($result) {
            log_message('info', "✅ CONSENT HISTORY BAŞARIYLA KAYDEDİLDİ - History ID: $result, Type: $changeType, User: " . ($userId ?? 'guest') . ', Changes: ' . count($changedConsents));
        } else {
            log_message('error', "❌ CONSENT HISTORY KAYDEDİLEMEDİ - Type: $changeType, User: " . ($userId ?? 'guest'));
            
            // Model hatalarını kontrol et
            $errors = $consentHistoryModel->errors();
            if (!empty($errors)) {
                log_message('error', 'ConsentHistoryModel validation errors: ' . json_encode($errors));
            }
        }
        
        return $result;
        
    } catch (\Exception $e) {
        log_message('error', "❌ _saveConsentToHistory EXCEPTION: " . $e->getMessage());
        log_message('error', "Stack trace: " . $e->getTraceAsString());
        return false;
    }
}

/**
 * Tek bir izni güncelle - GELİŞTİRİLMİŞ HISTORY DESTEĞİ İLE
 */
public function updateSingleConsent()
{
    $data_json = $this->request->getJSON();
    $consentModel = model('App\Models\ConsentModel');

    // Token kontrolü
    if (empty($data_json->token) || empty($data_json->user_id)) {
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Token or User ID missing'
        ]);
    }

    $tokenModel = model('App\Models\TokenModel');
    $token = $data_json->token;
    $user_token = $tokenModel->where('token', $token)->findAll(1);

    if (count($user_token) == 0 || $user_token[0]['user_id'] != $data_json->user_id) {
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Invalid token or user ID'
        ]);
    }
    $user_id = $data_json->user_id;

    if (empty($data_json->consent_type) || !isset($data_json->consent_value)) {
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Consent type and value required'
        ]);
    }

    $consentType = $data_json->consent_type;
    $consentValue = $data_json->consent_value === true || $data_json->consent_value === '1' ? '1' : '0';
    
    // Zorunlu izinlerin değiştirilmesini engelle
    $requiredConsents = ['kvkk_consent', 'gdpr_consent', 'privacy_consent', 'membership_agreement', 'explicit_consent'];
    if (in_array($consentType, $requiredConsents) && $consentValue === '0') {
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Required consents cannot be revoked. Use forget-me request instead.'
        ]);
    }

    // Geçerli izin tipleri kontrolü
    $validConsentTypes = [
        'marketing_consent', 'analytics_consent', 'push_consent', 
        'device_info_consent', 'electronic_communication'
    ];
    
    if (!in_array($consentType, $validConsentTypes)) {
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Invalid consent type'
        ]);
    }

    try {
        // En son izin kaydını getir
        $latestConsent = $consentModel->getLatestConsent($user_id);
        
        if (!$latestConsent) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'No existing consent found for user'
            ]);
        }
        
        // Değişiklik var mı kontrol et
        $oldValue = $latestConsent[$consentType] ?? '0';
        $newValue = $consentValue;
        
        if ($oldValue === $newValue) {
            log_message('info', "⚠️ Tek izin güncellemesi: Değişiklik yok - $consentType: $oldValue");
            return $this->respond([
                'code'     => 'success',
                'message'  => 'No change detected',
                'consent_type' => $consentType,
                'consent_value' => $consentValue,
                'change_detected' => false
            ]);
        }
        
        log_message('info', "🔄 Tek izin güncellemesi - $consentType: $oldValue → $newValue");
        
        // ÖNCE history'e eski veriyi kaydet
        $changedConsents = [
            $consentType => [
                'old_value' => $oldValue,
                'new_value' => $newValue
            ]
        ];
        
        $historyResult = $this->_saveConsentToHistory(
            $latestConsent, 
            $latestConsent, 
            true, 
            $user_id, 
            'single_consent_update',
            $changedConsents
        );
        
        if (!$historyResult) {
            log_message('error', '❌ Tek izin güncelleme history kaydı başarısız');
            throw new \Exception('History kaydı oluşturulamadı');
        }
        
        // Mevcut kaydı güncelle (tek satır)
        $latestConsent[$consentType] = $consentValue;
        $latestConsent['updated_at'] = date('Y-m-d H:i:s');
        $latestConsent['ip_address'] = $this->request->getIPAddress();
        $latestConsent['user_agent'] = $this->request->getUserAgent()->getAgentString();
        
        // Grup verilerini yeniden hesapla
        $groupData = $this->_calculateGroupData($latestConsent);
        foreach ($groupData as $key => $value) {
            $latestConsent[$key] = $value;
        }
        
        $updateResult = $consentModel->update($latestConsent['id'], $latestConsent);
        
        if (!$updateResult) {
            throw new \Exception('Consent güncelleme başarısız');
        }
        
        log_message('info', "✅ Tek izin başarıyla güncellendi - $consentType: $oldValue → $newValue, History ID: $historyResult");
        
        // Cihaz kayıtlarını güncelle
        $this->_updateDeviceConsentStatus($user_id, $consentType, $consentValue);
        
        return $this->respond([
            'code'            => 'success',
            'message'         => 'Consent updated successfully',
            'consent_type'    => $consentType,
            'consent_value'   => $consentValue,
            'old_value'       => $oldValue,
            'change_detected' => true,
            'history_id'      => $historyResult,
            'updated_at'      => $latestConsent['updated_at'],
            'version_info'    => [
                'consent_version' => '1.0',
                'text_version' => '1.0.0',
                'update_type' => 'single_consent_update'
            ]
        ]);
        
    } catch (\Exception $e) {
        log_message('error', 'Error updating single consent: ' . $e->getMessage());
        
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Error updating consent: ' . $e->getMessage()
        ]);
    }
}

  

    /**
     * İzin geçmişini getir
     */
    public function getConsentHistory()
    {
        $tokenModel = model('App\Models\TokenModel');
        $consentHistoryModel = model('App\Models\ConsentHistoryModel');

        // Token kontrolü
        if (empty($_GET['token'])) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Token missing'
            ]);
        }

        $token = $_GET['token'];
        $user_token = $tokenModel->where('token', $token)->findAll(1);

        if (count($user_token) == 0) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Valid Token missing'
            ]);
        }

        $user_id = $user_token[0]['user_id'];

        if (empty($_GET['user_id'])) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'User ID missing'
            ]);
        }

        if ($user_id != $_GET['user_id']) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Token missing permissions'
            ]);
        }

        // İzin geçmişini getir
        $history = $consentHistoryModel->getConsentHistoryWithVersions($user_id);
        
        // Hassas bilgileri filtrele
        $filteredHistory = [];
        foreach ($history as $item) {
            $filteredItem = [
                'id' => $item['id'],
                'consent_timestamp' => $item['timestamp'],
                'kvkk_consent' => $item['kvkk_consent'],
                'gdpr_consent' => $item['gdpr_consent'],
                'privacy_consent' => $item['privacy_consent'],
                'marketing_consent' => $item['marketing_consent'],
                'analytics_consent' => $item['analytics_consent'],
                'device_info_consent' => $item['device_info_consent'],
                'push_notification_consent' => $item['push_notification_consent'],
                'membership_agreement' => $item['membership_agreement'] ?? '0',
                'electronic_communication' => $item['electronic_communication'] ?? '0',
                'explicit_consent' => $item['explicit_consent'] ?? '0',
                'consent_version' => $item['consent_version'],
                'platform' => $item['platform'],
                'country_code' => $item['country_code'],
                'language' => $item['language'],
                'is_authenticated' => $item['is_authenticated'],
                'change_type' => $item['change_type'] ?? 'consent_update',
                'consent_versions' => !empty($item['consent_text_versions']) ? 
                    json_decode($item['consent_text_versions'], true) : null,
            ];

            // Cihaz bilgilerini sadeleştir
            if (!empty($item['device_model'])) {
                $filteredItem['device_model'] = $item['device_model'];
            }

            $filteredHistory[] = $filteredItem;
        }

        return $this->respond([
            'code'     => 'success',
            'message'  => 'Consent history retrieved successfully',
            'history'  => $filteredHistory,
            'total_records' => count($filteredHistory),
            'retention_info' => [
                'retention_period_days' => 2555,
                'oldest_record' => !empty($filteredHistory) ? 
                    end($filteredHistory)['consent_timestamp'] : null,
                'data_export_available' => true,
            ]
        ]);
    }


    /**
     * İzin versiyonlarını kontrol et
     */
    public function checkConsentVersions()
    {
        $data_json = $this->request->getJSON();
        
        if (empty($data_json->device_uuid) && (empty($data_json->user_id) || empty($data_json->token))) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Device UUID or user credentials required'
            ]);
        }

        try {
            $consentModel = model('App\Models\ConsentModel');
            $latestConsent = null;

            // Kullanıcı girişi varsa user_id ile ara
            if (!empty($data_json->user_id) && !empty($data_json->token)) {
                $tokenModel = model('App\Models\TokenModel');
                $user_token = $tokenModel->where('token', $data_json->token)->findAll(1);
                
                if (count($user_token) > 0 && $user_token[0]['user_id'] == $data_json->user_id) {
                    $latestConsent = $consentModel->getLatestConsent($data_json->user_id);
                }
            }

            // Device UUID ile ara
            if (!$latestConsent && !empty($data_json->device_uuid)) {
                $consents = $consentModel->getConsentsByDeviceUuid($data_json->device_uuid);
                $latestConsent = !empty($consents) ? $consents[0] : null;
            }

            if (!$latestConsent) {
                return $this->respond([
                    'code'               => 'success',
                    'consents_exist'     => false,
                    'up_to_date'         => false,
                    'current_versions'   => self::CURRENT_CONSENT_VERSIONS,
                    'current_text_versions' => self::CONSENT_TEXT_VERSIONS,
                    'user_versions'      => [],
                    'requires_consent'   => true,
                ]);
            }

            // Kullanıcının versiyon bilgilerini al
            $userVersions = [];
            if (!empty($latestConsent['consent_text_versions'])) {
                $userVersions = json_decode($latestConsent['consent_text_versions'], true) ?? [];
            }

            // v1.0 sabit olduğu için her zaman güncel
            return $this->respond([
                'code'               => 'success',
                'consents_exist'     => true,
                'up_to_date'         => true,
                'current_versions'   => self::CURRENT_CONSENT_VERSIONS,
                'current_text_versions' => self::CONSENT_TEXT_VERSIONS,
                'user_versions'      => $userVersions,
                'version_compliance' => [
                    'is_up_to_date' => true,
                    'requires_reconfirmation' => false,
                    'outdated_consents' => []
                ],
                'last_update'        => $latestConsent['updated_at'] ?? $latestConsent['created_at'] ?? '',
                'requires_reconfirmation' => false,
            ]);

        } catch (\Exception $e) {
            log_message('error', 'Error checking consent versions: ' . $e->getMessage());
            
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Error checking versions: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * Kullanıcı verilerini dışa aktar - GDPR Madde 15 uyumluluğu
     */
    public function exportUserData()
    {
        if (empty($_GET['user_id']) || empty($_GET['token'])) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'User ID and token required'
            ]);
        }

        // Token kontrolü
        $tokenModel = model('App\Models\TokenModel');
        $user_token = $tokenModel->where('token', $_GET['token'])->findAll(1);

        if (count($user_token) == 0 || $user_token[0]['user_id'] != $_GET['user_id']) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Invalid token or user ID'
            ]);
        }

        try {
            $consentModel = model('App\Models\ConsentModel');
            
            // Kullanıcının izin verilerini topla
            $exportData = $consentModel->exportUserConsentData($_GET['user_id']);
            
            return $this->respond([
                'code'     => 'success',
                'message'  => 'User data exported successfully',
                'data' => $exportData,
                'file_format' => 'json',
                'gdpr_compliance' => true,
                'kvkk_compliance' => true,
            ]);
            
        } catch (\Exception $e) {
            log_message('error', 'Error exporting user data: ' . $e->getMessage());
            
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Error exporting data: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * Cihaza bağlı izinleri kullanıcı hesabına aktar
     */
    public function transferConsents()
    {
        $data_json = $this->request->getJSON();
        
        // Gerekli parametreleri kontrol et
        if (empty($data_json->device_uuid) || empty($data_json->user_id) || empty($data_json->token)) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Missing required parameters'
            ]);
        }
        
        // Token kontrolü
        $tokenModel = model('App\Models\TokenModel');
        $token = $data_json->token;
        $user_token = $tokenModel->where('token', $token)->findAll(1);
        
        if (count($user_token) == 0 || $user_token[0]['user_id'] != $data_json->user_id) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Invalid token or user ID'
            ]);
        }
        
        try {
            $consentModel = model('App\Models\ConsentModel');
            $deviceUuid = $data_json->device_uuid;
            $userId = $data_json->user_id;
            
            // Cihaza bağlı misafir izinleri bul
            $deviceConsents = $consentModel->where('device_uuid', $deviceUuid)
                                          ->where('user_id IS NULL')
                                          ->first();
            
            if ($deviceConsents) {
                // Misafir izinlerini kullanıcı hesabına aktar
                $deviceConsents['user_id'] = $userId;
                unset($deviceConsents['id']); // ID'yi kaldır, yeni kayıt olsun
                
                $transferResult = $consentModel->insert($deviceConsents);
                
                if ($transferResult) {
                    // Eski misafir kaydını sil
                    $consentModel->where('device_uuid', $deviceUuid)
                                ->where('user_id IS NULL')
                                ->delete();
                    
                    return $this->respond([
                        'code'     => 'success',
                        'message'  => 'Consents transferred successfully'
                    ]);
                }
            }
            
            return $this->respond([
                'code'     => 'success',
                'message'  => 'No consents found to transfer'
            ]);
            
        } catch (\Exception $e) {
            log_message('error', 'Error transferring consents: ' . $e->getMessage());
            
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Error transferring consents: ' . $e->getMessage()
            ]);
        }
    }

    // ===== YARDIMCI METODLAR =====

    /**
     * Grup verilerini hesapla
     */
    private function _calculateGroupData($consentData)
    {
        $groupData = [];

        // Legal consents grubu - Hepsi 1 olmalı
        $legalConsents = ['kvkk_consent', 'gdpr_consent', 'privacy_consent', 'membership_agreement', 'explicit_consent'];
        $legalAll = true;
        foreach ($legalConsents as $consent) {
            if (($consentData[$consent] ?? '0') !== '1') {
                $legalAll = false;
                break;
            }
        }
        $groupData['legal_consents_group'] = $legalAll ? '1' : '0';

        // Communication consents grubu - En az biri 1 olmalı
        $commConsents = ['push_consent', 'marketing_consent', 'electronic_communication'];
        $commAny = false;
        foreach ($commConsents as $consent) {
            if (($consentData[$consent] ?? '0') === '1') {
                $commAny = true;
                break;
            }
        }
        $groupData['communication_consents_group'] = $commAny ? '1' : '0';

        // Experience consents grubu - En az biri 1 olmalı
        $expConsents = ['analytics_consent', 'device_info_consent'];
        $expAny = false;
        foreach ($expConsents as $consent) {
            if (($consentData[$consent] ?? '0') === '1') {
                $expAny = true;
                break;
            }
        }
        $groupData['experience_consents_group'] = $expAny ? '1' : '0';

        return $groupData;
    }

    /**
     * Cihaz bilgilerini güncelle
     */
    private function _updateDeviceInfo($data_json, $deviceModel, $userId, $isAuthenticated)
    {
        $deviceData = [
            'last_active' => date('Y-m-d H:i:s'),
            'is_active' => 1
        ];

        // Kullanıcı bilgilerini ekle
        if ($isAuthenticated && $userId !== null) {
            $deviceData['user_id'] = $userId;
        }

        if (!empty($data_json->user_email)) {
            $deviceData['email'] = $data_json->user_email;
        }

        // İzin durumlarını ekle
        if (isset($data_json->detailed_consents)) {
            $detailedConsents = (array) $data_json->detailed_consents;
            
            if (isset($detailedConsents['push_consent'])) {
                $deviceData['push_consent'] = $detailedConsents['push_consent'] === true || 
                                             $detailedConsents['push_consent'] === '1' || 
                                             $detailedConsents['push_consent'] === 1 ? 1 : 0;
            }
            
            if (isset($detailedConsents['marketing_consent'])) {
                $deviceData['marketing_consent'] = $detailedConsents['marketing_consent'] === true || 
                                                  $detailedConsents['marketing_consent'] === '1' || 
                                                  $detailedConsents['marketing_consent'] === 1 ? 1 : 0;
            }
        }

        // FCM token varsa güncelle
        if (!empty($data_json->fcmToken)) {
            $deviceModel->updateFcmToken($data_json->device_uuid, $data_json->fcmToken, $deviceData);
        } else {
            // Cihaz kaydını güncelle
            $device = $deviceModel->where('device_uuid', $data_json->device_uuid)->first();
            if ($device) {
                $deviceModel->update($device['id'], $deviceData);
            } else {
                // Yeni cihaz oluştur
                $deviceData['device_uuid'] = $data_json->device_uuid;
                $deviceData['first_seen'] = date('Y-m-d H:i:s');
                $deviceModel->insert($deviceData);
            }
        }
    }

    /**
     * Cihaz izin durumunu güncelle
     */
    private function _updateDeviceConsentStatus($userId, $consentType, $consentValue)
    {
        $deviceModel = model('App\Models\DeviceModel');
        
        if (in_array($consentType, ['push_consent', 'marketing_consent'])) {
            $devices = $deviceModel->where('user_id', $userId)->findAll();
            
            foreach ($devices as $device) {
                $updateData = [
                    $consentType => $consentValue === '1' ? 1 : 0,
                    'last_active' => date('Y-m-d H:i:s')
                ];
                
                $deviceModel->update($device['id'], $updateData);
                
                // Topic aboneliklerini güncelle
                if ($consentType === 'push_consent') {
                    $this->_updateTopicSubscriptions($device['device_uuid'], $userId, $consentValue === '1' ? 1 : 0, null);
                } elseif ($consentType === 'marketing_consent') {
                    $pushConsent = $device['push_consent'] ?? 0;
                    if ($pushConsent) {
                        $deviceModel->updateTopicSubscription($device['device_uuid'], 'marketing', $consentValue === '1');
                    }
                }
            }
        }
    }

    /**
     * Topic aboneliklerini güncelle
     */
    private function _updateTopicSubscriptions($deviceUuid, $userId, $pushConsent, $marketingConsent) 
    {
        $deviceModel = model('App\Models\DeviceModel');
        
        if ($pushConsent === 1) {
            $topicsToSubscribe = [];
            $topicsToUnsubscribe = [];
            
            // Kullanıcı bazlı abone olma/olmama
            if ($userId) {
                $topicsToSubscribe[] = 'user_' . $userId;
                $topicsToUnsubscribe[] = 'anonymous';
            } else {
                $topicsToSubscribe[] = 'anonymous';
            }
            
            // Pazarlama izni kontrolü
            if ($marketingConsent === 1) {
                $topicsToSubscribe[] = 'marketing';
            } elseif ($marketingConsent === 0) {
                $topicsToUnsubscribe[] = 'marketing';
            }
            
            // Abone ol
            foreach ($topicsToSubscribe as $topic) {
                $deviceModel->updateTopicSubscription($deviceUuid, $topic, true);
            }
            
            // Abonelikten çık
            foreach ($topicsToUnsubscribe as $topic) {
                $deviceModel->updateTopicSubscription($deviceUuid, $topic, false);
            }
        } elseif ($pushConsent === 0) {
            // Tüm konulardan çık
            $topicsToUnsubscribe = ['anonymous', 'marketing'];
            
            if ($userId) {
                $topicsToUnsubscribe[] = 'user_' . $userId;
            }
            
            foreach ($topicsToUnsubscribe as $topic) {
                $deviceModel->updateTopicSubscription($deviceUuid, $topic, false);
            }
        }
    }

    /**
     * FCM Push Token güncelleme
     */
    public function update_push_token()
    {
        $data_json = $this->request->getJSON();
        $deviceModel = model('App\Models\DeviceModel');

        // Zorunlu parametreleri kontrol et
        if (empty($data_json->device_uuid)) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Device UUID missing'
            ]);
        }

        if (empty($data_json->fcmToken) && empty($data_json->push_token)) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Push token missing'
            ]);
        }

        $fcmToken = !empty($data_json->fcmToken) ? $data_json->fcmToken : $data_json->push_token;
        $deviceUuid = $data_json->device_uuid;

        // İzin durumlarını kontrol et
        $pushConsent = isset($data_json->push_consent) ? 
                      ($data_json->push_consent === true || $data_json->push_consent === '1' ? 1 : 0) : null;
        
        $marketingConsent = isset($data_json->marketing_consent) ? 
                           ($data_json->marketing_consent === true || $data_json->marketing_consent === '1' ? 1 : 0) : null;

        // Ek verileri hazırla
        $additionalData = [
            'last_active' => date('Y-m-d H:i:s')
        ];

        // Kullanıcı ID'si varsa ekle
        if (!empty($data_json->user_id)) {
            $additionalData['user_id'] = $data_json->user_id;
        }

        // E-posta varsa ekle
        if (!empty($data_json->user_email)) {
            $additionalData['email'] = $data_json->user_email;
        }

        // İzin ayarları
        if ($pushConsent !== null) {
            $additionalData['push_consent'] = $pushConsent;
        }

        if ($marketingConsent !== null) {
            $additionalData['marketing_consent'] = $marketingConsent;
        }

        try {
            // FCM Token'ı güncelle
            $success = $deviceModel->updateFcmToken($deviceUuid, $fcmToken, $additionalData);

            if ($success) {
                return $this->respond([
                    'code'     => 'success',
                    'message'  => 'Push token updated successfully'
                ]);
            } else {
                return $this->respond([
                    'code'     => 'failed',
                    'message'  => 'Error updating push token'
                ]);
            }
        } catch (\Exception $e) {
            log_message('error', 'Error updating push token: ' . $e->getMessage());
            
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Error updating push token: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * Topic abonelikleri güncelleme
     */
    public function update_topic_subscriptions()
    {
        $data_json = $this->request->getJSON();
        $deviceModel = model('App\Models\DeviceModel');

        // Zorunlu parametreleri kontrol et
        if (empty($data_json->device_uuid)) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Device UUID missing'
            ]);
        }

        try {
            $topicsToAdd = !empty($data_json->subscribe_topics) ? $data_json->subscribe_topics : [];
            $topicsToRemove = !empty($data_json->unsubscribe_topics) ? $data_json->unsubscribe_topics : [];

            if (empty($topicsToAdd) && empty($topicsToRemove)) {
                return $this->respond([
                    'code'     => 'failed',
                    'message'  => 'No topics specified to add or remove'
                ]);
            }

            $success = true;

            // Eklenecek konular
            foreach ($topicsToAdd as $topic) {
                $result = $deviceModel->updateTopicSubscription($data_json->device_uuid, $topic, true);
                if (!$result) {
                    $success = false;
                }
            }

            // Çıkarılacak konular
            foreach ($topicsToRemove as $topic) {
                $result = $deviceModel->updateTopicSubscription($data_json->device_uuid, $topic, false);
                if (!$result) {
                    $success = false;
                }
            }

            if ($success) {
                return $this->respond([
                    'code'     => 'success',
                    'message'  => 'Topic subscriptions updated successfully'
                ]);
            } else {
                return $this->respond([
                    'code'     => 'failed',
                    'message'  => 'Error updating topic subscriptions'
                ]);
            }
        } catch (\Exception $e) {
            log_message('error', 'Error updating topic subscriptions: ' . $e->getMessage());
            
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Error updating topic subscriptions: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * Cihazı aktif/pasif yap
     */
    public function update_device_status()
    {
        $data_json = $this->request->getJSON();
        $deviceModel = model('App\Models\DeviceModel');

        // Zorunlu parametreleri kontrol et
        if (empty($data_json->device_uuid)) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Device UUID missing'
            ]);
        }

        if (!isset($data_json->is_active)) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Device status (is_active) missing'
            ]);
        }

        $isActive = $data_json->is_active === true || $data_json->is_active === '1' || $data_json->is_active === 1;

        try {
            // Cihaz durumunu güncelle
            $success = $deviceModel->setDeviceActive($data_json->device_uuid, $isActive);

            if ($success) {
                return $this->respond([
                    'code'     => 'success',
                    'message'  => 'Device status updated successfully'
                ]);
            } else {
                return $this->respond([
                    'code'     => 'failed',
                    'message'  => 'Error updating device status'
                ]);
            }
        } catch (\Exception $e) {
            log_message('error', 'Error updating device status: ' . $e->getMessage());
            
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Error updating device status: ' . $e->getMessage()
            ]);
        }
    }
}

?>
        