<?php
/**
 * ============================================================================
 * classes/Chat.php - Chat Management Class (One-on-One Only)
 * ============================================================================
 */

namespace App;

class Chat {
    private $conn;
    private $table_name = "chats";
    
    public function __construct($db) {
        $this->conn = $db;
    }
    
    /**
     * Get all one-on-one chats for a user (Facebook-style)
     */
    public function getUserChats($userId) {
        $query = "SELECT 
                    c.id,
                    c.created_at,
                    c.updated_at,
                    -- Get the other user's details
                    other_user.id as friend_id,
                    other_user.full_name as chat_name,
                    other_user.profile_picture as chat_avatar,
                    other_user.last_activity as friend_last_activity,
                    -- Last message details
                    (SELECT m.content 
                     FROM messages m 
                     WHERE m.chat_id = c.id 
                     AND m.is_encrypted = 0
                     ORDER BY m.created_at DESC 
                     LIMIT 1) as last_message,
                    (SELECT m.created_at 
                     FROM messages m 
                     WHERE m.chat_id = c.id 
                     ORDER BY m.created_at DESC 
                     LIMIT 1) as last_message_time,
                    (SELECT m.sender_id
                     FROM messages m 
                     WHERE m.chat_id = c.id 
                     ORDER BY m.created_at DESC 
                     LIMIT 1) as last_sender_id,
                    (SELECT m.is_encrypted
                     FROM messages m 
                     WHERE m.chat_id = c.id 
                     ORDER BY m.created_at DESC 
                     LIMIT 1) as last_message_encrypted,
                    -- Unread count
                    (SELECT COUNT(*) 
                     FROM messages m 
                     WHERE m.chat_id = c.id 
                     AND m.created_at > COALESCE(cm.last_read_at, '2000-01-01')
                     AND m.sender_id != :user_id) as unread_count
                FROM chats c
                INNER JOIN chat_members cm ON c.id = cm.chat_id
                INNER JOIN chat_members cm2 ON c.id = cm2.chat_id AND cm2.user_id != cm.user_id
                INNER JOIN users other_user ON cm2.user_id = other_user.id
                WHERE c.chat_type = 'one_to_one'
                AND cm.user_id = :user_id2
                ORDER BY 
                    CASE 
                        WHEN last_message_time IS NULL THEN 1 
                        ELSE 0 
                    END,
                    last_message_time DESC";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->bindParam(':user_id2', $userId);
        $stmt->execute();
        
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }
    
