<?php
/**
 * Message Model
 * Handles database operations for messages table
 */

require_once __DIR__ . '/../Core/init.php';

class Message
{
    private $db;
    
    public function __construct()
    {
        $this->db = Database::getInstance();
    }
    
    /**
     * Create a new message record
     */
    public function create($data)
    {
        try {
            $sql = "INSERT INTO messages (
                subject, content, recipient_type, recipient_id, recipient_name, 
                sender_id, status, sent_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
            
            $result = $this->db->execute($sql, [
                $data['subject'],
                $data['content'],
                $data['recipient_type'],
                $data['recipient_id'] ?? null,
                $data['recipient_name'] ?? null,
                $data['sender_id'],
                $data['status'] ?? 'sent'
            ]);
            
            return $result ? $this->db->lastInsertId() : false;
        } catch (Exception $e) {
            error_log("Message creation failed: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get all messages with pagination and optional filtering
     */
    /**
 * Get all messages with pagination and optional filtering
 */
    public function getAll($limit = 20, $offset = 0, $filters = [])
    {
        try {
            $where_conditions = [];
            $params = [];
            
            // Apply filters
            if (!empty($filters['recipient_type'])) {
                $where_conditions[] = "recipient_type = ?";
                $params[] = $filters['recipient_type'];
            }
            
            if (!empty($filters['search'])) {
                $where_conditions[] = "(subject LIKE ? OR content LIKE ? OR recipient_name LIKE ?)";
                $search_term = '%' . $filters['search'] . '%';
                $params[] = $search_term;
                $params[] = $search_term;
                $params[] = $search_term;
            }
            
            if (!empty($filters['date_from'])) {
                $where_conditions[] = "DATE(sent_at) >= ?";
                $params[] = $filters['date_from'];
            }
            
            if (!empty($filters['date_to'])) {
                $where_conditions[] = "DATE(sent_at) <= ?";
                $params[] = $filters['date_to'];
            }
            
            $where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';
            
            // FIXED: Check if users table has 'name' column or use email
            $sql = "SELECT m.*, 
                        COALESCE(u.name, u.email) as sender_name, 
                        u.email as sender_email 
                    FROM messages m 
                    LEFT JOIN users u ON m.sender_id = u.id 
                    $where_clause 
                    ORDER BY m.sent_at DESC 
                    LIMIT ? OFFSET ?";
            
            $params[] = (int)$limit;
            $params[] = (int)$offset;
            
            $messages = $this->db->fetchAll($sql, $params);
            
            // DEBUG: Check what we're getting
            error_log("Retrieved " . count($messages) . " messages");
            if (!empty($messages)) {
                error_log("First message: " . print_r($messages[0], true));
            }
            
            return $messages;
        } catch (Exception $e) {
            error_log("Message retrieval failed: " . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Get total count of messages for pagination
     */
    public function getCount($filters = [])
    {
        try {
            $where_conditions = [];
            $params = [];
            
            // Apply filters
            if (!empty($filters['recipient_type'])) {
                $where_conditions[] = "recipient_type = ?";
                $params[] = $filters['recipient_type'];
            }
            
            if (!empty($filters['search'])) {
                $where_conditions[] = "(subject LIKE ? OR content LIKE ? OR recipient_name LIKE ?)";
                $search_term = '%' . $filters['search'] . '%';
                $params[] = $search_term;
                $params[] = $search_term;
                $params[] = $search_term;
            }
            
            if (!empty($filters['date_from'])) {
                $where_conditions[] = "DATE(sent_at) >= ?";
                $params[] = $filters['date_from'];
            }
            
            if (!empty($filters['date_to'])) {
                $where_conditions[] = "DATE(sent_at) <= ?";
                $params[] = $filters['date_to'];
            }
            
            $where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';
            
            $sql = "SELECT COUNT(*) as count FROM messages $where_clause";
            
            $result = $this->db->fetch($sql, $params);
            return (int)($result['count'] ?? 0);
        } catch (Exception $e) {
            error_log("Message count failed: " . $e->getMessage());
            return 0;
        }
    }
    
    /**
     * Get message by ID
     */
    public function getById($id)
    {
        try {
            $sql = "SELECT m.*, u.name as sender_name, u.email as sender_email 
                   FROM messages m 
                   LEFT JOIN users u ON m.sender_id = u.id 
                   WHERE m.id = ?";
            
            return $this->db->fetch($sql, [$id]);
        } catch (Exception $e) {
            error_log("Message retrieval by ID failed: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Delete message by ID
     */
    public function delete($id)
    {
        try {
            $sql = "DELETE FROM messages WHERE id = ?";
            return $this->db->execute($sql, [$id]);
        } catch (Exception $e) {
            error_log("Message deletion failed: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get message statistics
     */
    /**
 * Get message statistics
 */
    public function getStatistics()
    {
        try {
            $stats = [];
            
            // Total messages
            $result = $this->db->fetch("SELECT COUNT(*) as count FROM messages");
            $stats['total'] = (int)($result['count'] ?? 0);
            
            // Messages by recipient type - FIXED
            $stats['by_type'] = $this->db->fetchAll("SELECT recipient_type, COUNT(*) as count FROM messages GROUP BY recipient_type");
            
            // Messages sent today
            $result = $this->db->fetch("SELECT COUNT(*) as count FROM messages WHERE DATE(sent_at) = CURDATE()");
            $stats['today'] = (int)($result['count'] ?? 0);
            
            // Messages sent this week
            $result = $this->db->fetch("SELECT COUNT(*) as count FROM messages WHERE WEEK(sent_at) = WEEK(NOW()) AND YEAR(sent_at) = YEAR(NOW())");
            $stats['this_week'] = (int)($result['count'] ?? 0);
            
            return $stats;
        } catch (Exception $e) {
            error_log("Message statistics failed: " . $e->getMessage());
            return [
                'total' => 0,
                'by_type' => [],
                'today' => 0,
                'this_week' => 0
            ];
        }
    }
    
    /**
     * Get recent messages for dashboard
     */
    public function getRecent($limit = 10)
    {
        try {
            $sql = "SELECT m.*, u.name as sender_name 
                   FROM messages m 
                   LEFT JOIN users u ON m.sender_id = u.id 
                   ORDER BY m.sent_at DESC 
                   LIMIT ?";
            
            return $this->db->fetchAll($sql, [(int)$limit]);
        } catch (Exception $e) {
            error_log("Recent messages retrieval failed: " . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Get recipient type display name
     */
    public function getRecipientTypeDisplay($type)
    {
        $types = [
            'individual_vendor' => 'Individual Vendor',
            'individual_customer' => 'Individual Customer',
            'all_vendors' => 'All Vendors',
            'all_customers' => 'All Customers',
            'all_admins' => 'All Administrators'
        ];
        
        return $types[$type] ?? $type;
    }
    
    /**
     * Get recipient type badge class
     */
    public function getRecipientTypeBadgeClass($type)
    {
        $classes = [
            'individual_vendor' => 'badge badge-primary',
            'individual_customer' => 'badge badge-success',
            'all_vendors' => 'badge badge-warning',
            'all_customers' => 'badge badge-info',
            'all_admins' => 'badge badge-secondary'
        ];
        
        return $classes[$type] ?? 'badge badge-light';
    }

    /**
     * Get unread messages count for a user
     */
    public function getUnreadCount($user_id, $user_type = null)
    {
        try {
            // For now, return 0 since we don't have read/unread tracking
            // This can be enhanced later by adding a read_at column to messages table
            return 0;
            
            // Future implementation would be:
            // $sql = "SELECT COUNT(*) as count FROM messages 
            //         WHERE recipient_id = ? 
            //         AND (recipient_type = ? OR recipient_type LIKE 'all_%')
            //         AND read_at IS NULL";
            // $result = $this->db->fetch($sql, [$user_id, $user_type]);
            // return (int)($result['count'] ?? 0);
        } catch (Exception $e) {
            error_log("Unread count failed: " . $e->getMessage());
            return 0;
        }
    }
}