<?php

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

class EnquireController extends ResourceController
{
    use ResponseTrait;
    
    /**
     * Get enquiries list based on user role with role-based data masking - OPTIMIZED
     */
    public function getEnquiries()
    {
        // Check authentication
        $tokenModel = model('App\Models\TokenModel');
        $userModel = model('App\Models\UserModel');
        
        // [Check Token]
        if (empty($_GET['token'])) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Token eksik'
            ]);
        }

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

        if (count($user_token) == 0) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Geçerli token eksik'
            ]);
        }
        
        $userId = $user_token[0]['user_id'];
        
        // Get user info to check role
        $user = $userModel->find($userId);
        
        if (!$user) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Kullanıcı bulunamadı'
            ]);
        }
        
        // Check if user is admin or agent
        $isAdmin = $user['type'] === 'ADMIN';
        $isAgent = $user['type'] === 'AGENT';
        
        if (!$isAdmin && !$isAgent) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Bu işlem için yetkiniz yok'
            ]);
        }
        
        // Pagination params
        $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
        $offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;
        $roleRestricted = isset($_GET['role_restricted']) ? $_GET['role_restricted'] === 'true' : true;
        
        // OPTIMIZE: Limit maximum records to prevent memory issues
        if ($limit > 50) {
            $limit = 50;
        }
        
        // Get enquiries
        $enquireModel = model('App\Models\EnquireModel');
        
        try {
            $enquiries = $enquireModel->getEnquiriesWithAppointmentsOptimized($userId, $isAdmin, $limit, $offset);
            
            // ROL BAZLI VERİ MASKELEME - OPTIMIZE: Process in chunks
            if ($isAgent && $roleRestricted) {
                foreach ($enquiries as &$enquiry) {
                    // Agent sadece ilan bilgisi ve randevu saatini görebilir
                    $enquiry['name_surname'] = '***';
                    $enquiry['phone'] = '***';
                    $enquiry['mail'] = '***';
                    $enquiry['message'] = 'Bu ilana talep var';
                    
                    // Admin notlarını kaldır - OPTIMIZE: Check if exists first
                    if (isset($enquiry['replies']) && is_array($enquiry['replies'])) {
                        $enquiry['replies'] = array_filter($enquiry['replies'], function($reply) {
                            return !isset($reply['is_admin_only']) || $reply['is_admin_only'] != 1;
                        });
                        $enquiry['replies'] = array_values($enquiry['replies']); // Re-index array
                    }
                }
            }
            
            // Get unread count - OPTIMIZE: Single query
            $unreadCount = $enquireModel->getUnreadCountOptimized($userId, $isAdmin);
            
            // Separate enquiries into categories - OPTIMIZE: Single loop
            $categorizedEnquiries = [
                'pending' => [],
                'answered' => [],
                'closed' => []
            ];
            
            foreach ($enquiries as $enquiry) {
                if ($enquiry['status'] === 'closed') {
                    $categorizedEnquiries['closed'][] = $enquiry;
                } elseif ($enquiry['status'] === 'answered') {
                    $categorizedEnquiries['answered'][] = $enquiry;
                } else {
                    $categorizedEnquiries['pending'][] = $enquiry;
                }
            }
            
            return $this->respond([
                'code'     => 'success',
                'message'  => 'Sorular başarıyla alındı',
                'enquiries' => $enquiries,
                'categorized_enquiries' => $categorizedEnquiries,
                'unread_count' => $unreadCount,
                'total' => count($enquiries),
                'is_admin' => $isAdmin,
                'is_agent' => $isAgent,
                'has_more' => count($enquiries) >= $limit // Indicate if more records available
            ]);
            
        } catch (\Exception $e) {
            log_message('error', 'getEnquiries error: ' . $e->getMessage());
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Veri yüklenirken hata oluştu: ' . $e->getMessage()
            ]);
        }
    }
    
/**
 * Get enquiry details with role-based data masking
 */
public function getEnquiryDetails()
{
    // Check authentication
    $tokenModel = model('App\Models\TokenModel');
    $userModel = model('App\Models\UserModel');
    
    // [Check Token]
    if (empty($_GET['token'])) {
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Token eksik'
        ]);
    }

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

    if (count($user_token) == 0) {
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Geçerli token eksik'
        ]);
    }
    
    $userId = $user_token[0]['user_id'];
    
    // Check enquiry ID
    if (empty($_GET['enquiry_id'])) {
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Soru ID eksik'
        ]);
    }
    
    $enquiryId = (int)$_GET['enquiry_id'];
    
    // Get user info to check role
    $user = $userModel->find($userId);
    
    if (!$user) {
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Kullanıcı bulunamadı'
        ]);
    }
    
    // Check user role
    $isAdmin = $user['type'] === 'ADMIN';
    $isAgent = $user['type'] === 'AGENT';
    $isUser = $user['type'] === 'USER';
    
    $enquireModel = model('App\Models\EnquireModel');
    
    // ============================================================================
    // ✅ USER ROLÜ İÇİN ÖZEL İŞLEM - SADECE KENDİ ENQUIRY'SİNE ERİŞEBİLİR
    // ============================================================================
  // USER ROLÜ İÇİN ÖZEL İŞLEM
