<?php
function debugLog($message) {
    // 1. Create a file named 'debug.txt' in your backends folder
    $logFile = __DIR__ . '/debug.txt';
    
    // 2. Format the message with a timestamp
    $entry = date("Y-m-d H:i:s") . " - " . print_r($message, true) . PHP_EOL;
    
    // 3. Append it to the file
    file_put_contents($logFile, $entry, FILE_APPEND);
}

class Post {
    private $pdo;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    private function getBaseUrl() {
        //$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$protocol = "https://";
        $host = $_SERVER['HTTP_HOST'];
        // Assume uploads is at root/uploads
        // If index.php is in backend/, and uploads is backend/uploads.
        // And we access via http://host:port/uploads/file
        // If we serve via `php -S 0.0.0.0:5000`, root is backend/. So /uploads/ is correct.
        return $protocol . $host . '/backends' . '/uploads/';
    }

private function uploadFile() {
        // 1. Log what we received for debugging
        error_log("FILES array: " . print_r($_FILES, true));
        
        if (!isset($_FILES['image'])) {
            error_log("No 'image' key in FILES array");
            return null;
        }
        
        if ($_FILES['image']['error'] !== UPLOAD_ERR_OK) {
            error_log("Upload error code: " . $_FILES['image']['error']);
            return null;
        }

        // 2. FIX: Save to 'storage' folder (matching your index.php logic)
        $targetDir = __DIR__ . '/../storage/';
        
        // Create folder if it doesn't exist
        if (!file_exists($targetDir)) {
            if (!mkdir($targetDir, 0777, true)) {
                error_log("Failed to create storage directory");
                throw new Exception("Server Error: Cannot create storage directory");
            }
        }

        // 3. Generate secure filename
        $fileName = uniqid() . '_' . basename($_FILES['image']['name']);
        $targetFile = $targetDir . $fileName;

        // 4. Move file
        if (move_uploaded_file($_FILES['image']['tmp_name'], $targetFile)) {
            return $fileName;
        }
        throw new Exception("File upload failed");
    }

    public function create($userId, $data) {
        // Check daily post limit
        $config = require __DIR__ . '/../config/config.php';
        
        $stmtLimit = $this->pdo->prepare("SELECT posts_today, last_post_date FROM users WHERE id = ?");
        $stmtLimit->execute([$userId]);
        $limitData = $stmtLimit->fetch();
        
        $today = date('Y-m-d');
        $postsToday = $limitData['posts_today'];
        $lastPostDate = $limitData['last_post_date'];
        
        // Reset counter if it's a new day
        if ($lastPostDate !== $today) {
            $postsToday = 0;
        }
        
        // Check if limit reached
        if ($postsToday >= $config['daily_post_limit']) {
            throw new Exception("Daily post limit of {$config['daily_post_limit']} reached. Try again tomorrow.", 429);
        }
        
        // 1. Upload the file to /storage/
        $fileName = $this->uploadFile();
        if (!$fileName) throw new Exception("No File Selected!", 400);

        // 2. FIX: Construct the URL with '/uploads/' so .htaccess catches it
        // Result: http://site.com/backends/uploads/image.jpg
        $baseUrl = rtrim($this->getBaseUrl(), '/'); 
        $imageUrl = $baseUrl . '/uploads/' . $fileName;
        
        $message = $_POST['message'] ?? '';

        error_log(print_r($_POST, true)); // Log incoming data for debugging

        // Get encrypted keys
        $friendsPostKeys = $_POST['encryptedPostKeys'];
        $friendsPostKeysMap = json_decode($friendsPostKeys, true);

        $this->pdo->beginTransaction();
        try {
            // Insert Main Post
            $stmt = $this->pdo->prepare("INSERT INTO posts (sender_id, image_url, message) VALUES (?, ?, ?)");
            $stmt->execute([$userId, $imageUrl, $message]);
            $postId = $this->pdo->lastInsertId();

            // Insert Recipients
            // Note: Ensure your 'post_recipients' table actually has 'post_backup_blob' column
            $stmtRecip = $this->pdo->prepare("INSERT INTO post_recipients (post_id, recipient_id, post_backup_blob) VALUES (?, ?, ?)");
            
            foreach ($friendsPostKeysMap as $friendId => $postKey) {
                $stmtRecip->execute([$postId, $friendId, $postKey]);
            }
            
            // Update post counter
            $newCount = $postsToday + 1;
            $stmtUpdate = $this->pdo->prepare("UPDATE users SET posts_today = ?, last_post_date = ? WHERE id = ?");
            $stmtUpdate->execute([$newCount, $today, $userId]);
            
            $this->pdo->commit();
            
            return $this->getPostById($postId);

        } catch (Exception $e) {
            error_log("Error creating post: " . $e->getMessage());
            $this->pdo->rollBack();
            throw $e;
        }
    }
	
