<?php
/**
 * ============================================================================
 * classes/Story.php - Story Management Class
 * ============================================================================
 */

namespace App;

class Story {
    private $conn;
    private $table_name = "user_stories";
    
    public function __construct($db) {
        $this->conn = $db;
    }
    
    /**
     * Create a new story
     */
    public function create($userId, $mediaType, $mediaUrl = null, $content = null) {
        // Stories expire after 24 hours
        $expiresAt = date('Y-m-d H:i:s', strtotime('+24 hours'));
        
        $query = "INSERT INTO user_stories 
                  (user_id, media_type, media_url, content, expires_at) 
                  VALUES (:user_id, :media_type, :media_url, :content, :expires_at)";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->bindParam(':media_type', $mediaType);
        $stmt->bindParam(':media_url', $mediaUrl);
        $stmt->bindParam(':content', $content);
        $stmt->bindParam(':expires_at', $expiresAt);
        
        if ($stmt->execute()) {
            return $this->conn->lastInsertId();
        }
        
        return false;
    }
    
    /**
     * Get active stories from friends and user
     */
    public function getActiveFeedStories($userId) {
        $query = "SELECT 
                    s.id as story_id,
                    s.user_id,
                    s.media_type,
                    s.media_url,
                    s.content,
                    s.views_count,
                    s.created_at,
                    s.expires_at,
                    u.full_name,
                    u.profile_picture,
                    (SELECT COUNT(*) FROM story_views sv WHERE sv.story_id = s.id AND sv.viewer_id = :user_id1) as viewed_by_user,
                    (SELECT COUNT(*) FROM user_stories WHERE user_id = s.user_id AND expires_at > NOW()) as total_stories_count
                FROM user_stories s
                INNER JOIN users u ON s.user_id = u.id
                WHERE s.expires_at > NOW()
                AND (
                    s.user_id = :user_id2
                    OR EXISTS (
                        SELECT 1 FROM friendships f 
                        WHERE ((f.user_id = s.user_id AND f.friend_id = :user_id3) 
                        OR (f.friend_id = s.user_id AND f.user_id = :user_id4))
                        AND f.status = 'accepted'
                    )
                )
                ORDER BY 
                    CASE WHEN s.user_id = :user_id5 THEN 0 ELSE 1 END,
                    s.created_at DESC";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':user_id1', $userId);
        $stmt->bindParam(':user_id2', $userId);
        $stmt->bindParam(':user_id3', $userId);
        $stmt->bindParam(':user_id4', $userId);
        $stmt->bindParam(':user_id5', $userId);
        $stmt->execute();
        
        $stories = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        // Group stories by user
        $groupedStories = [];
        foreach ($stories as $story) {
            $userId = $story['user_id'];
            if (!isset($groupedStories[$userId])) {
                $groupedStories[$userId] = [
                    'user_id' => $story['user_id'],
                    'full_name' => $story['full_name'],
                    'profile_picture' => $story['profile_picture'],
                    'total_stories' => $story['total_stories_count'],
                    'has_unseen' => !$story['viewed_by_user'],
                    'stories' => []
                ];
            }
            $groupedStories[$userId]['stories'][] = $story;
        }
        
        return array_values($groupedStories);
    }
    
    /**
     * Get user's stories
     */
    public function getUserStories($userId) {
        $query = "SELECT 
                    s.*,
                    u.full_name,
                    u.profile_picture
                FROM user_stories s
                INNER JOIN users u ON s.user_id = u.id
                WHERE s.user_id = :user_id
                AND s.expires_at > NOW()
                ORDER BY s.created_at DESC";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->execute();
        
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }
    
    /**
     * Get single story
     */
    public function getStory($storyId) {
        $query = "SELECT 
                    s.*,
                    u.full_name,
                    u.profile_picture
                FROM user_stories s
                INNER JOIN users u ON s.user_id = u.id
                WHERE s.id = :story_id
                AND s.expires_at > NOW()";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':story_id', $storyId);
        $stmt->execute();
        
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }
    
    /**
     * Mark story as viewed
     */
    public function markAsViewed($storyId, $viewerId) {
        // Check if already viewed
        $checkQuery = "SELECT id FROM story_views 
                       WHERE story_id = :story_id AND viewer_id = :viewer_id";
        $checkStmt = $this->conn->prepare($checkQuery);
        $checkStmt->bindParam(':story_id', $storyId);
        $checkStmt->bindParam(':viewer_id', $viewerId);
        $checkStmt->execute();
        
        if ($checkStmt->rowCount() > 0) {
            return true; // Already viewed
        }
        
        // Insert view record
        $query = "INSERT INTO story_views (story_id, viewer_id) 
                  VALUES (:story_id, :viewer_id)";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':story_id', $storyId);
        $stmt->bindParam(':viewer_id', $viewerId);
        
        return $stmt->execute();
    }
    
    /**
     * Get story viewers
     */
    public function getViewers($storyId) {
        $query = "SELECT 
                    sv.id,
                    sv.viewed_at,
                    u.id as user_id,
                    u.full_name,
                    u.profile_picture
                FROM story_views sv
                INNER JOIN users u ON sv.viewer_id = u.id
                WHERE sv.story_id = :story_id
                ORDER BY sv.viewed_at DESC";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':story_id', $storyId);
        $stmt->execute();
        
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }
    
    /**
     * Delete story
     */
    public function delete($storyId, $userId) {
        $query = "DELETE FROM user_stories 
                  WHERE id = :story_id AND user_id = :user_id";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':story_id', $storyId);
        $stmt->bindParam(':user_id', $userId);
        
        return $stmt->execute();
    }
    
    /**
     * Clean up expired stories
     */
    public function cleanupExpired() {
        // Get expired stories with media
        $query = "SELECT id, media_url FROM user_stories 
                  WHERE expires_at <= NOW() AND media_url IS NOT NULL";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        $expiredStories = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        // Delete media files
        foreach ($expiredStories as $story) {
            if ($story['media_url']) {
                $filename = basename($story['media_url']);
                $filePath = __DIR__ . '/../assets/uploads/stories/' . $filename;
                if (file_exists($filePath)) {
                    unlink($filePath);
                }
            }
        }
        
        // Delete expired stories from database
        $deleteQuery = "DELETE FROM user_stories WHERE expires_at <= NOW()";
        $deleteStmt = $this->conn->prepare($deleteQuery);
        return $deleteStmt->execute();
    }
}