<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Config\Database;
use App\Middleware\AuthMiddleware;
use PDO;

class StoryController extends Controller {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance()->getConnection();
    }

    public function feed() {
        $userId = AuthMiddleware::authenticate();

        // Get stories from followed users + own stories + seed users?
        // Simple feed: All active stories
        $stmt = $this->db->prepare("
            SELECT s.*, u.username, u.display_name, u.avatar_url, u.is_seed, u.seed_label
            FROM stories s
            JOIN users u ON s.user_id = u.id
            WHERE s.expires_at > NOW() AND s.deleted_at IS NULL
            ORDER BY s.created_at DESC
            LIMIT 50
        ");
        $stmt->execute();
        $stories = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Fetch comments for each story
        foreach ($stories as &$story) {
            // Count total comments
            $stmtCount = $this->db->prepare("SELECT COUNT(*) FROM story_comments WHERE story_id = ?");
            $stmtCount->execute([$story['id']]);
            $story['comment_count'] = (int)$stmtCount->fetchColumn();

            // Fetch latest 3 comments
            $stmtComments = $this->db->prepare("
                SELECT c.*, u.username, u.display_name, u.avatar_url
                FROM story_comments c
                JOIN users u ON c.user_id = u.id
                WHERE c.story_id = ?
                ORDER BY c.created_at DESC
                LIMIT 3
            ");
            $stmtComments->execute([$story['id']]);
            $story['latest_comments'] = array_reverse($stmtComments->fetchAll(PDO::FETCH_ASSOC));
        }

        $this->json($stories);
    }

    public function create() {
        $userId = AuthMiddleware::authenticate();
        $input = $this->input();
        
        $this->validate($input, ['type' => 'required']);

        $content = isset($input['content']) ? $input['content'] : null;
        $mediaUrl = isset($input['media_url']) ? $input['media_url'] : null;
        
        if (!$content && !$mediaUrl) {
            $this->json(['error' => 'Story must have content or media'], 422);
        }

        // 1. Character Limit Check (155 chars)
        if ($content && mb_strlen($content) > 155) {
            $this->json(['error' => 'Story content exceeds 155 characters limit.'], 400);
        }

        // 2. Daily Limit Check — Plus: 10, Normal: 3
        $stmtPlus = $this->db->prepare("SELECT is_plus_subscriber FROM users WHERE id = ?");
        $stmtPlus->execute([$userId]);
        $isPlus = (int)($stmtPlus->fetchColumn() ?: 0) === 1;
        $storyLimit = $isPlus ? 10 : 3;

        $stmt = $this->db->prepare("SELECT COUNT(*) FROM stories WHERE user_id = ? AND created_at >= CURDATE()");
        $stmt->execute([$userId]);
        $dailyCount = $stmt->fetchColumn();

        if ($dailyCount >= $storyLimit) {
            $this->json(['error' => "Daily story limit ($storyLimit) reached!"], 429);
        }

        $expiresAt = date('Y-m-d H:i:s', time() + (24 * 60 * 60)); // 24 hours

        $stmt = $this->db->prepare("INSERT INTO stories (user_id, type, content, media_url, expires_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())");
        $stmt->execute([$userId, $input['type'], $content, $mediaUrl, $expiresAt]);
        
        $this->json(['success' => true]);
    }

    public function delete($id) {
        $userId = AuthMiddleware::authenticate();

        // Soft delete: Update deleted_at instead of removing the row
        $stmt = $this->db->prepare("UPDATE stories SET deleted_at = NOW() WHERE id = ? AND user_id = ?");
        $stmt->execute([$id, $userId]);

        $this->json(['success' => true]);
    }

    public function comment($id) {
        $userId = AuthMiddleware::authenticate();
        $input = $this->input();
        
        $this->validate($input, ['content' => 'required']);
        
        $content = $input['content'];
        if (mb_strlen($content) > 155) {
            $this->json(['error' => 'Comment exceeds 155 characters limit.'], 400);
        }

        // Daily Comment Limit — Plus: 10, Normal: 3
        $stmtPlus = $this->db->prepare("SELECT is_plus_subscriber FROM users WHERE id = ?");
        $stmtPlus->execute([$userId]);
        $isPlus = (int)($stmtPlus->fetchColumn() ?: 0) === 1;
        $commentLimit = $isPlus ? 10 : 3;

        $stmtCount = $this->db->prepare("SELECT COUNT(*) FROM story_comments WHERE user_id = ? AND created_at >= CURDATE()");
        $stmtCount->execute([$userId]);
        $dailyComments = $stmtCount->fetchColumn();

        if ($dailyComments >= $commentLimit) {
            $this->json(['error' => "Daily comment limit ($commentLimit) reached!"], 429);
        }

        // Check if story exists
        $stmt = $this->db->prepare("SELECT id FROM stories WHERE id = ?");
        $stmt->execute([$id]);
        if (!$stmt->fetch()) {
            $this->json(['error' => 'Story not found'], 404);
        }

        $stmt = $this->db->prepare("INSERT INTO story_comments (story_id, user_id, content, created_at) VALUES (?, ?, ?, NOW())");
        $stmt->execute([$id, $userId, $content]);
        $commentId = $this->db->lastInsertId();

        // fetch created comment with user details
        $stmt = $this->db->prepare("
            SELECT c.*, u.username, u.display_name, u.avatar_url
            FROM story_comments c
            JOIN users u ON c.user_id = u.id
            WHERE c.id = ?
        ");
        $stmt->execute([$commentId]);
        $comment = $stmt->fetch(PDO::FETCH_ASSOC);

        $this->json($comment);
    }

    public function deleteComment($commentId) {
        $userId = AuthMiddleware::authenticate();

        // Allow delete if user is comment owner OR story owner
        $stmt = $this->db->prepare("
            SELECT c.user_id as comment_owner_id, s.user_id as story_owner_id
            FROM story_comments c
            JOIN stories s ON c.story_id = s.id
            WHERE c.id = ?
        ");
        $stmt->execute([$commentId]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$data) {
            $this->json(['error' => 'Comment not found'], 404);
        }

        if ($userId != $data['comment_owner_id'] && $userId != $data['story_owner_id']) {
            $this->json(['error' => 'Unauthorized'], 403);
        }

        $stmt = $this->db->prepare("DELETE FROM story_comments WHERE id = ?");
        $stmt->execute([$commentId]);

        $this->json(['success' => true]);
    }

    public function getUserStories($id) {
        AuthMiddleware::authenticate();

        $userId = (int)$id;

        $stmt = $this->db->prepare("
            SELECT s.*, u.username, u.display_name, u.avatar_url
            FROM stories s
            JOIN users u ON s.user_id = u.id
            WHERE s.user_id = ? AND s.expires_at > NOW() AND s.deleted_at IS NULL
            ORDER BY s.created_at DESC
        ");
        $stmt->execute([$userId]);
        $stories = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Fetch comments for each story (N+1 but minimal impact for limited stories)
        foreach ($stories as &$story) {
            // Count total comments
            $stmtCount = $this->db->prepare("SELECT COUNT(*) FROM story_comments WHERE story_id = ?");
            $stmtCount->execute([$story['id']]);
            $story['comment_count'] = (int)$stmtCount->fetchColumn();

            // Fetch latest 3 comments
            $stmtComments = $this->db->prepare("
                SELECT c.*, u.username, u.display_name, u.avatar_url
                FROM story_comments c
                JOIN users u ON c.user_id = u.id
                WHERE c.story_id = ?
                ORDER BY c.created_at DESC
                LIMIT 3
            ");
            $stmtComments->execute([$story['id']]);
            $story['latest_comments'] = array_reverse($stmtComments->fetchAll(PDO::FETCH_ASSOC));
        }

        $this->json($stories);
    }

    public function getComments($id) {
        AuthMiddleware::authenticate();

        $stmt = $this->db->prepare("
            SELECT c.*, u.username, u.display_name, u.avatar_url
            FROM story_comments c
            JOIN users u ON c.user_id = u.id
            WHERE c.story_id = ?
            ORDER BY c.created_at DESC
        ");
        $stmt->execute([$id]);
        $comments = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $this->json($comments);
    }
}