    public function getPostKey($userId, $postId) {
        $stmt = $this->pdo->prepare("SELECT post_backup_blob FROM post_recipients WHERE post_id = ? AND recipient_id = ?");
        $stmt->execute([$postId, $userId]);
        $data = $stmt->fetch();
        if (!$data) {
            throw new Exception("No access to this post's key", 403);
        }
        return ['backup_blob' => $data['post_backup_blob']];
    }

    public function getFeed($userId) {
        $stmt = $this->pdo->prepare("
            SELECT DISTINCT p.*, u.username as sender_name,
            (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count,
            (SELECT COUNT(*) FROM likes WHERE post_id = p.id AND user_id = ?) as is_liked
            FROM posts p
            JOIN users u ON p.sender_id = u.id
            LEFT JOIN post_recipients pr ON p.id = pr.post_id
            WHERE pr.recipient_id = ? OR p.sender_id = ?
            ORDER BY p.created_at DESC
            LIMIT 20
        ");
        $stmt->execute([$userId, $userId, $userId]);
        $rows = $stmt->fetchAll();
        $arr = array_map([$this, 'formatPost'], $rows);
        error_log("Fetched " . count($arr) . " posts for user $userId"); // Debugging line
        return $arr;
    }

    public function getLatest($userId) {
        $stmt = $this->pdo->prepare("
            SELECT DISTINCT p.*, u.username as sender_name,
            (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count,
            (SELECT COUNT(*) FROM likes WHERE post_id = p.id AND user_id = ?) as is_liked
            FROM posts p
            JOIN users u ON p.sender_id = u.id
            LEFT JOIN post_recipients pr ON p.id = pr.post_id
            WHERE pr.recipient_id = ? OR p.sender_id = ?
            ORDER BY p.created_at DESC
            LIMIT 1
        ");
        $stmt->execute([$userId, $userId, $userId]);
        $post = $stmt->fetch();
        if (!$post) return null;
        return $this->formatPost($post);
    }

    public function getLatestFromFriend($userId, $friendId) {
        // Verify friendship exists
        $checkFriend = $this->pdo->prepare("SELECT 1 FROM friendships WHERE user_id = ? AND friend_id = ? AND status = 'accepted'");
        $checkFriend->execute([$userId, $friendId]);
        if (!$checkFriend->fetch()) {
            throw new Exception("Not friends with this user", 403);
        }

        $stmt = $this->pdo->prepare("
            SELECT p.*, u.username as sender_name,
            (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count,
            (SELECT COUNT(*) FROM likes WHERE post_id = p.id AND user_id = ?) as is_liked
            FROM posts p
            JOIN users u ON p.sender_id = u.id
            WHERE p.sender_id = ?
            ORDER BY p.created_at DESC
            LIMIT 1
        ");
        $stmt->execute([$userId, $friendId]);
        $post = $stmt->fetch();
        if (!$post) return null;
        return $this->formatPost($post);
    }

    public function delete($userId, $postId) {
        $post = $this->getPostById($postId, $userId);
        if (!$post) throw new Exception("Post not found", 404);
        
        // Check ownership
        // Note: My formatPost returns string ID.
        if ($post['senderId'] != $userId) {
            throw new Exception("Not authorized", 401);
        }

        // Delete file
        $fileUrl = $post['imageUrl'];
        // extract filename
        // Assumes format: http://host/uploads/filename
        $parts = explode('/uploads/', $fileUrl);
        if (count($parts) > 1) {
            $localPath = __DIR__ . '/../uploads/' . $parts[1];
            if (file_exists($localPath)) {
                unlink($localPath);
            }
        }

        $stmt = $this->pdo->prepare("DELETE FROM posts WHERE id = ?");
        $stmt->execute([$postId]);
        return ["msg" => "Post removed"];
    }

    public function toggleLike($userId, $postId) {
        $check = $this->pdo->prepare("SELECT 1 FROM likes WHERE post_id = ? AND user_id = ?");
        $check->execute([$postId, $userId]);
        if ($check->fetch()) {
            // Unlike
            $stmt = $this->pdo->prepare("DELETE FROM likes WHERE post_id = ? AND user_id = ?");
            $stmt->execute([$postId, $userId]);
            $liked = false;
        } else {
            // Like
            $stmt = $this->pdo->prepare("INSERT INTO likes (post_id, user_id) VALUES (?, ?)");
            $stmt->execute([$postId, $userId]);
            $liked = true;
        }
        
        // Return updated counts
        $countStmt = $this->pdo->prepare("SELECT COUNT(*) FROM likes WHERE post_id = ?");
        $countStmt->execute([$postId]);
        $count = $countStmt->fetchColumn();
        
        return ['liked' => $liked, 'likes' => $count];
    }

    public function update($userId, $postId) {
        // ...existing code...
        // For update, I need to check post first.
        // getPostById now needs userId.
        
        $post = $this->getPostById($postId, $userId);
        if (!$post) throw new Exception("Post not found", 404);
        if ($post['senderId'] != $userId) throw new Exception("Not authorized", 401);

        $message = $_REQUEST['message'] ?? $post['message']; 
        
        // ...existing code...
        
        $newMessage = $message;
        $newImageUrl = $post['imageUrl'];
        
        // Check for file (only works if POST used or parsed)
        $newFile = $this->uploadFile();
        if ($newFile) {
            // Delete old
             $parts = explode('/uploads/', $post['imageUrl']);
            if (count($parts) > 1) {
                $localPath = __DIR__ . '/../uploads/' . $parts[1];
                if (file_exists($localPath)) unlink($localPath);
            }
            $newImageUrl = $this->getBaseUrl() . $newFile;
        }

        $stmt = $this->pdo->prepare("UPDATE posts SET message = ?, image_url = ? WHERE id = ?");
        $stmt->execute([$newMessage, $newImageUrl, $postId]);
        
        return $this->getPostById($postId, $userId);
    }

    private function getPostById($id, $userId = 0) {
        $stmt = $this->pdo->prepare("
            SELECT p.*, u.username as sender_name,
            (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count,
            (SELECT COUNT(*) FROM likes WHERE post_id = p.id AND user_id = ?) as is_liked
            FROM posts p
            JOIN users u ON p.sender_id = u.id
            WHERE p.id = ?
        ");
        $stmt->execute([$userId, $id]);
        $row = $stmt->fetch();
        if (!$row) return null;
        return $this->formatPost($row);
    }

    private function formatPost($row) {
        return [
            '_id' => (string)$row['id'],
            'sender' => [
                 '_id' => (string)$row['sender_id'],
                 'username' => $row['sender_name'] ?? 'Unknown',
                 'id' => (string)$row['sender_id']
            ],
            'senderId' => (string)$row['sender_id'],
            'imageUrl' => $row['image_url'],
            'message' => $row['message'],
            'createdAt' => $row['created_at'],
            'likeCount' => $row['like_count'] ?? 0,
            'isLiked' => (bool)($row['is_liked'] ?? false)
        ];
    }

    public function getRemainingPosts($userId) {
        $config = require __DIR__ . '/../config/config.php';
        
        $stmt = $this->pdo->prepare("SELECT posts_today, last_post_date FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $data = $stmt->fetch();
        
        $today = date('Y-m-d');
        $postsToday = ($data['last_post_date'] === $today) ? $data['posts_today'] : 0;
        $remaining = max(0, $config['daily_post_limit'] - $postsToday);
        
        return [
            'postsToday' => $postsToday,
            'dailyLimit' => $config['daily_post_limit'],
            'remaining' => $remaining
        ];
    }
}
