<?php
/**
 * ============================================================================
 * classes/Group_Enhanced.php - Enhanced Group Management Class
 * Facebook-style group features
 * ============================================================================
 */

namespace App;

use PDO;
use Exception;

class GroupEnhanced extends Group {
    
    /**
     * Update a post
     */
    public function updatePost($postId, $userId, $content, $groupId) {
        try {
            // Get the database connection from parent
            $db = $this->getDb();
            
            // Check if user owns the post
            $sql = "SELECT user_id FROM group_posts WHERE id = ? AND group_id = ?";
            $stmt = $db->prepare($sql);
            $stmt->execute([$postId, $groupId]);
            $post = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$post) {
                return ['success' => false, 'message' => 'Post not found'];
            }
            
            if ($post['user_id'] != $userId) {
                return ['success' => false, 'message' => 'You can only edit your own posts'];
            }
            
            $sql = "UPDATE group_posts SET content = ?, updated_at = NOW() 
                    WHERE id = ? AND user_id = ?";
            $stmt = $db->prepare($sql);
            $stmt->execute([$content, $postId, $userId]);
            
            return ['success' => true, 'message' => 'Post updated successfully'];
            
        } catch (Exception $e) {
            error_log("Update post error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Failed to update post'];
        }
    }
    
    /**
     * Get a single post with details
     */
    public function getPost($postId) {
        $db = $this->getDb();
        
        $sql = "SELECT gp.*, 
                u.full_name, u.profile_picture,
                (SELECT COUNT(*) FROM group_post_likes WHERE post_id = gp.id) as likes_count,
                (SELECT COUNT(*) FROM group_post_comments WHERE post_id = gp.id) as comments_count
                FROM group_posts gp
                JOIN users u ON gp.user_id = u.id
                WHERE gp.id = ?";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$postId]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    /**
     * Check if user has liked a post
     */
    public function hasLikedPost($postId, $userId) {
        $db = $this->getDb();
        
        $sql = "SELECT id FROM group_post_likes WHERE post_id = ? AND user_id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$postId, $userId]);
        return $stmt->fetch() !== false;
    }
    
    /**
     * Get post likes
     */
    public function getPostLikes($postId, $limit = 50) {
        $db = $this->getDb();
        
        $sql = "SELECT gpl.*, u.full_name, u.profile_picture
                FROM group_post_likes gpl
                JOIN users u ON gpl.user_id = u.id
                WHERE gpl.post_id = ?
                ORDER BY gpl.created_at DESC
                LIMIT ?";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$postId, $limit]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    /**
     * Delete a comment
     */
    public function deleteComment($commentId, $userId, $groupId) {
        try {
            $db = $this->getDb();
            
            // Get comment details
            $sql = "SELECT gpc.user_id, gp.group_id 
                    FROM group_post_comments gpc
                    JOIN group_posts gp ON gpc.post_id = gp.id
                    WHERE gpc.id = ?";
            $stmt = $db->prepare($sql);
            $stmt->execute([$commentId]);
            $comment = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$comment) {
                return ['success' => false, 'message' => 'Comment not found'];
            }
            
            // Check permissions (comment owner or group admin)
            $isOwner = ($comment['user_id'] == $userId);
            $isAdmin = $this->isAdmin($groupId, $userId);
            
            if (!$isOwner && !$isAdmin) {
                return ['success' => false, 'message' => 'Unauthorized'];
            }
            
            $sql = "DELETE FROM group_post_comments WHERE id = ?";
            $stmt = $db->prepare($sql);
            $stmt->execute([$commentId]);
            
            return ['success' => true, 'message' => 'Comment deleted'];
            
        } catch (Exception $e) {
            error_log("Delete comment error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Failed to delete comment'];
        }
    }
    
    /**
     * Update comment
     */
    public function updateComment($commentId, $userId, $content) {
        try {
            $db = $this->getDb();
            
            // Check if user owns the comment
            $sql = "SELECT user_id FROM group_post_comments WHERE id = ?";
            $stmt = $db->prepare($sql);
            $stmt->execute([$commentId]);
            $comment = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$comment || $comment['user_id'] != $userId) {
                return ['success' => false, 'message' => 'Unauthorized'];
            }
            
            $sql = "UPDATE group_post_comments SET content = ?, updated_at = NOW() 
                    WHERE id = ? AND user_id = ?";
            $stmt = $db->prepare($sql);
            $stmt->execute([$content, $commentId, $userId]);
            
            return ['success' => true, 'message' => 'Comment updated'];
            
        } catch (Exception $e) {
            error_log("Update comment error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Failed to update comment'];
        }
    }
    
    /**
     * Search members
     */
    public function searchMembers($groupId, $query) {
        $db = $this->getDb();
        $searchTerm = '%' . $query . '%';
        
        $sql = "SELECT gm.*, u.full_name, u.profile_picture, u.district_id, u.email
                FROM group_members gm
                JOIN users u ON gm.user_id = u.id
                WHERE gm.group_id = ? 
                AND gm.status = 'active'
                AND u.full_name LIKE ?
                ORDER BY u.full_name ASC
                LIMIT 20";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$groupId, $searchTerm]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    /**
     * Get member statistics
     */
    public function getMemberStats($groupId, $userId) {
        $db = $this->getDb();
        
        $sql = "SELECT 
                (SELECT COUNT(*) FROM group_posts WHERE group_id = ? AND user_id = ?) as posts_count,
                (SELECT COUNT(*) FROM group_post_comments gpc 
                 JOIN group_posts gp ON gpc.post_id = gp.id 
                 WHERE gp.group_id = ? AND gpc.user_id = ?) as comments_count,
                (SELECT COUNT(*) FROM group_post_likes gpl
                 JOIN group_posts gp ON gpl.post_id = gp.id
                 WHERE gp.group_id = ? AND gpl.user_id = ?) as likes_count";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$groupId, $userId, $groupId, $userId, $groupId, $userId]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    /**
     * Get group analytics (admin only)
     */
    public function getGroupAnalytics($groupId, $userId) {
        if (!$this->isAdmin($groupId, $userId)) {
            return null;
        }
        
        $db = $this->getDb();
        
        $sql = "SELECT 
                (SELECT COUNT(*) FROM group_members WHERE group_id = ? AND status = 'active') as total_members,
                (SELECT COUNT(*) FROM group_members WHERE group_id = ? AND status = 'pending') as pending_requests,
                (SELECT COUNT(*) FROM group_posts WHERE group_id = ?) as total_posts,
                (SELECT COUNT(*) FROM group_post_comments gpc 
                 JOIN group_posts gp ON gpc.post_id = gp.id 
                 WHERE gp.group_id = ?) as total_comments,
                (SELECT COUNT(*) FROM group_post_likes gpl
                 JOIN group_posts gp ON gpl.post_id = gp.id
                 WHERE gp.group_id = ?) as total_likes,
                (SELECT COUNT(*) FROM group_members 
                 WHERE group_id = ? AND DATE(joined_at) >= DATE_SUB(NOW(), INTERVAL 7 DAY)) as new_members_week,
                (SELECT COUNT(*) FROM group_posts 
                 WHERE group_id = ? AND DATE(created_at) >= DATE_SUB(NOW(), INTERVAL 7 DAY)) as new_posts_week";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$groupId, $groupId, $groupId, $groupId, $groupId, $groupId, $groupId]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    /**
     * Ban a member (admin only)
     */
    public function banMember($groupId, $memberId, $adminId) {
        try {
            if (!$this->isAdmin($groupId, $adminId)) {
                return ['success' => false, 'message' => 'Unauthorized'];
            }
            
            $db = $this->getDb();
            
            // Can't ban another admin
            $sql = "SELECT role FROM group_members WHERE group_id = ? AND user_id = ?";
            $stmt = $db->prepare($sql);
            $stmt->execute([$groupId, $memberId]);
            $member = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($member && $member['role'] === 'admin') {
                return ['success' => false, 'message' => 'Cannot ban an admin'];
            }
            
            $sql = "UPDATE group_members SET status = 'banned' 
                    WHERE group_id = ? AND user_id = ?";
            $stmt = $db->prepare($sql);
            $stmt->execute([$groupId, $memberId]);
            
            return ['success' => true, 'message' => 'Member banned'];
            
        } catch (Exception $e) {
            error_log("Ban member error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Failed to ban member'];
        }
    }
    
    /**
     * Unban a member (admin only)
     */
    public function unbanMember($groupId, $memberId, $adminId) {
        try {
            if (!$this->isAdmin($groupId, $adminId)) {
                return ['success' => false, 'message' => 'Unauthorized'];
            }
            
            $db = $this->getDb();
            
            $sql = "UPDATE group_members SET status = 'active' 
                    WHERE group_id = ? AND user_id = ? AND status = 'banned'";
            $stmt = $db->prepare($sql);
            $stmt->execute([$groupId, $memberId]);
            
            if ($stmt->rowCount() > 0) {
                return ['success' => true, 'message' => 'Member unbanned'];
            } else {
                return ['success' => false, 'message' => 'Member not found or not banned'];
            }
            
        } catch (Exception $e) {
            error_log("Unban member error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Failed to unban member'];
        }
    }
    
    /**
     * Get banned members
     */
    public function getBannedMembers($groupId) {
        $db = $this->getDb();
        
        $sql = "SELECT gm.*, u.full_name, u.profile_picture, u.email
                FROM group_members gm
                JOIN users u ON gm.user_id = u.id
                WHERE gm.group_id = ? AND gm.status = 'banned'
                ORDER BY gm.joined_at DESC";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$groupId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    /**
     * Update group details (admin only)
     */
    public function updateGroup($groupId, $userId, $data) {
        try {
            if (!$this->isAdmin($groupId, $userId)) {
                return ['success' => false, 'message' => 'Unauthorized'];
            }
            
            $db = $this->getDb();
            
            $allowedFields = ['group_name', 'description', 'category', 'privacy', 'rules', 'location'];
            $updateFields = [];
            $params = [];
            
            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $updateFields[] = "$field = ?";
                    $params[] = $data[$field];
                }
            }
            
            if (empty($updateFields)) {
                return ['success' => false, 'message' => 'No fields to update'];
            }
            
            $params[] = $groupId;
            $sql = "UPDATE groups SET " . implode(', ', $updateFields) . " WHERE id = ?";
            
            $stmt = $db->prepare($sql);
            $stmt->execute($params);
            
            return ['success' => true, 'message' => 'Group updated successfully'];
            
        } catch (Exception $e) {
            error_log("Update group error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Failed to update group'];
        }
    }
    
    /**
     * Get top contributors
     */
    public function getTopContributors($groupId, $limit = 10) {
        $db = $this->getDb();
        
        $sql = "SELECT u.id, u.full_name, u.profile_picture, gm.role,
                COUNT(DISTINCT gp.id) as post_count,
                COUNT(DISTINCT gpc.id) as comment_count,
                (COUNT(DISTINCT gp.id) + COUNT(DISTINCT gpc.id)) as total_activity
                FROM group_members gm
                JOIN users u ON gm.user_id = u.id
                LEFT JOIN group_posts gp ON gp.user_id = u.id AND gp.group_id = ?
                LEFT JOIN group_post_comments gpc ON gpc.user_id = u.id 
                    AND gpc.post_id IN (SELECT id FROM group_posts WHERE group_id = ?)
                WHERE gm.group_id = ? AND gm.status = 'active'
                GROUP BY u.id, u.full_name, u.profile_picture, gm.role
                ORDER BY total_activity DESC
                LIMIT ?";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$groupId, $groupId, $groupId, $limit]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}