if ($isUser) {
    // ✅ DÜZELTME: property.post_id ile JOIN ve language_id = 3
    $enquiry = $enquireModel->select('
            enquire.*, 
            property.image_filename as property_image_filename,
            property_lang.json_object as property_json
        ')
        ->join('property', 'property.id = enquire.property_id', 'left')
        ->join('property_lang', 'property_lang.property_id = enquire.property_id AND property_lang.language_id = 3', 'left')
        ->where('enquire.id', $enquiryId)
        ->groupStart()
            ->where('enquire.user_id', $userId)
            ->orWhere('enquire.phone', $user['phone'])
            ->orWhere('enquire.mail', $user['mail'])
        ->groupEnd()
        ->first();
    
    if (!$enquiry) {
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Bu sorguya erişim yetkiniz yok'
        ]);
    }
    
    // ✅ JSON'dan field_10 (başlık) ve field_64 (adres) al
    $propertyTitle = 'İlan';
    $propertyAddress = '';
    
    if (!empty($enquiry['property_json'])) {
        $propertyData = json_decode($enquiry['property_json'], true);
        if ($propertyData) {
            // field_10 = başlık
            $propertyTitle = $propertyData['field_10'] ?? 'İlan';
            // field_64 = adres
            $propertyAddress = $propertyData['field_64'] ?? '';
        }
    }
    
    $enquiry['property_title'] = $propertyTitle;
    $enquiry['property_address'] = $propertyAddress;
    $enquiry['property_location'] = $propertyAddress;
    
    // ✅ Property image - sadece filename
    $propertyImage = '';
    if (!empty($enquiry['property_image_filename'])) {
        $filename = trim($enquiry['property_image_filename']);
        // Eğer virgülle ayrılmış liste varsa ilk resmi al
        if (strpos($filename, ',') !== false) {
            $images = explode(',', $filename);
            $propertyImage = trim($images[0]);
        } else {
            $propertyImage = $filename;
        }
    }
    $enquiry['property_image'] = $propertyImage;
    
    // Get replies (exclude admin-only notes)
    $db = \Config\Database::connect();
    $replies = $db->table('enquire_replies')
        ->where('enquire_id', $enquiryId)
        ->where('(is_admin_only IS NULL OR is_admin_only = 0)')
        ->orderBy('created_at', 'ASC')
        ->get()
        ->getResultArray();
    
    $enquiry['replies'] = $replies;
    
    // Count unread messages
    $lastReadTime = $enquiry['last_user_read'] ?? '2000-01-01 00:00:00';
    $enquiry['unread_count'] = $db->table('enquire_replies')
        ->where('enquire_id', $enquiryId)
        ->where('(is_admin_only IS NULL OR is_admin_only = 0)')
        ->where('(is_system_message IS NULL OR is_system_message = 0)')
        ->where('user_id IS NOT NULL')
        ->where('created_at >', $lastReadTime)
        ->countAllResults();
    
    // Get agent info if available
    if (!empty($enquiry['agent_id'])) {
        $agent = $userModel->find($enquiry['agent_id']);
        if ($agent) {
            $enquiry['agent_name'] = $agent['name_surname'] ?? '';
            $enquiry['agent_email'] = $agent['mail'] ?? '';
            $enquiry['agent_phone'] = $agent['phone'] ?? '';
        }
    }
    
    // Update last_user_read
    $enquireModel->update($enquiryId, [
        'last_user_read' => date('Y-m-d H:i:s')
    ]);
    
    // Cleanup
    unset($enquiry['property_json']);
    unset($enquiry['property_image_filename']);
    
    return $this->respond([
        'code'     => 'success',
        'message'  => 'Soru detayları başarıyla alındı',
        'enquiry' => $enquiry,
        'is_admin' => false
    ]);
}
    
    // ============================================================================
    // ADMIN VE AGENT ROLÜ İÇİN MEVCUT İŞLEM
    // ============================================================================
    if (!$isAdmin && !$isAgent) {
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Bu işlem için yetkiniz yok'
        ]);
    }
    
    // Get enquiry details
    $enquiry = $enquireModel->getEnquiryWithRepliesOptimized($enquiryId, $userId, $isAdmin);
    
    if (!$enquiry) {
        return $this->respond([
            'code'     => 'failed',
            'message'  => 'Soru bulunamadı veya görüntüleme yetkiniz yok'
        ]);
    }
    
    // ROL BAZLI VERİ MASKELEME - AGENT İÇİN
    if ($isAgent) {
        $enquiry['name_surname'] = '***';
        $enquiry['phone'] = '***';
        $enquiry['mail'] = '***';
        $enquiry['message'] = 'Bu ilana talep var';
        
        // Admin notlarını kaldır
        if (isset($enquiry['replies']) && is_array($enquiry['replies'])) {
            $enquiry['replies'] = array_filter($enquiry['replies'], function($reply) {
                return !isset($reply['is_admin_only']) || $reply['is_admin_only'] != 1;
            });
            $enquiry['replies'] = array_values($enquiry['replies']);
        }
    }
    
    return $this->respond([
        'code'     => 'success',
        'message'  => 'Soru detayları başarıyla alındı',
        'enquiry' => $enquiry,
        'is_admin' => $isAdmin
    ]);
}
    
    /**
     * Add admin note - ONLY FOR ADMINS
     */
    public function addAdminNote()
    {
        // Check authentication
        $tokenModel = model('App\Models\TokenModel');
        $userModel = model('App\Models\UserModel');
        
        $data_json = $this->request->getJSON();
        
        // [Check Token]
        if (empty($data_json->token)) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Token eksik'
            ]);
        }

        $token = $data_json->token;
        $user_token = $tokenModel->where('token', $token)->findAll(1);

        if (count($user_token) == 0) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Geçerli token eksik'
            ]);
        }
        
        $userId = $user_token[0]['user_id'];
        
        // Check required parameters
        if (empty($data_json->enquiry_id) || empty($data_json->note)) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Soru ID ve not alanları zorunludur'
            ]);
        }
        
        $enquiryId = (int)$data_json->enquiry_id;
        $note = $data_json->note;
        $isAdminOnly = isset($data_json->is_admin_only) ? (bool)$data_json->is_admin_only : true;
        
        // Get user info to check role
        $user = $userModel->find($userId);
        
        if (!$user) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Kullanıcı bulunamadı'
            ]);
        }
        
        // Check if user is admin
        $isAdmin = $user['type'] === 'ADMIN';
        
        if (!$isAdmin) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Bu işlem için admin yetkisi gerekli'
            ]);
        }
        
        // Add the admin note
        $enquireModel = model('App\Models\EnquireModel');
        $replyId = $enquireModel->addAdminNote($enquiryId, $userId, $note, $isAdminOnly);
        
        if (!$replyId) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Not eklenirken bir hata oluştu'
            ]);
        }
        
        // Get updated enquiry details
        $enquiry = $enquireModel->getEnquiryWithRepliesOptimized($enquiryId, $userId, $isAdmin);
        
        return $this->respond([
            'code'     => 'success',
            'message'  => 'Admin notu başarıyla eklendi',
            'reply_id' => $replyId,
            'enquiry' => $enquiry
        ]);
    }

    /**
     * Get customer enquiries - ONLY FOR ADMINS
     */
    public function getCustomerEnquiries()
    {
        // Check authentication
        $tokenModel = model('App\Models\TokenModel');
        $userModel = model('App\Models\UserModel');
        
        // [Check Token]
        if (empty($_GET['token'])) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Token eksik'
            ]);
        }

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

        if (count($user_token) == 0) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Geçerli token eksik'
            ]);
        }
        
        $userId = $user_token[0]['user_id'];
        
        // Check customer phone
        if (empty($_GET['customer_phone'])) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Müşteri telefonu eksik'
            ]);
        }
        
        $customerPhone = $_GET['customer_phone'];
        
        // Get user info to check role
        $user = $userModel->find($userId);
        
        if (!$user || $user['type'] !== 'ADMIN') {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Bu işlem için admin yetkisi gerekli'
            ]);
        }
        
        // Get customer enquiries
        $enquireModel = model('App\Models\EnquireModel');
        $enquiries = $enquireModel->getCustomerEnquiries($customerPhone);
        
        return $this->respond([
            'code'     => 'success',
            'message'  => 'Müşteri soruları başarıyla alındı',
            'enquiries' => $enquiries,
            'total' => count($enquiries)
        ]);
    }

    /**
     * Get property enquiries - ONLY FOR ADMINS
     */
    public function getPropertyEnquiries()
    {
        // Check authentication
        $tokenModel = model('App\Models\TokenModel');
        $userModel = model('App\Models\UserModel');
        
        // [Check Token]
        if (empty($_GET['token'])) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Token eksik'
            ]);
        }

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

        if (count($user_token) == 0) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Geçerli token eksik'
            ]);
        }
        
        $userId = $user_token[0]['user_id'];
        
        // Check property ID
        if (empty($_GET['property_id'])) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'İlan ID eksik'
            ]);
        }
        
        $propertyId = (int)$_GET['property_id'];
        
        // Get user info to check role
        $user = $userModel->find($userId);
        
        if (!$user || $user['type'] !== 'ADMIN') {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Bu işlem için admin yetkisi gerekli'
            ]);
        }
        
        // Get property enquiries
        $enquireModel = model('App\Models\EnquireModel');
        $enquiries = $enquireModel->getPropertyEnquiries($propertyId);
        
        return $this->respond([
            'code'     => 'success',
            'message'  => 'İlan soruları başarıyla alındı',
            'enquiries' => $enquiries,
            'total' => count($enquiries)
        ]);
    }

    /**
     * Get agent notification info - ONLY FOR AGENTS
     */
    public function getAgentNotificationInfo()
    {
        // Check authentication
        $tokenModel = model('App\Models\TokenModel');
        $userModel = model('App\Models\UserModel');
        
        // [Check Token]
        if (empty($_GET['token'])) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Token eksik'
            ]);
        }

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

        if (count($user_token) == 0) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Geçerli token eksik'
            ]);
        }
        
        $userId = $user_token[0]['user_id'];
        
        // Check enquiry ID
        if (empty($_GET['enquiry_id'])) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Soru ID eksik'
            ]);
        }
        
        $enquiryId = (int)$_GET['enquiry_id'];
        
        // Get user info to check role
        $user = $userModel->find($userId);
        
        if (!$user || $user['type'] !== 'AGENT') {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Bu işlem sadece agent için geçerli'
            ]);
        }
        
        // Get basic enquiry info for agent
        $enquireModel = model('App\Models\EnquireModel');
        $info = $enquireModel->getAgentNotificationInfo($enquiryId, $userId);
        
        if (!$info) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Bildirim bilgisi bulunamadı'
            ]);
        }
        
        return $this->respond([
            'code'     => 'success',
            'message'  => 'Bildirim bilgisi başarıyla alındı',
            'property_id' => $info['property_id'],
            'property_title' => $info['property_title'],
            'has_enquiry' => true,
            'appointment_date' => $info['appointment_date'],
            'appointment_time' => $info['appointment_time']
        ]);
    }
    
    /**
     * Add a reply to an enquiry
     */
    public function addReply()
    {
        // Check authentication
        $tokenModel = model('App\Models\TokenModel');
        $userModel = model('App\Models\UserModel');
        
        $data_json = $this->request->getJSON();
        
        // [Check Token]
        if (empty($data_json->token)) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Token eksik'
            ]);
        }

        $token = $data_json->token;
        $user_token = $tokenModel->where('token', $token)->findAll(1);

        if (count($user_token) == 0) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Geçerli token eksik'
            ]);
        }
        
        $userId = $user_token[0]['user_id'];
        
        // Check required parameters
        if (empty($data_json->enquiry_id) || empty($data_json->message)) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Soru ID ve mesaj alanları zorunludur'
            ]);
        }
        
        $enquiryId = (int)$data_json->enquiry_id;
        $message = $data_json->message;
        $isSystemMessage = isset($data_json->system_message) ? (bool)$data_json->system_message : false;
        
        // Get user info to check role
        $user = $userModel->find($userId);
        
        if (!$user) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Kullanıcı bulunamadı'
            ]);
        }
        
        // Check if user is admin or agent
        $isAdmin = $user['type'] === 'ADMIN';
        $isAgent = $user['type'] === 'AGENT';
        
        if (!$isAdmin && !$isAgent) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Bu işlem için yetkiniz yok'
            ]);
        }
        
           // Add the reply
    $enquireModel = model('App\Models\EnquireModel');
    $replyId = $enquireModel->addReplyOptimized($enquiryId, $userId, $message, $isSystemMessage);
    
    if (!$replyId) {
        return $this->respond([
            'code' => 'failed',
            'message' => 'Cevap eklenirken bir hata oluştu veya yetkiniz yok'
        ]);
    }
    
    // Admin ise müşteriye bildirim gönder
    if ($isAdmin) {
        $user = $userModel->find($userId);
        $adminName = $user['name_surname'] ?? 'SatışaHazır Temsilcisi';
        
        $enquireModel->sendCustomerReplyNotification(
            $enquiryId,
            $replyId,
            $adminName,
            $message
        );
    }
    
    // Get updated enquiry details
    $enquiry = $enquireModel->getEnquiryWithRepliesOptimized($enquiryId, $userId, $isAdmin);
    
    return $this->respond([
        'code' => 'success',
        'message' => 'Cevap başarıyla eklendi',
        'reply_id' => $replyId,
        'enquiry' => $enquiry
    ]);

    }

    /**
     * Close an enquiry
     */
    public function closeEnquiry()
    {
        // Check authentication
        $tokenModel = model('App\Models\TokenModel');
        $userModel = model('App\Models\UserModel');
        
        $data_json = $this->request->getJSON();
        
        // [Check Token]
        if (empty($data_json->token)) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Token eksik'
            ]);
        }

        $token = $data_json->token;
        $user_token = $tokenModel->where('token', $token)->findAll(1);

        if (count($user_token) == 0) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Geçerli token eksik'
            ]);
        }
        
        $userId = $user_token[0]['user_id'];
        
        // Check required parameters
        if (empty($data_json->enquiry_id)) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Soru ID zorunludur'
            ]);
        }
        
        $enquiryId = (int)$data_json->enquiry_id;
        
        // Get user info to check role
        $user = $userModel->find($userId);
        
        if (!$user) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Kullanıcı bulunamadı'
            ]);
        }
        
        // Check if user is admin or agent
        $isAdmin = $user['type'] === 'ADMIN';
        $isAgent = $user['type'] === 'AGENT';
        
        if (!$isAdmin && !$isAgent) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Bu işlem için yetkiniz yok'
            ]);
        }
        
        // Close the enquiry
        $enquireModel = model('App\Models\EnquireModel');
        $success = $enquireModel->closeEnquiry($enquiryId, $userId);
        
        if (!$success) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Soru kapatılırken bir hata oluştu veya yetkiniz yok'
            ]);
        }
        
        return $this->respond([
            'code'     => 'success',
            'message'  => 'Soru başarıyla kapatıldı'
        ]);
    }

    /**
     * Send call reminder notification
     */
    public function sendCallReminder()
    {
        // Check authentication
        $tokenModel = model('App\Models\TokenModel');
        $userModel = model('App\Models\UserModel');
        
        $data_json = $this->request->getJSON();
        
        // [Check Token]
        if (empty($data_json->token)) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Token eksik'
            ]);
        }

        $token = $data_json->token;
        $user_token = $tokenModel->where('token', $token)->findAll(1);

        if (count($user_token) == 0) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Geçerli token eksik'
            ]);
        }
        
        $userId = $user_token[0]['user_id'];
        
        // Check required parameters
        if (empty($data_json->enquiry_id) || empty($data_json->customer_name)) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Soru ID ve müşteri ismi zorunludur'
            ]);
        }
        
        $enquiryId = (int)$data_json->enquiry_id;
        $customerName = $data_json->customer_name;
        
        // Get user info to check role
        $user = $userModel->find($userId);
        
        if (!$user) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Kullanıcı bulunamadı'
            ]);
        }
        
        // Check if user is admin or agent
        $isAdmin = $user['type'] === 'ADMIN';
        $isAgent = $user['type'] === 'AGENT';
        
        if (!$isAdmin && !$isAgent) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Bu işlem için yetkiniz yok'
            ]);
        }
        
        // Send call reminder
        $enquireModel = model('App\Models\EnquireModel');
        $success = $enquireModel->sendCallReminderNotification($enquiryId, $customerName, $userId);
        
        if (!$success) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Arama hatırlatması gönderilirken bir hata oluştu'
            ]);
        }
        
        return $this->respond([
            'code'     => 'success',
            'message'  => 'Arama hatırlatması başarıyla gönderildi'
        ]);
    }
    
    /**
     * Get unread enquiry count
     */
    public function getUnreadCount()
    {
        // Check authentication
        $tokenModel = model('App\Models\TokenModel');
        $userModel = model('App\Models\UserModel');
        
        // [Check Token]
        if (empty($_GET['token'])) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Token eksik'
            ]);
        }

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

        if (count($user_token) == 0) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Geçerli token eksik'
            ]);
        }
        
        $userId = $user_token[0]['user_id'];
        
        // Get user info to check role
        $user = $userModel->find($userId);
        
        if (!$user) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Kullanıcı bulunamadı'
            ]);
        }
        
        // Check if user is admin or agent
        $isAdmin = $user['type'] === 'ADMIN';
        $isAgent = $user['type'] === 'AGENT';
        
        if (!$isAdmin && !$isAgent) {
            return $this->respond([
                'code'     => 'failed',
                'message'  => 'Bu işlem için yetkiniz yok'
                ]);
        }
        
        // Get unread count
        $enquireModel = model('App\Models\EnquireModel');
        $unreadCount = $enquireModel->getUnreadCountOptimized($userId, $isAdmin);
        
        return $this->respond([
            'code'     => 'success',
            'message'  => 'Okunmamış soru sayısı başarıyla alındı',
            'unread_count' => $unreadCount
        ]);
    }
    
    /**
     * Store new enquiry and send notifications - HEAVILY OPTIMIZED
     */
    public function listing_agent_message()
    {
        $data = array(
            'code'	    => 'empty_code',
            'message'   => 'Empty Message'
        );

        $postBody = file_get_contents('php://input');
        $data_json = json_decode($postBody);

        if(empty($data_json->listing_id))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Missing listing id in request'
            ));
        }

        // OPTIMIZE: Early validation before heavy operations
        $validation = \Config\Services::validation();
        $validation->setRules([
            'listing_id' => ['label' => 'listing_id', 'rules' => 'required'],
            'Name' => ['label' => 'Name', 'rules' => 'required'],
            'Email' => ['label' => 'Email', 'rules' => ['required', 'valid_email']],
            'Phone' => ['label' => 'Phone', 'rules' => ['required']], 
            'Message' => ['label' => 'Message', 'rules' => ['required']],
        ]);

        if (!$validation->withRequest($this->request)->run()) {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => join("\n", $validation->getErrors())
            ));
        }

        // OPTIMIZE: Use cached models
        $listingModel = model('App\Models\ListingModel');
        $userModel = model('App\Models\UserModel');
        $settingsModel = model('App\Models\SettingsModel');

        // OPTIMIZE: Use simple find instead of complex where
        $items = $listingModel->select('property.*, property_lang.json_object, property.user_id')
                              ->join('property_lang', 'property.id = property_lang.property_id', 'left')
                              ->where('property.id', $data_json->listing_id)
                              ->where('property_lang.language_id', getenv('LANGUAGE_ID'))
                              ->findAll(1);

        if(count($items) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Listing id not found'
            ));
        }

        // get listing
        $listing = $items[0];

        // OPTIMIZE: Simplified user lookup
        $user = NULL;
        $email_to = NULL;
        $agent_id = NULL;
        
        if(!empty($listing['user_id'])) {
            $user = $userModel->find($listing['user_id']);
            if($user) {
                $email_to = $user['mail'];
                $agent_id = $user['id'];
            }
        }
        
        if(!$user) {
            // OPTIMIZE: Cache admin user
            $user = $userModel->where('type', 'ADMIN')->first();
            if($user) {
                $email_to = $settingsModel->get_setting('email');
            }
        }

        // OPTIMIZE: Prepare data early
        $data_json = $this->request->getJSON();
        
        $enquireModel = model('App\Models\EnquireModel');
        
          $customerId = null;
    if (!empty($data_json->user_id)) {
        $customerId = (int)$data_json->user_id;
    }
        
        // OPTIMIZE: Minimal data insertion
        $data = [
            'property_id' => $data_json->listing_id,
            'phone' => $data_json->Phone,
            'mail' => $data_json->Email,
            'name_surname' => $data_json->Name,
            'message' => $data_json->Message,
            'agent_id' => $agent_id,
             'user_id' => $customerId,
            'readed' => 0,
            'date' => date('Y-m-d H:i:s'),
            'status' => 'pending'
        ];
        
        // Add appointment date if provided
        if (!empty($data_json->appointment_date)) {
            $data['appointment_date'] = $data_json->appointment_date;
        }
        
        // Add appointment time if provided
        if (!empty($data_json->appointment_time)) {
            $data['appointment_time'] = $data_json->appointment_time;
        }

        try {
            // OPTIMIZE: Single insert operation
            $insert_id = $enquireModel->insert($data);
            
            if ($insert_id) {
                // OPTIMIZE: Bildirim gönderimi - Hemen çağır
                $data['id'] = $insert_id;
                
                 // OTOMATK SİSTEM MESAJLARINI EKLE
              
              $enquireModel->addAutomaticSystemMessages($insert_id, $customerId);
                
                // BİLDİRİM GÖNDERİMİ - SENKRON OLARAK
                try {
                    $notificationResult = $enquireModel->sendNewEnquiryNotificationsOptimized($data);
                    
                    if ($notificationResult) {
                        log_message('info', "Enquiry notifications sent successfully - EnquiryId: $insert_id");
                    } else {
                      log_message('error', "Enquiry notifications failed - EnquiryId: $insert_id");
                    }
                } catch (\Exception $e) {
                    // Bildirim hatası olsa bile soru kaydedildi
                    log_message('error', 'Notification error in listing_agent_message: ' . $e->getMessage());
                }
                
                return $this->respond(array(
                    'code'	    => 'success',
                    'message'   => 'Mesajınız başarı ile gönderildi. Temsilcilerimiz en kısa sürede size dönüş yapacaklar.',
                    'enquiry_id' => $insert_id
                ));
            } else {
                return $this->respond(array(
                    'code'	    => 'failed',
                    'message'   => 'Mesaj kaydedilemedi'
                ));
            }
            
        } catch (\Exception $e) {
            log_message('error', 'listing_agent_message error: ' . $e->getMessage());
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Sistem hatası oluştu'
            ));
        }
    }

    /**
     * Get upcoming appointments for reminder notifications (Cron job endpoint)
     */
    public function getUpcomingAppointments()
    {
        // This endpoint can be called by a cron job to send appointment reminders
        $enquireModel = model('App\Models\EnquireModel');
        $upcomingAppointments = $enquireModel->getUpcomingAppointmentsByDateTime();
        
        $notificationService = service('NotificationService');
        $userModel = model('App\Models\UserModel');
        $sentCount = 0;
        
        foreach ($upcomingAppointments as $enquiry) {
            // Check if appointment is actually in 5 minutes
            if (!empty($enquiry['appointment_date']) && 
                !empty($enquiry['appointment_time']) && 
                $enquiry['appointment_time'] !== 'En yakın zaman') {
                
                // Parse appointment date and time
                $appointmentDate = $enquiry['appointment_date']; // yyyy-mm-dd format
                $appointmentTimeStr = $enquiry['appointment_time']; // HH:MM-HH:MM format
                
                if (strpos($appointmentTimeStr, '-') !== false) {
                    $timeParts = explode('-', $appointmentTimeStr);
                    $startTime = trim($timeParts[0]);
                    $appointmentDateTime = $appointmentDate . ' ' . $startTime . ':00';
                    
                    $appointmentTimestamp = strtotime($appointmentDateTime);
                    $now = time();
                    $timeDiff = $appointmentTimestamp - $now;
                    
                    // If appointment is in 4-6 minutes, send reminder
                    if ($timeDiff >= 240 && $timeDiff <= 360) { // 4-6 minutes in seconds
                        
                        // Send notification to admin and agent
                        $notificationData = [
                            'property_id' => $enquiry['property_id'],
                            'enquiry_id' => $enquiry['id'],
                            'click_action' => 'OPEN_ENQUIRY_DETAIL',
                            'notification_type' => 'appointment_reminder'
                        ];
                        
                        $title = 'Randevu Hatırlatması';
                        $body = $enquiry['name_surname'] . ' müşterisi 5 dakika içinde aranacak - ' . $enquiry['property_address'];
                        
                        // Notify admin
                        $admins = $userModel->where('type', 'ADMIN')->findAll();
                        foreach ($admins as $admin) {
                            $notificationService->sendToUser(
                                $admin['id'],
                                $title,
                                $body,
                                $notificationData
                            );
                        }
                        
                        // Notify agent if assigned
                        if (!empty($enquiry['agent_id'])) {
                            $notificationService->sendToUser(
                                $enquiry['agent_id'],
                                $title,
                                $body,
                                $notificationData
                            );
                        }
                        
                        $sentCount++;
                    }
                }
            }
        }
        
        return $this->respond([
            'code' => 'success',
            'message' => "Sent {$sentCount} appointment reminders",
            'sent_count' => $sentCount
        ]);
    }
    
    
