<?php

namespace App\Models;

use CodeIgniter\Model;

class EnquireModel extends Model
{
    protected $table = 'enquire';
    protected $primaryKey = 'id';
    
    protected $useAutoIncrement = true;
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    
    protected $allowedFields = [
        'property_id',
        'agent_id',
        'phone',
        'mail',
        'user_id',
        'name_surname',
        'message',
        'appointment_date',
        'appointment_time',
        'readed',
        'last_user_read',
        'status',
        'date'
    ];
    
    protected $useTimestamps = false;
    
    /**
     * Yeni soru sorulduğunda çağrılacak bildirim gönderme metodu - OPTİMİZE EDİLDİ
     */
    public function sendNewEnquiryNotificationsOptimized($enquiryData)
    {
        try {
            // NotificationService ve models
            $notificationService = service('NotificationService');
            $notificationModel = model('App\Models\NotificationModel');
            $userModel = model('App\Models\UserModel');
            $listingModel = model('App\Models\ListingModel');
            
            $enquiryId = $enquiryData['id'];
            $propertyId = $enquiryData['property_id'];
            $agentId = $enquiryData['agent_id'] ?? null;
            $customerName = $enquiryData['name_surname'] ?? 'Müşteri';
            
            // Property bilgilerini al
            $property = $listingModel->select('property.*, property_lang.json_object')
                                   ->join('property_lang', 'property.id = property_lang.property_id', 'left')
                                   ->where('property.id', $propertyId)
                                   ->where('property_lang.language_id', getenv('LANGUAGE_ID'))
                                   ->first();
            
            if (!$property) {
                log_message('error', "Property bulunamadı: $propertyId");
                return false;
            }
            
            // Property başlığını al
            $propertyTitle = 'İlan';
            if (!empty($property['json_object'])) {
                $propertyData = json_decode($property['json_object'], true);
                if (isset($propertyData['title'])) {
                    $propertyTitle = $propertyData['title'];
                }
            }
            
            // Property adresini al (kısaltılmış)
            $propertyAddress = '';
            if (!empty($property['json_object'])) {
                $propertyData = json_decode($property['json_object'], true);
                if (isset($propertyData['address'])) {
                    $propertyAddress = mb_strlen($propertyData['address']) > 50 
                        ? mb_substr($propertyData['address'], 0, 47) . '...' 
                        : $propertyData['address'];
                }
            }
            
            $success = true;
            
            // 1. TÜM ADMİNLERE BİLDİRİM GÖNDER
            $admins = $userModel->where('type', 'ADMIN')->findAll();
            
            foreach ($admins as $admin) {
                // Admin bildirim içeriği
                $adminTitle = 'Yeni Soru: ' . $propertyTitle;
                $adminBody = $customerName . ' müşterisinden yeni bir soru geldi';
                
                // Admin için detaylı data
                $adminData = [
                    'enquiry_id' => $enquiryId,
                    'property_id' => $propertyId,
                    'notification_type' => 'new_enquiry_admin',
                    'click_action' => 'OPEN_ENQUIRY_DETAIL',
                    'property_title' => $propertyTitle,
                    'customer_name' => $customerName,
                    'agent_id' => $agentId
                ];
                
                // Notifications tablosuna kayıt ekle
                $notificationModel->addNotification([
                    'user_id' => $admin['id'],
                    'title' => $adminTitle,
                    'body' => $adminBody,
                    'data' => json_encode($adminData),
                    'target' => 'enquiry_admin',
                    'status' => 'sent'
                ]);
                
                // Push bildirimi gönder
                $result = $notificationService->sendToUser(
                    $admin['id'],
                    $adminTitle,
                    $adminBody,
                    $adminData
                );
                
                if (!$result) {
                    $success = false;
                    log_message('error', "Admin bildirim gönderilemedi - UserId: {$admin['id']}, EnquiryId: $enquiryId");
                } else {
                    log_message('info', "Admin bildirim gönderildi - UserId: {$admin['id']}, EnquiryId: $enquiryId");
                }
            }
            
            // 2. AGENT'A BİLDİRİM GÖNDER (Eğer agent atanmışsa ve admin değilse)
            if ($agentId) {
                $agent = $userModel->find($agentId);
                
                if ($agent && $agent['type'] === 'AGENT') {
                    // Agent bildirim içeriği (müşteri bilgileri gizli)
                    $agentTitle = 'Yeni Talep: ' . $propertyTitle;
                    $agentBody = $propertyTitle . ' mülkünüz için 1 soru talebi alındı';
                    
                    // Agent için sınırlı data (müşteri bilgileri yok)
                    $agentData = [
                        'enquiry_id' => $enquiryId,
                        'property_id' => $propertyId,
                        'notification_type' => 'new_enquiry_agent',
                        'click_action' => 'OPEN_ENQUIRY_DETAIL',
                        'property_title' => $propertyTitle,
                        'property_address' => $propertyAddress
                    ];
                    
                    // Notifications tablosuna kayıt ekle
                    $notificationModel->addNotification([
                        'user_id' => $agentId,
                        'title' => $agentTitle,
                        'body' => $agentBody,
                        'data' => json_encode($agentData),
                        'target' => 'enquiry_agent',
                        'status' => 'sent'
                    ]);
                    
                    // Push bildirimi gönder
                    $result = $notificationService->sendToUser(
                        $agentId,
                        $agentTitle,
                        $agentBody,
                        $agentData
                    );
                    
                    if (!$result) {
                        $success = false;
                        log_message('error', "Agent bildirim gönderilemedi - AgentId: $agentId, EnquiryId: $enquiryId");
                    } else {
                        log_message('info', "Agent bildirim gönderildi - AgentId: $agentId, EnquiryId: $enquiryId");
                    }
                }
            }
            
            return $success;
            
        } catch (\Exception $e) {
            log_message('error', 'Enquiry notification error: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Cevap eklendiğinde bildirim gönder
     */
    public function sendReplyNotification($enquiryId, $replyId, $replierName, $message, $isAgent = false)
    {
        try {
            // Enquiry bilgilerini al
            $enquiry = $this->getEnquiryWithProperty($enquiryId);
            if (!$enquiry) {
                return false;
            }
            
            $propertyTitle = $enquiry['property_title'] ?? 'İlan';
            $agentId = $enquiry['agent_id'] ?? null;
            
            // NotificationService ve models
            $notificationService = service('NotificationService');
            $notificationModel = model('App\Models\NotificationModel');
            $userModel = model('App\Models\UserModel');
            
            // Özet mesaj (max 100 karakter)
            $shortMessage = mb_strlen($message) > 100 
                ? mb_substr($message, 0, 97) . '...' 
                : $message;
            
            // Bildirim içeriği
            $title = 'Yeni Cevap: ' . $propertyTitle;
            $body = $replierName . ': ' . $shortMessage;
            
            // Ek veriler
            $data = [
                'enquiry_id' => $enquiryId,
                'reply_id' => $replyId,
                'notification_type' => 'enquiry_reply',
                'click_action' => 'OPEN_ENQUIRY_DETAIL',
                'property_title' => $propertyTitle
            ];
            
            $success = true;
            
        //    if ($isAgent) {
                // Temsilci cevapladıysa, adminlere bildirim gönder
              //  $admins = $userModel->where('type', 'ADMIN')->findAll();
               $admins = $userModel->whereIn('type', ['ADMIN', 'AGENT_ADMIN'])->findAll(); 
                foreach ($admins as $admin) {
                    // Notifications tablosuna kayıt ekle
                    $notificationModel->addNotification([
                        'user_id' => $admin['id'],
                        'title' => $title,
                        'body' => $body,
                        'data' => json_encode($data),
                        'target' => 'enquiry_reply',
                        'status' => 'sent'
                    ]);
                    
                    // Push bildirimi gönder
                    $result = $notificationService->sendToUser(
                        $admin['id'],
                        $title,
                        $body,
                        $data
                    );
                    
                    if (!$result) {
                        $success = false;
                    }
                }
       //     } else {
                // Admin cevapladıysa, temsilciye bildirim gönder
                if ($agentId) {
                    $agent = $userModel->find($agentId);
                    
                    if ($agent && $agent['type'] === 'AGENT') {
                        // Notifications tablosuna kayıt ekle
                        $notificationModel->addNotification([
                            'user_id' => $agentId,
                            'title' => $title,
                            'body' => $body,
                            'data' => json_encode($data),
                            'target' => 'enquiry_reply',
                            'status' => 'sent'
                        ]);
                        
                        // Push bildirimi gönder
                        $result = $notificationService->sendToUser(
                            $agentId,
                            $title,
                            $body,
                            $data
                        );
                        
                        if (!$result) {
                            $success = false;
                        }
                    }
                }
         //   }
            
            return $success;
            
        } catch (\Exception $e) {
            log_message('error', 'Reply notification error: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Enquiry'yi property ile birlikte getir
     */
    private function getEnquiryWithProperty($enquiryId)
    {
        $listingModel = model('App\Models\ListingModel');
        
        $enquiry = $this->find($enquiryId);
        if (!$enquiry) {
            return null;
        }
        
        // Property bilgilerini al
        $property = $listingModel->select('property.*, 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();
        
        if ($property && !empty($property['json_object'])) {
            $propertyData = json_decode($property['json_object'], true);
            $enquiry['property_title'] = $propertyData['title'] ?? 'İlan';
        } else {
            $enquiry['property_title'] = 'İlan';
        }
        
        return $enquiry;
    }
    
    /**
     * Optimized: Get enquiries with appointments for listing
     */
    public function getEnquiriesWithAppointmentsOptimized($userId, $isAdmin, $limit = 20, $offset = 0)
    {
        $builder = $this->db->table($this->table . ' e');
        
        // Base query with joins - property_user tablosunu kullanarak user bilgisini al
        $builder->select('
            e.*,
            pu.user_id as property_owner_id,
            pl.json_object as property_data,
            u.name_surname as agent_name
        ')
        ->join('property p', 'e.property_id = p.id', 'left')
        ->join('property_user pu', 'p.id = pu.property_id', 'left')
        ->join('property_lang pl', 'p.id = pl.property_id AND pl.language_id = ' . getenv('LANGUAGE_ID'), 'left')
        ->join('user u', 'e.agent_id = u.id', 'left');
        
        // Role-based filtering
        if (!$isAdmin) {
            // Agent can only see their own enquiries
            $builder->where('e.agent_id', $userId);
        }
        
        // Order and limit
        $builder->orderBy('e.date', 'DESC')
                ->limit($limit, $offset);
        
        $enquiries = $builder->get()->getResultArray();
        
        // Process enquiries
        foreach ($enquiries as &$enquiry) {
            // Parse property data
            if (!empty($enquiry['property_data'])) {
                $propertyData = json_decode($enquiry['property_data'], true);
                $enquiry['property_title'] = $propertyData['title'] ?? 'İlan';
                $enquiry['property_address'] = $propertyData['address'] ?? '';
            } else {
                $enquiry['property_title'] = 'İlan';
                $enquiry['property_address'] = '';
            }
            
            // Get replies
            $enquiry['replies'] = $this->getEnquiryReplies($enquiry['id']);
            
            // Clean up
            unset($enquiry['property_data']);
        }
        
        return $enquiries;
    }
    
    /**
     * Get enquiry replies
     */
    private function getEnquiryReplies($enquiryId)
    {
        // Mevcut enquire_replies tablosunu kullan
        $db = \Config\Database::connect();
        return $db->table('enquire_replies')
                  ->where('enquire_id', $enquiryId)
                  ->orderBy('created_at', 'ASC')
                  ->get()
                  ->getResultArray();
    }
    
    /**
     * Optimized: Get enquiry with replies
     */
    public function getEnquiryWithRepliesOptimized($enquiryId, $userId, $isAdmin)
    {
        $builder = $this->db->table($this->table . ' e');
        
        $builder->select('
            e.*,
            pu.user_id as property_owner_id,
            pl.json_object as property_data,
            u.name_surname as agent_name
        ')
        ->join('property p', 'e.property_id = p.id', 'left')
        ->join('property_user pu', 'p.id = pu.property_id', 'left')
        ->join('property_lang pl', 'p.id = pl.property_id AND pl.language_id = ' . getenv('LANGUAGE_ID'), 'left')
        ->join('user u', 'e.agent_id = u.id', 'left')
        ->where('e.id', $enquiryId);
        
        // Role-based access control
        if (!$isAdmin) {
            $builder->where('e.agent_id', $userId);
        }
        
        $enquiry = $builder->get()->getRowArray();
        
        if (!$enquiry) {
            return null;
        }
        
        // Parse property data
        if (!empty($enquiry['property_data'])) {
            $propertyData = json_decode($enquiry['property_data'], true);
            $enquiry['property_title'] = $propertyData['title'] ?? 'İlan';
            $enquiry['property_address'] = $propertyData['address'] ?? '';
        } else {
            $enquiry['property_title'] = 'İlan';
            $enquiry['property_address'] = '';
        }
        
        // Get replies
        $enquiry['replies'] = $this->getEnquiryReplies($enquiryId);
        
        // Clean up
        unset($enquiry['property_data']);
        
        return $enquiry;
    }
    
    /**
     * Optimized: Get unread count
     */
    public function getUnreadCountOptimized($userId, $isAdmin)
    {
        $builder = $this->db->table($this->table);
        
        $builder->where('readed', 0);
        
        if (!$isAdmin) {
            $builder->where('agent_id', $userId);
        }
        
        return $builder->countAllResults();
    }
    
    /**
     * Add reply - optimized
     */
    public function addReplyOptimized($enquiryId, $userId, $message, $isSystemMessage = false)
    {
        // Check access rights
        $enquiry = $this->find($enquiryId);
        if (!$enquiry) {
            return false;
        }
        
        // Check if user has permission
        $userModel = model('App\Models\UserModel');
        $user = $userModel->find($userId);
        
        if (!$user) {
            return false;
        }
        
        $isAdmin = $user['type'] === 'ADMIN';
        $isAgent = $user['type'] === 'AGENT';
        
        if (!$isAdmin && !$isAgent) {
            return false;
        }
        
        // Agent can only reply to their own enquiries
        if ($isAgent && $enquiry['agent_id'] != $userId) {
            return false;
        }
        
        // Add reply using direct database insert
        $db = \Config\Database::connect();
        
        $replyData = [
            'enquire_id' => $enquiryId,
            'user_id' => $userId,
            'message' => $message,
            'is_system_message' => $isSystemMessage ? 1 : 0,
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        $replyId = $db->table('enquire_replies')->insert($replyData);
        
        if ($replyId) {
            // Update enquiry status
            $this->update($enquiryId, [
                'status' => 'answered',
                'readed' => 1
            ]);
            
            // Send notification
            $replierName = $user['name_surname'] ?? ($isAdmin ? 'Admin' : 'Temsilci');
            $this->sendReplyNotification($enquiryId, $replyId, $replierName, $message, $isAgent);
        }
        
        return $replyId;
    }
    
    /**
     * Add admin note
     */
    public function addAdminNote($enquiryId, $userId, $note, $isAdminOnly = true)
    {
        // Check if user is admin
        $userModel = model('App\Models\UserModel');
        $user = $userModel->find($userId);
        
        if (!$user || $user['type'] !== 'ADMIN') {
            return false;
        }
        
        // Add note as reply using direct database insert
        $db = \Config\Database::connect();
        
        $replyData = [
            'enquire_id' => $enquiryId,
            'user_id' => $userId,
            'message' => $note,
            'is_admin_only' => $isAdminOnly ? 1 : 0,
            'is_system_message' => 1,
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        return $db->table('enquire_replies')->insert($replyData);
    }
    
    /**
     * Close enquiry
     */
    public function closeEnquiry($enquiryId, $userId)
    {
        // Check access rights
        $enquiry = $this->find($enquiryId);
        if (!$enquiry) {
            return false;
        }
        
        $userModel = model('App\Models\UserModel');
        $user = $userModel->find($userId);
        
        if (!$user) {
            return false;
        }
        
        $isAdmin = $user['type'] === 'ADMIN';
        $isAgent = $user['type'] === 'AGENT';
        
        if (!$isAdmin && !$isAgent) {
            return false;
        }
        
        // Agent can only close their own enquiries
        if ($isAgent && $enquiry['agent_id'] != $userId) {
            return false;
        }
        
        return $this->update($enquiryId, [
            'status' => 'closed',
            'readed' => 1
        ]);
    }
    
    /**
     * Get customer enquiries - admin only
     */
    public function getCustomerEnquiries($customerPhone)
    {
        return $this->where('phone', $customerPhone)
                   ->orderBy('date', 'DESC')
                   ->findAll();
    }
    
    /**
     * Get property enquiries - admin only
     */
    public function getPropertyEnquiries($propertyId)
    {
        return $this->where('property_id', $propertyId)
                   ->orderBy('date', 'DESC')
                   ->findAll();
    }
    
    /**
     * Get agent notification info
     */
    public function getAgentNotificationInfo($enquiryId, $userId)
    {
        $builder = $this->db->table($this->table . ' e');
        
        $builder->select('
            e.property_id,
            e.appointment_date,
            e.appointment_time,
            pl.json_object as property_data
        ')
        ->join('property_lang pl', 'e.property_id = pl.property_id AND pl.language_id = ' . getenv('LANGUAGE_ID'), 'left')
        ->where('e.id', $enquiryId)
        ->where('e.agent_id', $userId);
        
        $result = $builder->get()->getRowArray();
        
        if (!$result) {
            return null;
        }
        
        // Parse property data
        $propertyTitle = 'İlan';
        if (!empty($result['property_data'])) {
            $propertyData = json_decode($result['property_data'], true);
            $propertyTitle = $propertyData['title'] ?? 'İlan';
        }
        
        return [
            'property_id' => $result['property_id'],
            'property_title' => $propertyTitle,
            'appointment_date' => $result['appointment_date'],
            'appointment_time' => $result['appointment_time']
        ];
    }
    
    /**
     * Send call reminder notification
     */
    public function sendCallReminderNotification($enquiryId, $customerName, $userId)
    {
        try {
            $enquiry = $this->getEnquiryWithProperty($enquiryId);
            if (!$enquiry) {
                return false;
            }
            
            $propertyTitle = $enquiry['property_title'] ?? 'İlan';
            
            $notificationService = service('NotificationService');
            $notificationModel = model('App\Models\NotificationModel');
            $userModel = model('App\Models\UserModel');
            
            // Bildirim içeriği
            $title = 'Arama Hatırlatması';
            $body = $customerName . ' müşterisi aranmalı - ' . $propertyTitle;
            
            $data = [
                'enquiry_id' => $enquiryId,
                'notification_type' => 'call_reminder',
                'click_action' => 'OPEN_ENQUIRY_DETAIL',
                'property_title' => $propertyTitle,
                'customer_name' => $customerName
            ];
            
            // Adminlere gönder
            $admins = $userModel->where('type', 'ADMIN')->findAll();
            $success = true;
            
            foreach ($admins as $admin) {
                // Notifications tablosuna kayıt ekle
                $notificationModel->addNotification([
                    'user_id' => $admin['id'],
                    'title' => $title,
                    'body' => $body,
                    'data' => json_encode($data),
                    'target' => 'call_reminder',
                    'status' => 'sent'
                ]);
                
                // Push bildirimi gönder
                $result = $notificationService->sendToUser(
                    $admin['id'],
                    $title,
                    $body,
                    $data
                );
                
                if (!$result) {
                    $success = false;
                }
            }
            
            return $success;
            
        } catch (\Exception $e) {
            log_message('error', 'Call reminder notification error: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get upcoming appointments for reminders
     */
    public function getUpcomingAppointmentsByDateTime()
    {
        $builder = $this->db->table($this->table . ' e');
        
        $builder->select('
            e.*,
            pl.json_object as property_data
        ')
        ->join('property_lang pl', 'e.property_id = pl.property_id AND pl.language_id = ' . getenv('LANGUAGE_ID'), 'left')
        ->where('e.appointment_date IS NOT NULL')
        ->where('e.appointment_time IS NOT NULL')
        ->where('e.appointment_time !=', 'En yakın zaman')
        ->where('e.status !=', 'closed')
        ->where('DATE(e.appointment_date)', date('Y-m-d'));
        
        $results = $builder->get()->getResultArray();
        
        // Process results
        foreach ($results as &$result) {
            if (!empty($result['property_data'])) {
                $propertyData = json_decode($result['property_data'], true);
                $result['property_address'] = $propertyData['address'] ?? '';
            } else {
                $result['property_address'] = '';
            }
            unset($result['property_data']);
        }
        
        return $results;
    }
    
    /**
 * Send notification to customer when admin replies
 */
public function sendCustomerReplyNotification($enquiryId, $replyId, $adminName, $message)
{
    try {
        $enquiry = $this->getEnquiryWithProperty($enquiryId);
        if (!$enquiry) {
            return false;
        }
        
        $propertyTitle = $enquiry['property_title'] ?? 'İlan';
        
        $notificationService = service('NotificationService');
        $notificationModel = model('App\Models\NotificationModel');
        $userModel = model('App\Models\UserModel');
        
        // Özet mesaj
        $shortMessage = mb_strlen($message) > 100 
            ? mb_substr($message, 0, 97) . '...' 
            : $message;
        
        // Bildirim içeriği
        $title = 'Yeni Cevap: ' . $propertyTitle;
        $body = $adminName . ': ' . $shortMessage;
        
        // Ek veriler
        $data = [
            'enquiry_id' => $enquiryId,
            'reply_id' => $replyId,
            'notification_type' => 'enquiry_reply',
            'click_action' => 'OPEN_USER_CHAT',
            'property_title' => $propertyTitle
        ];
        
        // Müşteriyi telefon veya email ile bul
        $customer = $userModel->where('phone', $enquiry['phone'])
                             ->orWhere('mail', $enquiry['mail'])
                             ->first();
        
        if ($customer) {
            // Notifications tablosuna kayıt ekle
            $notificationModel->addNotification([
                'user_id' => $customer['id'],
                'title' => $title,
                'body' => $body,
                'data' => json_encode($data),
                'target' => 'enquiry_reply_customer',
                'status' => 'sent'
            ]);
            
            // Push bildirimi gönder
            $result = $notificationService->sendToUser(
                $customer['id'],
                $title,
                $body,
                $data
            );
            
            return $result;
        }
        
        return false;
        
    } catch (\Exception $e) {
        log_message('error', 'Customer reply notification error: ' . $e->getMessage());
        return false;
    }
}
    
    /**
 * Add automatic system messages after enquiry creation
 */
/**
 * Add automatic system messages after enquiry creation
 */
public function addAutomaticSystemMessages($enquiryId, $userId = null)
{
    try {
        $db = \Config\Database::connect();
        
        if ($userId === null) {
            $enquiry = $this->find($enquiryId);
            if ($enquiry) {
                $userId = $enquiry['user_id'] ?? null;
            }
        }
        
        if ($userId === null) {
            $userId = 0;
        }
        
        // First system message
        $firstMessage = "Talebiniz SatışaHazır temsilcimize iletilmiştir. En kısa sürede size dönüş yapılacaktır.";
        
        $replyData1 = [
            'enquire_id' => $enquiryId,
            'user_id' => $userId,
            'message' => $firstMessage,
            'is_system_message' => 1,
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        $db->table('enquire_replies')->insert($replyData1);
        
        sleep(1);
        
        // ✅ Second system message - BUTTON PROMPT
        $secondMessage = "Sizi arayarak bilgilendirmemizi ister misiniz?";
        
        $replyData2 = [
            'enquire_id' => $enquiryId,
            'user_id' => $userId,
            'message' => $secondMessage,
            'is_system_message' => 1,
            'is_button_prompt' => 1, // ✅ Özel flag - buton göstermek için
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        $db->table('enquire_replies')->insert($replyData2);
        
        return true;
    } catch (\Exception $e) {
        log_message('error', 'Error adding automatic system messages: ' . $e->getMessage());
        return false;
    }
}
}