    /**
     * Create or get one-on-one chat
     */
    public function createOrGetOneOnOne($userId1, $userId2) {
        try {
            // Prevent self-chat
            if ($userId1 == $userId2) {
                return false;
            }
            
            // Check if chat already exists between these two users
            $query = "SELECT c.id 
                      FROM chats c
                      INNER JOIN chat_members cm1 ON c.id = cm1.chat_id
                      INNER JOIN chat_members cm2 ON c.id = cm2.chat_id
                      WHERE c.chat_type = 'one_to_one'
                      AND cm1.user_id = :user1
                      AND cm2.user_id = :user2
                      LIMIT 1";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':user1', $userId1);
            $stmt->bindParam(':user2', $userId2);
            $stmt->execute();
            
            $existing = $stmt->fetch(\PDO::FETCH_ASSOC);
            
            if ($existing) {
                return $existing['id'];
            }
            
            // Create new chat
            $this->conn->beginTransaction();
            
            $query = "INSERT INTO chats (chat_type, created_by, created_at, updated_at) 
                      VALUES ('one_to_one', :created_by, NOW(), NOW())";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':created_by', $userId1);
            $stmt->execute();
            
            $chatId = $this->conn->lastInsertId();
            
            // Add both members
            $this->addMember($chatId, $userId1);
            $this->addMember($chatId, $userId2);
            
            $this->conn->commit();
            
            return $chatId;
            
        } catch (\Exception $e) {
            if ($this->conn->inTransaction()) {
                $this->conn->rollBack();
            }
            error_log('Create chat error: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Add member to chat
     */
    public function addMember($chatId, $userId, $role = 'member') {
        $query = "INSERT INTO chat_members (chat_id, user_id, role, joined_at) 
                  VALUES (:chat_id, :user_id, :role, NOW())";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':chat_id', $chatId);
        $stmt->bindParam(':user_id', $userId);
        $stmt->bindParam(':role', $role);
        
        return $stmt->execute();
    }
    
    /**
     * Get chat details for one-on-one chat
     */
    public function getChatDetails($chatId, $userId) {
        $query = "SELECT 
                    c.*,
                    other_user.id as friend_id,
                    other_user.full_name as display_name,
                    other_user.profile_picture as display_avatar,
                    other_user.last_activity as friend_last_activity,
                    cm.role as user_role,
                    -- Check if friend is online (active in last 5 minutes)
                    CASE 
                        WHEN other_user.last_activity > DATE_SUB(NOW(), INTERVAL 5 MINUTE)
                        THEN 1 
                        ELSE 0 
                    END as is_online
                FROM chats c
                INNER JOIN chat_members cm ON c.id = cm.chat_id
                INNER JOIN chat_members cm2 ON c.id = cm2.chat_id AND cm2.user_id != cm.user_id
                INNER JOIN users other_user ON cm2.user_id = other_user.id
                WHERE c.id = :chat_id 
                AND c.chat_type = 'one_to_one'
                AND cm.user_id = :user_id";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':chat_id', $chatId);
        $stmt->bindParam(':user_id', $userId);
        $stmt->execute();
        
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }
    
    /**
     * Check if user is member of chat
     */
    public function isMember($chatId, $userId) {
        $query = "SELECT COUNT(*) as count 
                  FROM chat_members 
                  WHERE chat_id = :chat_id AND user_id = :user_id";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':chat_id', $chatId);
        $stmt->bindParam(':user_id', $userId);
        $stmt->execute();
        
        $result = $stmt->fetch(\PDO::FETCH_ASSOC);
        return $result['count'] > 0;
    }
    
    /**
     * Update last read timestamp
     */
    public function updateLastRead($chatId, $userId) {
        $query = "UPDATE chat_members 
                  SET last_read_at = NOW() 
                  WHERE chat_id = :chat_id AND user_id = :user_id";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':chat_id', $chatId);
        $stmt->bindParam(':user_id', $userId);
        
        return $stmt->execute();
    }
    
    /**
     * Delete chat (actually just remove user from members)
     */
    public function deleteChat($chatId, $userId) {
        $query = "DELETE FROM chat_members 
                  WHERE chat_id = :chat_id AND user_id = :user_id";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':chat_id', $chatId);
        $stmt->bindParam(':user_id', $userId);
        
        return $stmt->execute();
    }
    
    /**
     * Search in chats
     */
    public function searchChats($userId, $searchTerm) {
        $searchTerm = "%{$searchTerm}%";
        
        $query = "SELECT DISTINCT
                    c.id,
                    other_user.full_name as chat_name,
                    other_user.profile_picture as chat_avatar,
                    other_user.id as friend_id
                FROM chats c
                INNER JOIN chat_members cm ON c.id = cm.chat_id
                INNER JOIN chat_members cm2 ON c.id = cm2.chat_id AND cm2.user_id != cm.user_id
                INNER JOIN users other_user ON cm2.user_id = other_user.id
                WHERE c.chat_type = 'one_to_one'
                AND cm.user_id = :user_id
                AND (other_user.full_name LIKE :search 
                     OR EXISTS (
                         SELECT 1 FROM messages m 
                         WHERE m.chat_id = c.id 
                         AND m.content LIKE :search2
                         AND m.is_encrypted = 0
                     ))
                ORDER BY other_user.full_name ASC
                LIMIT 20";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->bindParam(':search', $searchTerm);
        $stmt->bindParam(':search2', $searchTerm);
        $stmt->execute();
        
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }
    
    /**
     * Get user's online friends who they have chats with
     */
    public function getOnlineFriends($userId) {
        $query = "SELECT DISTINCT
                    other_user.id,
                    other_user.full_name,
                    other_user.profile_picture,
                    other_user.last_activity
                FROM chats c
                INNER JOIN chat_members cm ON c.id = cm.chat_id
                INNER JOIN chat_members cm2 ON c.id = cm2.chat_id AND cm2.user_id != cm.user_id
                INNER JOIN users other_user ON cm2.user_id = other_user.id
                WHERE c.chat_type = 'one_to_one'
                AND cm.user_id = :user_id
                AND other_user.last_activity > DATE_SUB(NOW(), INTERVAL 5 MINUTE)
                ORDER BY other_user.last_activity DESC";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->execute();
        
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }
}