/**
 * Get user's own enquiries (for customers) - CHAT VIEW
 */
public function getMyEnquiries()
{
    $tokenModel = model('App\Models\TokenModel');
    $userModel = model('App\Models\UserModel');
    
    if (empty($_GET['token'])) {
        return $this->respond([
            'code' => 'failed',
            'message' => 'Token eksik'
        ]);
    }

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

    if (count($user_token) == 0) {
        return $this->respond([
            'code' => 'failed',
            'message' => 'Geçerli token eksik'
        ]);
    }
    
    $userId = $user_token[0]['user_id'];
    $user = $userModel->find($userId);
    
    if (!$user) {
        return $this->respond([
            'code' => 'failed',
            'message' => 'Kullanıcı bulunamadı'
        ]);
    }
    
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
    $offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;
    
    if ($limit > 50) {
        $limit = 50;
    }
    
    $enquireModel = model('App\Models\EnquireModel');
    
    // ✅ DÜZELTME: property.post_id ile JOIN ve language_id = 3
    $enquiries = $enquireModel->select('
            enquire.*, 
            property.image_filename as property_image_filename,
            property_lang.json_object as property_json
        ')
        ->join('property', 'property.id = enquire.property_id', 'left')
        ->join('property_lang', 'property_lang.property_id = enquire.property_id AND property_lang.language_id = 3', 'left')
        ->groupStart()
            ->where('enquire.user_id', $userId)
            ->orWhere('enquire.phone', $user['phone'])
            ->orWhere('enquire.mail', $user['mail'])
        ->groupEnd()
        ->orderBy('enquire.date', 'DESC')
        ->limit($limit, $offset)
        ->findAll();
    
    // Process enquiries
    $db = \Config\Database::connect();
    $totalUnread = 0;
    
    foreach ($enquiries as &$enquiry) {
        // ✅ JSON'dan field_10 (başlık) ve field_64 (adres) al
        $propertyTitle = 'İlan';
        $propertyAddress = '';
        
        if (!empty($enquiry['property_json'])) {
            $propertyData = json_decode($enquiry['property_json'], true);
            if ($propertyData) {
                // field_10 = başlık
                $propertyTitle = $propertyData['field_10'] ?? 'İlan';
                // field_64 = adres (Türkiye - İstanbul Avrupa Anadolu - Adalar - Burgazada Mah -)
                $propertyAddress = $propertyData['field_64'] ?? '';
            }
        }
        
        $enquiry['property_title'] = $propertyTitle;
        $enquiry['property_address'] = $propertyAddress;
        $enquiry['property_location'] = $propertyAddress;
        
        // ✅ Property image - sadece filename
        $propertyImage = '';
        if (!empty($enquiry['property_image_filename'])) {
            $filename = trim($enquiry['property_image_filename']);
            // Eğer virgülle ayrılmış liste varsa ilk resmi al
            if (strpos($filename, ',') !== false) {
                $images = explode(',', $filename);
                $propertyImage = trim($images[0]);
            } else {
                $propertyImage = $filename;
            }
        }
        $enquiry['property_image'] = $propertyImage;
        
        // Get replies (excluding admin-only notes)
        $replies = $db->table('enquire_replies')
            ->where('enquire_id', $enquiry['id'])
            ->where('(is_admin_only IS NULL OR is_admin_only = 0)')
            ->orderBy('created_at', 'ASC')
            ->get()
            ->getResultArray();
        
        $enquiry['replies'] = $replies;
        
        // Count unread replies from admin
        $lastReadTime = $enquiry['last_user_read'] ?? '2000-01-01 00:00:00';
        $unreadCount = $db->table('enquire_replies')
            ->where('enquire_id', $enquiry['id'])
            ->where('(is_admin_only IS NULL OR is_admin_only = 0)')
            ->where('(is_system_message IS NULL OR is_system_message = 0)')
            ->where('user_id IS NOT NULL')
            ->where('created_at >', $lastReadTime)
            ->countAllResults();
        
        $enquiry['unread_count'] = $unreadCount;
        $totalUnread += $unreadCount;
        
        // Cleanup
        unset($enquiry['property_json']);
        unset($enquiry['property_image_filename']);
    }
    
    // Get total count for pagination
    $total = $enquireModel
        ->groupStart()
            ->where('user_id', $userId)
            ->orWhere('phone', $user['phone'])
            ->orWhere('mail', $user['mail'])
        ->groupEnd()
        ->countAllResults();
    
    return $this->respond([
        'code' => 'success',
        'message' => 'Sorularınız başarıyla alındı',
        'enquiries' => $enquiries,
        'unread_count' => $totalUnread,
        'total' => $total,
        'has_more' => count($enquiries) >= $limit
    ]);
}

/**
 * Mark enquiry as read by user
 */
public function markEnquiryAsRead()
{
    $data_json = $this->request->getJSON();
    $tokenModel = model('App\Models\TokenModel');
    
    if (empty($data_json->token) || empty($data_json->enquiry_id)) {
        return $this->respond([
            'code' => 'failed',
            'message' => 'Token veya enquiry_id eksik'
        ]);
    }

    $token = $data_json->token;
    $user_token = $tokenModel->where('token', $token)->findAll(1);

    if (count($user_token) == 0) {
        return $this->respond([
            'code' => 'failed',
            'message' => 'Geçerli token eksik'
        ]);
    }
    
    $enquiryId = (int)$data_json->enquiry_id;
    $enquireModel = model('App\Models\EnquireModel');
    
    $success = $enquireModel->update($enquiryId, [
        'last_user_read' => date('Y-m-d H:i:s')
    ]);
    
    return $this->respond([
        'code' => $success ? 'success' : 'failed',
        'message' => $success ? 'Okundu olarak işaretlendi' : 'İşaretleme başarısız'
    ]);
}
/**
 * Send user reply
 */
public function sendUserReply()
{
    $data_json = $this->request->getJSON();
    $tokenModel = model('App\Models\TokenModel');
    $userModel = model('App\Models\UserModel');
    
    if (empty($data_json->token)) {
        return $this->respond([
            'code' => 'failed',
            'message' => 'Token eksik'
        ]);
    }

    $token = $data_json->token;
    $user_token = $tokenModel->where('token', $token)->findAll(1);

    if (count($user_token) == 0) {
        return $this->respond([
            'code' => 'failed',
            'message' => 'Geçerli token eksik'
        ]);
    }
    
    $userId = $user_token[0]['user_id'];
    
    if (empty($data_json->enquiry_id) || empty($data_json->message)) {
        return $this->respond([
            'code' => 'failed',
            'message' => 'Enquiry ID ve mesaj gerekli'
        ]);
    }
    
    $enquiryId = (int)$data_json->enquiry_id;
    $message = $data_json->message;
    
    $enquireModel = model('App\Models\EnquireModel');
    $enquiry = $enquireModel->find($enquiryId);
    
    if (!$enquiry) {
        return $this->respond([
            'code' => 'failed',
            'message' => 'Soru bulunamadı'
        ]);
    }
    
    // ✅ Kullanıcının bu enquiry'ye erişim yetkisi var mı kontrol et
    $user = $userModel->find($userId);
    if (!$user) {
        return $this->respond([
            'code' => 'failed',
            'message' => 'Kullanıcı bulunamadı'
        ]);
    }
    
    // Kullanıcının enquiry'sine ait olduğunu kontrol et
    if ($enquiry['user_id'] != $userId && 
        $enquiry['phone'] != $user['phone'] && 
        $enquiry['mail'] != $user['mail']) {
        return $this->respond([
            'code' => 'failed',
            'message' => 'Bu sorguya erişim yetkiniz yok'
        ]);
    }
    
    // ✅ ÖZEL BUTON CEVAPLARI - "Evet" veya "Hayır"
    $isCallbackResponse = false;
    $finalMessage = $message;
    
    if (strtolower(trim($message)) === 'evet' || strtolower(trim($message)) === 'yes') {
        $finalMessage = 'Evet, aranmak istiyorum.';
        $isCallbackResponse = true;
    } elseif (strtolower(trim($message)) === 'hayır' || strtolower(trim($message)) === 'hayir' || strtolower(trim($message)) === 'no') {
        $finalMessage = 'Hayır, aramaya gerek yok.';
        $isCallbackResponse = true;
    }
    
    // Add user reply
    $db = \Config\Database::connect();
    
    // ✅ DÜZELTME: user_id'yi insert et
    $replyData = [
        'enquire_id' => $enquiryId,
        'user_id' => $userId,
        'message' => $finalMessage,
        'is_user_message' => 1,
        'created_at' => date('Y-m-d H:i:s')
    ];
    
    $insertResult = $db->table('enquire_replies')->insert($replyData);
    
    if ($insertResult) {
        // ✅ Get the inserted reply ID
        $replyId = $db->insertID();
        
        // Update enquiry status
        $enquireModel->update($enquiryId, [
            'status' => 'answered',
            'last_user_read' => date('Y-m-d H:i:s')
        ]);
        
        // ✅ EVET cevabı ise otomatik sistem mesajı ekle
        if ($isCallbackResponse && strtolower(trim($message)) === 'evet') {
            sleep(1); // Kısa bekleme
            
            // Randevu bilgilerini al
            $appointmentDate = $enquiry['appointment_date'] ?? '';
            $appointmentTime = $enquiry['appointment_time'] ?? '';
            
            $systemMessage = 'SatışaHazır temsilcimiz';
            
            if (!empty($appointmentDate) && !empty($appointmentTime) && $appointmentTime !== 'En yakın zaman') {
                // Tarihi formatla (dd/mm/yyyy)
                try {
                    $dateObj = new \DateTime($appointmentDate);
                    $formattedDate = $dateObj->format('d/m/Y');
                    $systemMessage .= ", belirlediğiniz {$formattedDate} tarih ve {$appointmentTime} saatinde";
                } catch (\Exception $e) {
                    $systemMessage .= ', en kısa sürede';
                }
            } else {
                $systemMessage .= ', en kısa sürede';
            }
            
            $systemMessage .= ' sizi 444 58 03 nolu kurumsal hattımızdan arayarak bilgilendirecektir.';
            
            // ✅ DÜZELTME: Sistem mesajları için user_id NULL
            $systemReplyData = [
                'enquire_id' => $enquiryId,
                'user_id' => null, // ✅ NULL yerine 0 kullanma
                'message' => $systemMessage,
                'is_system_message' => 1,
                'created_at' => date('Y-m-d H:i:s')
            ];
            
            $db->table('enquire_replies')->insert($systemReplyData);
        }
        
        // Send notification to admins
        $userName = $user['name_surname'] ?? 'Kullanıcı';
        
        // Get property info
        $listingModel = model('App\Models\ListingModel');
        $property = $listingModel->select('property_lang.json_object')
            ->join('property_lang', 'property.id = property_lang.property_id', 'left')
            ->where('property.id', $enquiry['property_id'])
            ->where('property_lang.language_id', getenv('LANGUAGE_ID'))
            ->first();
        
        $propertyTitle = 'İlan';
        if ($property && !empty($property['json_object'])) {
            $propertyData = json_decode($property['json_object'], true);
            $propertyTitle = $propertyData['title'] ?? 'İlan';
        }
        
        // Send notification to admins
        try {
            $enquireModel->sendReplyNotification(
                $enquiryId,
                $replyId,
                $userName,
                $finalMessage,
                false
            );
        } catch (\Exception $e) {
            log_message('error', 'sendReplyNotification error: ' . $e->getMessage());
        }
        
     // ✅ Get updated enquiry with ALL replies (including new system message)
$updatedEnquiry = $enquireModel->select('
        enquire.*, 
        property.image_filename as property_image_filename,
        property_lang.json_object as property_json
    ')
    ->join('property', 'property.id = enquire.property_id', 'left')
    ->join('property_lang', 'property_lang.property_id = enquire.property_id AND property_lang.language_id = 3', 'left')
    ->where('enquire.id', $enquiryId)
    ->first();

if ($updatedEnquiry) {
    // ✅ JSON'dan field_10 (başlık) ve field_64 (adres) al
    $propertyTitle = 'İlan';
    $propertyAddress = '';
    
    if (!empty($updatedEnquiry['property_json'])) {
        $propertyData = json_decode($updatedEnquiry['property_json'], true);
        if ($propertyData) {
            // field_10 = başlık
            $propertyTitle = $propertyData['field_10'] ?? 'İlan';
            // field_64 = adres
            $propertyAddress = $propertyData['field_64'] ?? '';
        }
    }
    
    $updatedEnquiry['property_title'] = $propertyTitle;
    $updatedEnquiry['property_location'] = $propertyAddress;
    
    // Property image
    $propertyImage = '';
    if (!empty($updatedEnquiry['property_image_filename'])) {
        $filename = trim($updatedEnquiry['property_image_filename']);
        if (strpos($filename, ',') !== false) {
            $images = explode(',', $filename);
            $propertyImage = trim($images[0]);
        } else {
            $propertyImage = $filename;
        }
    }
    $updatedEnquiry['property_image'] = $propertyImage;
    
    // Get ALL replies
    $replies = $db->table('enquire_replies')
        ->where('enquire_id', $enquiryId)
        ->where('(is_admin_only IS NULL OR is_admin_only = 0)')
        ->orderBy('created_at', 'ASC')
        ->get()
        ->getResultArray();
    
    $updatedEnquiry['replies'] = $replies;
    
    // Cleanup
    unset($updatedEnquiry['property_json']);
    unset($updatedEnquiry['property_image_filename']);
}
        
        return $this->respond([
            'code' => 'success',
            'message' => 'Mesaj gönderildi',
            'reply_id' => $replyId,
            'enquiry' => $updatedEnquiry ?? null
        ]);
    } else {
        return $this->respond([
            'code' => 'failed',
            'message' => 'Mesaj gönderilemedi'
        ]);
    }
}


// ============================================================================
// EnquireController.php'ye eklenecek YENİ metod
// 
// İSİM: sendCustomerReplyNotification (mevcut sendReplyNotification ile KARIŞMASIN)
// 
// AMAÇ: CRM'den admin cevap yazınca SADECE MÜŞTERİYE bildirim göndermek
// ============================================================================

/**
 * 🔔 CRM'den admin cevap yazdığında SADECE MÜŞTERİYE bildirim gönder
 * 
 * POST /api/enquire/sendCustomerReplyNotification
 * 
 * MEVCUT sendReplyNotification ile KARIŞMAZ çünkü:
 * - sendReplyNotification: Kullanıcı → Admin/Agent bildiriminde kullanılıyor ✅
 * - sendCustomerReplyNotification: Admin → Müşteri bildiriminde kullanılacak ✅ (YENİ)
 * 
 * Parametreler:
 * - enquiry_id: Soru ID
 * - reply_id: Cevap ID (opsiyonel)
 * - message: Gönderilen mesaj
 * - is_admin_only: Admin notu mu? (0 veya 1)
 * - staff_name: Cevap yazan admin/agent adı
 */
public function sendCustomerReplyNotification()
{
    exit();
    try {
        // ✅ 1. BAŞLANGIÇ LOG
        log_message('info', '═══════════════════════════════════════════════════');
        log_message('info', '🔔 sendCustomerReplyNotification endpoint ÇAĞRILDI');
        log_message('info', '📍 Timestamp: ' . date('Y-m-d H:i:s'));
        
        // ✅ 2. POST VERİLERİNİ AL VE LOGLA
        $enquiry_id = $this->request->getPost('enquiry_id');
        $reply_id = $this->request->getPost('reply_id');
        $message = $this->request->getPost('message');
        $is_admin_only = $this->request->getPost('is_admin_only') ?? 0;
        $staff_name = $this->request->getPost('staff_name') ?? 'SatışaHazır Temsilcisi';
        
        log_message('info', '📦 Gelen Parametreler:');
        log_message('info', '  - enquiry_id: ' . ($enquiry_id ?? 'NULL'));
        log_message('info', '  - reply_id: ' . ($reply_id ?? 'NULL'));
        log_message('info', '  - message: ' . substr($message ?? '', 0, 50) . '...');
        log_message('info', '  - is_admin_only: ' . $is_admin_only);
        log_message('info', '  - staff_name: ' . $staff_name);
        
        // ✅ 3. VALİDASYON
        if (empty($enquiry_id)) {
            log_message('error', '❌ Validasyon hatası: enquiry_id eksik');
            return $this->respond([
                'success' => false,
                'message' => 'enquiry_id gerekli'
            ], 400);
        }
        
        if (empty($message)) {
            log_message('error', '❌ Validasyon hatası: message eksik');
            return $this->respond([
                'success' => false,
                'message' => 'message gerekli'
            ], 400);
        }
        
        log_message('info', '✅ Validasyon başarılı');
        
        // ✅ 4. ADMIN NOTU KONTROLÜ
        if ($is_admin_only == 1) {
            log_message('info', '📝 Admin notu algılandı - Müşteriye bildirim GÖNDERİLMEYECEK');
            return $this->respond([
                'success' => true,
                'message' => 'Admin notu - Bildirim gönderilmedi',
                'sent_count' => 0
            ]);
        }
        
        log_message('info', '👤 Normal cevap - Müşteriye bildirim gönderilecek');
        
        // ✅ 5. REPLY ID KONTROLÜ
        if (empty($reply_id)) {
            log_message('info', '🔍 Reply ID yok, son reply aranıyor...');
            
            $db = \Config\Database::connect();
            $lastReply = $db->table('enquire_replies')
                           ->where('enquire_id', $enquiry_id)
                           ->orderBy('created_at', 'DESC')
                           ->limit(1)
                           ->get()
                           ->getRowArray();
            
            if ($lastReply) {
                $reply_id = $lastReply['id'];
                log_message('info', '✅ Son reply bulundu: ' . $reply_id);
            } else {
                $reply_id = 0;
                log_message('warning', '⚠️ Hiç reply bulunamadı, reply_id = 0 olarak ayarlandı');
            }
        }
        
        // ✅ 6. MODEL METODUNU ÇAĞIR
        log_message('info', '📡 EnquireModel::sendCustomerReplyNotification() çağrılıyor...');
        log_message('info', '  - Enquiry ID: ' . $enquiry_id);
        log_message('info', '  - Reply ID: ' . $reply_id);
        log_message('info', '  - Staff Name: ' . $staff_name);
        
        $enquireModel = model('App\Models\EnquireModel');
        
        $success = $enquireModel->sendCustomerReplyNotification(
            $enquiry_id,
            $reply_id,
            $staff_name,
            $message
        );
        
        // ✅ 7. SONUÇ LOG
        if ($success) {
            log_message('info', '✅✅✅ Müşteriye bildirim BAŞARIYLA gönderildi!');
            log_message('info', '  - Enquiry ID: ' . $enquiry_id);
            log_message('info', '  - Reply ID: ' . $reply_id);
            log_message('info', '═══════════════════════════════════════════════════');
            
            return $this->respond([
                'success' => true,
                'message' => 'Müşteriye bildirim başarıyla gönderildi',
                'sent_count' => 1,
                'enquiry_id' => $enquiry_id,
                'reply_id' => $reply_id
            ]);
        } else {
            log_message('warning', '⚠️⚠️⚠️ Bildirim gönderilemedi (müşteri/token bulunamadı)');
            log_message('info', '  - Enquiry ID: ' . $enquiry_id);
            log_message('info', '═══════════════════════════════════════════════════');
            
            return $this->respond([
                'success' => true,
                'message' => 'Bildirim gönderilemedi (müşteri bulunamadı veya token yok)',
                'sent_count' => 0
            ]);
        }
        
    } catch (\Exception $e) {
        log_message('error', '❌❌❌ EXCEPTION OLUŞTU!');
        log_message('error', '  - Hata: ' . $e->getMessage());
        log_message('error', '  - Dosya: ' . $e->getFile() . ':' . $e->getLine());
        log_message('error', '  - Stack Trace: ' . $e->getTraceAsString());
        log_message('info', '═══════════════════════════════════════════════════');
        
        return $this->respond([
            'success' => false,
            'message' => 'Bildirim gönderilemedi: ' . $e->getMessage()
        ], 500);
    }
}


// ============================================================================
// AÇIKLAMA:
// 
// Bu endpoint CRM'den çağrılır ve EnquireModel::sendCustomerReplyNotification() 
// metodunu kullanır.
//
// Mevcut sendReplyNotification endpoint'i ile KARIŞMAZ çünkü:
// 1. Farklı isim: sendCustomerReplyNotification
// 2. Farklı amaç: Admin → Müşteri (diğeri Müşteri → Admin)
// 3. Farklı route: /api/enquire/sendCustomerReplyNotification
// ============================================================================
}